~azzar1/unity/add-show-desktop-key

« back to all changes in this revision

Viewing changes to ivle/makeuser.py

  • Committer: William Grant
  • Date: 2009-01-22 04:47:42 UTC
  • mfrom: (1080.1.93 storm)
  • Revision ID: grantw@unimelb.edu.au-20090122044742-sa8gnww0ma2bm2rv
Merge Storm branch. ivle.db is dead. Watch out for the schema change.

Show diffs side-by-side

added added

removed removed

Lines of Context:
45
45
import filecmp
46
46
import logging
47
47
import ivle.conf
48
 
import ivle.db
49
48
import ivle.pulldown_subj
50
49
 
 
50
from ivle.database import ProjectGroup
 
51
 
51
52
def chown_to_webserver(filename):
52
53
    """
53
54
    Chowns a file so the web server user owns it.
73
74
 
74
75
    chown_to_webserver(path)
75
76
 
76
 
def rebuild_svn_config():
 
77
def rebuild_svn_config(store):
77
78
    """Build the complete SVN configuration file.
78
79
    """
79
 
    conn = ivle.db.DB()
80
 
    users = conn.get_users()
 
80
    users = store.find(ivle.database.User)
81
81
    groups = {}
82
82
    for u in users:
83
83
        role = str(u.role)
103
103
    os.rename(ivle.conf.svn_conf + ".new", ivle.conf.svn_conf)
104
104
    chown_to_webserver(ivle.conf.svn_conf)
105
105
 
106
 
def rebuild_svn_group_config():
 
106
def rebuild_svn_group_config(store):
107
107
    """Build the complete SVN configuration file for groups
108
108
    """
109
 
    conn = ivle.db.DB()
110
 
    groups = conn.get_all('project_group',
111
 
        ['groupid', 'groupnm', 'projectsetid'])
112
109
    f = open(ivle.conf.svn_group_conf + ".new", "w")
113
110
    f.write("# IVLE SVN Group Repositories Configuration\n")
114
111
    f.write("# Auto-generated on %s\n" % time.asctime())
115
112
    f.write("\n")
116
 
    for g in groups:
117
 
        projectsetid = g['projectsetid']
118
 
        offeringinfo = conn.get_offering_info(projectsetid)
119
 
        subj_short_name = offeringinfo['subj_short_name']
120
 
        year = offeringinfo['year']
121
 
        semester = offeringinfo['semester']
122
 
        reponame = "_".join([subj_short_name, year, semester, g['groupnm']])
 
113
    for group in store.find(ProjectGroup):
 
114
        offering = group.project_set.offering
 
115
        reponame = "_".join([offering.subject.short_name,
 
116
                             offering.semester.year,
 
117
                             offering.semester.semester,
 
118
                             group.name])
123
119
        f.write("[%s:/]\n"%reponame)
124
 
        users = conn.get_projectgroup_members(g['groupid'])
125
 
        for u in users:
126
 
            f.write("%s = rw\n"%u['login'])
 
120
        for user in group.members:
 
121
            f.write("%s = rw\n" % user.login)
127
122
        f.write("\n")
128
123
    f.close()
129
124
    os.rename(ivle.conf.svn_group_conf + ".new", ivle.conf.svn_group_conf)
130
125
    chown_to_webserver(ivle.conf.svn_group_conf)
131
126
 
132
 
def make_svn_auth(login, throw_on_error=True):
 
127
def make_svn_auth(store, login, throw_on_error=True):
133
128
    """Setup svn authentication for the given user.
134
 
       FIXME: create local.auth entry
 
129
       Uses the given DB store object. Does not commit to the db.
135
130
    """
136
131
    passwd = md5.new(uuid.uuid4().bytes).digest().encode('hex')
137
132
    if os.path.exists(ivle.conf.svn_auth_ivle):
139
134
    else:
140
135
        create = "c"
141
136
 
142
 
    ivle.db.DB().update_user(login, svn_pass=passwd)
 
137
    user = ivle.database.User.get_by_login(store, login)
 
138
    user.svn_pass = unicode(passwd)
143
139
 
144
140
    res = os.system("htpasswd -%smb %s %s %s" % (create,
145
141
                                              ivle.conf.svn_auth_ivle,
182
178
    return (to_add, to_remove)
183
179
 
184
180
 
185
 
def make_jail(username, uid, force=True, svn_pass=None):
 
181
def make_jail(user, force=True):
186
182
    """Creates a new user's jail space, in the jail directory as configured in
187
183
    conf.py.
188
184
 
193
189
 
194
190
    Chowns the user's directory within the jail to the given UID.
195
191
 
196
 
    Note: This takes separate username and uid arguments. The UID need not
197
 
    *necessarily* correspond to a Unix username at all, if all you are
198
 
    planning to do is setuid to it. This allows the caller the freedom of
199
 
    deciding the binding between username and uid, if any.
200
 
 
201
192
    force: If false, exception if jail already exists for this user.
202
193
    If true (default), overwrites it, but preserves home directory.
203
 
 
204
 
    svn_pass: If provided this will be a string, the randomly-generated
205
 
    Subversion password for this user (if you happen to already have it).
206
 
    If not provided, it will be read from the database.
