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

« back to all changes in this revision

Viewing changes to lib/common/makeuser.py

  • Committer: stevenbird
  • Date: 2008-02-19 21:17:21 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:512
Renaming of problems to exercises (initial commit).
Fix up module naming (exercises sometimes called tutorials).

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# IVLE - Informatics Virtual Learning Environment
 
2
# Copyright (C) 2007-2008 The University of Melbourne
 
3
#
 
4
# This program is free software; you can redistribute it and/or modify
 
5
# it under the terms of the GNU General Public License as published by
 
6
# the Free Software Foundation; either version 2 of the License, or
 
7
# (at your option) any later version.
 
8
#
 
9
# This program is distributed in the hope that it will be useful,
 
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
12
# GNU General Public License for more details.
 
13
#
 
14
# You should have received a copy of the GNU General Public License
 
15
# along with this program; if not, write to the Free Software
 
16
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 
17
 
 
18
# Module: MakeUser
 
19
# Author: Matt Giuca
 
20
# Date:   1/2/2008
 
21
 
 
22
# Allows creation of users. This sets up the following:
 
23
# * User's jail and home directory within the jail.
 
24
# * Subversion repository (TODO)
 
25
# * Check out Subversion workspace into jail (TODO)
 
26
# * Database details for user
 
27
# * Unix user account
 
28
 
 
29
# TODO: Sanitize login name and other fields.
 
30
# Users must not be called "temp" or "template".
 
31
 
 
32
# TODO: When creating a new home directory, chown it to its owner
 
33
 
 
34
import md5
 
35
import os
 
36
import stat
 
37
import shutil
 
38
import time
 
39
import uuid
 
40
import warnings
 
41
 
 
42
import conf
 
43
import db
 
44
 
 
45
def make_svn_repo(login):
 
46
    """Create a repository for the given user.
 
47
    """
 
48
    path = os.path.join(conf.svn_repo_path, login)
 
49
    res = os.system("svnadmin create '%s'" % path)
 
50
    if res != 0:
 
51
        raise Exception("Cannot create repository for %s" % login)
 
52
 
 
53
def rebuild_svn_config():
 
54
    """Build the complete SVN configuration file.
 
55
    """
 
56
    conn = db.DB()
 
57
    res = conn.query("SELECT login, rolenm FROM login;").dictresult()
 
58
    groups = {}
 
59
    for r in res:
 
60
        role = r['rolenm']
 
61
        if role not in groups:
 
62
            groups[role] = []
 
63
        groups[role].append(r['login'])
 
64
    f = open(conf.svn_conf + ".new", "w")
 
65
    f.write("# IVLE SVN Repositories Configuration\n")
 
66
    f.write("# Auto-generated on %s\n" % time.asctime())
 
67
    f.write("\n")
 
68
    f.write("[groups]\n")
 
69
    for (g,ls) in groups.iteritems():
 
70
        f.write("%s = %s\n" % (g, ",".join(ls)))
 
71
    f.write("\n")
 
72
    for r in res:
 
73
        login = r['login']
 
74
        f.write("[%s:/]\n" % login)
 
75
        f.write("%s = rw\n" % login)
 
76
        f.write("@tutor = r\n")
 
77
        f.write("@lecturer = rw\n")
 
78
        f.write("@admin = rw\n")
 
79
        f.write("\n")
 
80
    f.close()
 
81
    os.rename(conf.svn_conf + ".new", conf.svn_conf)
 
82
 
 
83
def make_svn_config(login):
 
84
    """Add an entry to the apache-svn config file for the given user.
 
85
       Assumes the given user is either a guest or a student.
 
86
    """
 
87
    f = open(conf.svn_conf, "a")
 
88
    f.write("[%s:/]\n" % login)
 
89
    f.write("%s = rw\n" % login)
 
90
    f.write("@tutor = r\n")
 
91
    f.write("@lecturer = rw\n")
 
92
    f.write("@admin = rw\n")
 
93
    f.write("\n")
 
94
    f.close()
 
95
 
 
96
def make_svn_auth(login):
 
97
    """Setup svn authentication for the given user.
 
98
       FIXME: create local.auth entry
 
99
    """
 
100
    passwd = md5.new(uuid.uuid4().bytes).digest().encode('hex')
 
101
    if os.path.exists(conf.svn_auth_ivle):
 
102
        create = ""
 
103
    else:
 
104
        create = "c"
 
105
 
 
106
    db.DB().update_user({'svn_pass':passwd})
 
107
 
 
108
    res = os.system("htpasswd -%smb %s %s" % (create,
 
109
                                              conf.svn_auth_ivle,
 
110
                                              login, passwd))
 
111
    if res != 0:
 
112
        raise Exception("Unable to create ivle-auth for %s" % login)
 
113
 
 
114
def make_jail(username, uid, force=True):
 
115
    """Creates a new user's jail space, in the jail directory as configured in
 
116
    conf.py.
 
117
 
 
118
    This expects there to be a "template" directory within the jail root which
 
119
    contains all the files for a sample student jail. It creates the student's
 
120
    directory in the jail root, by making a hard-link copy of every file in the
 
121
    template directory, recursively.
 
122
 
 
123
    Returns the path to the user's home directory.
 
124
 
 
125
    Chowns the user's directory within the jail to the given UID.
 
126
 
 
127
    Note: This takes separate username and uid arguments. The UID need not
 
128
    *necessarily* correspond to a Unix username at all, if all you are
 
129
    planning to do is setuid to it. This allows the caller the freedom of
 
130
    deciding the binding between username and uid, if any.
 
131
 
 
132
    force: If false, exception if jail already exists for this user.
 
133
    If true (default), overwrites it, but preserves home directory.
 
134
    """
 