207
194
    """
208
195
    # MUST run as root or some of this may fail
209
196
    if os.getuid() != 0:
216
203
    elif not os.path.isdir(tempdir):
217
204
        os.unlink(tempdir)
218
205
        os.mkdir(tempdir)
219
 
    userdir = os.path.join(ivle.conf.jail_src_base, username)
 
206
    userdir = os.path.join(ivle.conf.jail_src_base, user.login)
220
207
    homedir = os.path.join(userdir, 'home')
221
 
    userhomedir = os.path.join(homedir, username)   # Return value
 
208
    userhomedir = os.path.join(homedir, user.login)   # Return value
222
209
 
223
210
    if os.path.exists(userdir):
224
211
        if not force:
239
226
        shutil.move(homebackup, homedir)
240
227
        # Change the ownership of all the files to the right unixid
241
228
        logging.debug("chown %s's home directory files to uid %d"
242
 
            %(username, uid))
243
 
        os.chown(userhomedir, uid, uid)
 
229
            %(user.login, user.unixid))
 
230
        os.chown(userhomedir, user.unixid, user.unixid)
244
231
        for root, dirs, files in os.walk(userhomedir):
245
232
            for fsobj in dirs + files:
246
 
                os.chown(os.path.join(root, fsobj), uid, uid)
 
233
                os.chown(os.path.join(root, fsobj), user.unixid, user.unixid)
247
234
    else:
248
235
        # No user jail exists
249
236
        # Set up the user's home directory
250
237
        os.makedirs(userhomedir)
251
238
        # Chown (and set the GID to the same as the UID).
252
 
        os.chown(userhomedir, uid, uid)
 
239
        os.chown(userhomedir, user.unixid, user.unixid)
253
240
        # Chmod to rwxr-xr-x (755)
254
241
        os.chmod(userhomedir, 0755)
255
242
 
256
 
    # There are 2 special files which need to be generated specific to this
257
 
    # user: ${python_site_packages}/lib/conf/conf.py and /etc/passwd.
258
 
    # "__" username "__" users are exempt (special)
259
 
    if not (username.startswith("__") and username.endswith("__")):
260
 
        make_conf_py(username, userdir, ivle.conf.jail_system, svn_pass)
261
 
        make_etc_passwd(username, userdir, ivle.conf.jail_system, uid)
 
243
    make_conf_py(user.login, userdir, ivle.conf.jail_system, user.svn_pass)
 
244
    make_etc_passwd(user.login, userdir, ivle.conf.jail_system, user.unixid)
262
245
 
263
246
    return userhomedir
264
247
 
265
 
def make_conf_py(username, user_jail_dir, staging_dir, svn_pass=None):
 
248
def make_conf_py(username, user_jail_dir, staging_dir, svn_pass):
266
249
    """
267
250
    Creates (overwriting any existing file, and creating directories) a
268
251
    file ${python_site_packages}/ivle/conf/conf.py in a given user's jail.
279
262
            ivle.conf.python_site_packages[1:], "ivle/conf/conf.py")
280
263
    os.makedirs(os.path.dirname(conf_path))
281
264
 
282
 
    # If svn_pass isn't supplied, grab it from the DB
283
 
    if svn_pass is None:
284
 
        dbconn = ivle.db.DB()
285
 
        svn_pass = dbconn.get_user(username).svn_pass
286
 
        dbconn.close()
287
 
 
288
265
    # Read the contents of the template conf file
289
266
    try:
290
267
        template_conf_file = open(template_conf_path, "r")
327
304
                      % (username, unixid, unixid, username))
328
305
    passwd_file.close()
329
306
 
330
 
def make_user_db(throw_on_error = True, **kwargs):
331
 
    """Creates a user's entry in the database, filling in all the fields.
332
 
    All arguments must be keyword args. They are the fields in the table.
333
 
    However, instead of supplying a "passhash", you must supply a
334
 
    "password" argument, which will be hashed internally.
335
 
    Also do not supply a state. All users are created in the "no_agreement"
336
 
    state.
337
 
    Also pulls the user's subjects using the configured subject pulldown
338
 
    module, and adds enrolments to the DB.
339
 
    Throws an exception if the user already exists.
340
 
    """
341
 
    dbconn = ivle.db.DB()
342
 
    dbconn.create_user(**kwargs)
343
 
    dbconn.close()
344
 
 
345
 
    if kwargs['password']:
346
 
        if os.path.exists(ivle.conf.svn_auth_local):
347
 
            create = ""
348
 
        else:
349
 
            create = "c"
350
 
        res = os.system("htpasswd -%smb %s %s %s" % (create,
351
 
                                                     ivle.conf.svn_auth_local,
352
 
                                                     kwargs['login'],
353
 
                                                     kwargs['password']))
354
 
        if res != 0 and throw_on_error:
355
 
            raise Exception("Unable to create local-auth for %s" % kwargs['login'])
356
 
 
357
 
    # Make sure the file is owned by the web server
358
 
    if create == "c":
359
 
        chown_to_webserver(ivle.conf.svn_auth_local)
360
 
 
361
 
    # Pulldown subjects and add enrolments
362
 
    ivle.pulldown_subj.enrol_user(kwargs['login'])
363
 
 
364
307
def mount_jail(login):
365
308
    # This is where we'll mount to...
366
309
    destdir = os.path.join(ivle.conf.jail_base, login)