135
    # MUST run as root or some of this may fail
 
136
    if os.getuid() != 0:
 
137
        raise Exception("Must run make_jail as root")
 
138
    
 
139
    templatedir = os.path.join(conf.jail_base, 'template')
 
140
    if not os.path.isdir(templatedir):
 
141
        raise Exception("Template jail directory does not exist: " +
 
142
            templatedir)
 
143
    # tempdir is for putting backup homes in
 
144
    tempdir = os.path.join(conf.jail_base, 'temp')
 
145
    if not os.path.exists(tempdir):
 
146
        os.makedirs(tempdir)
 
147
    elif not os.path.isdir(tempdir):
 
148
        os.unlink(tempdir)
 
149
        os.mkdir(tempdir)
 
150
    userdir = os.path.join(conf.jail_base, username)
 
151
    homedir = os.path.join(userdir, 'home')
 
152
 
 
153
    if os.path.exists(userdir):
 
154
        if not force:
 
155
            raise Exception("User's jail already exists")
 
156
        # User jail already exists. Blow it away but preserve their home
 
157
        # directory.
 
158
        # Ignore warnings about the use of tmpnam
 
159
        warnings.simplefilter('ignore')
 
160
        homebackup = os.tempnam(tempdir)
 
161
        warnings.resetwarnings()
 
162
        # Note: shutil.move does not behave like "mv" - it does not put a file
 
163
        # into a directory if it already exists, just fails. Therefore it is
 
164
        # not susceptible to tmpnam symlink attack.
 
165
        shutil.move(homedir, homebackup)
 
166
        try:
 
167
            # Any errors that occur after making the backup will be caught and
 
168
            # the backup will be un-made.
 
169
            # XXX This will still leave the user's jail in an unusable state,
 
170
            # but at least they won't lose their files.
 
171
            shutil.rmtree(userdir)
 
172
 
 
173
            # Hard-link (copy aliasing) the entire tree over
 
174
            linktree(templatedir, userdir)
 
175
        finally:
 
176
            # Set up the user's home directory (restore backup)
 
177
            # First make sure the directory is empty and its parent exists
 
178
            try:
 
179
                shutil.rmtree(homedir)
 
180
            except:
 
181
                pass
 
182
            # XXX If this fails the user's directory will be lost (in the temp
 
183
            # directory). But it shouldn't fail as homedir should not exist.
 
184
            os.makedirs(homedir)
 
185
            shutil.move(homebackup, homedir)
 
186
        return os.path.join(homedir, username)
 
187
    else:
 
188
        # No user jail exists
 
189
        # Hard-link (copy aliasing) the entire tree over
 
190
        linktree(templatedir, userdir)
 
191
 
 
192
        # Set up the user's home directory
 
193
        userhomedir = os.path.join(homedir, username)
 
194
        os.mkdir(userhomedir)
 
195
        # Chown (and set the GID to the same as the UID).
 
196
        os.chown(userhomedir, uid, uid)
 
197
        # Chmod to rwxr-xr-x (755)
 
198
        os.chmod(userhomedir, 0755)
 
199
        return userhomedir
 
200
 
 
201
def linktree(src, dst):
 
202
    """Recursively hard-link a directory tree using os.link().
 
203
 
 
204
    The destination directory must not already exist.
 
205
    If exception(s) occur, an Error is raised with a list of reasons.
 
206
 
 
207
    Symlinks are preserved (in fact, hard links are created which point to the
 
208
    symlinks).
 
209
 
 
210
    Code heavily based upon shutil.copytree from Python 2.5 library.
 
211
    """
 
212
    names = os.listdir(src)
 
213
    os.makedirs(dst)
 
214
    errors = []
 
215
    for name in names:
 
216
        srcname = os.path.join(src, name)
 
217
        dstname = os.path.join(dst, name)
 
218
        try:
 
219
            if os.path.isdir(srcname):
 
220
                linktree(srcname, dstname)
 
221
            else:
 
222
                os.link(srcname, dstname)
 
223
            # XXX What about devices, sockets etc.?
 
224
        except (IOError, os.error), why:
 
225
            errors.append((srcname, dstname, str(why)))
 
226
        # catch the Error from the recursive copytree so that we can
 
227
        # continue with other files
 
228
        except Exception, err:
 
229
            errors.append(err.args[0])
 
230
    try:
 
231
        shutil.copystat(src, dst)
 
232
    except WindowsError:
 
233
        # can't copy file access times on Windows
 
234
        pass
 
235
    except OSError, why:
 
236
        errors.extend((src, dst, str(why)))
 
237
    if errors:
 
238
        raise Exception, errors
 
239
 
 
240
def make_user_db(**kwargs):
 
241
    """Creates a user's entry in the database, filling in all the fields.
 
242
    All arguments must be keyword args. They are the fields in the table.
 
243
    However, instead of supplying a "passhash", you must supply a
 
244
    "password" argument, which will be hashed internally.
 
245
    Also do not supply a state. All users are created in the "no_agreement"
 
246
    state.
 
247
    Throws an exception if the user already exists.
 
248
    """
 
249
    dbconn = db.DB()
 
250
    dbconn.create_user(**kwargs)
 
251
    dbconn.close()