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

« back to all changes in this revision

Viewing changes to lib/common/makeuser.py

  • Committer: drtomc
  • Date: 2008-02-20 22:09:25 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:525
A sample apache config containing both ivle and svn configuration.

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, throw_on_error=True):
 
46
    """Create a repository for the given user.
 
47
    """
 
48
    path = os.path.join(conf.svn_repo_path, login)
 
49
    try:
 
50
        res = os.system("svnadmin create '%s'" % path)
 
51
        if res != 0 and throw_on_error:
 
52
            raise Exception("Cannot create repository for %s" % login)
 
53
    except Exception, exc:
 
54
        print repr(exc)
 
55
        if throw_on_error:
 
56
            raise
 
57
 
 
58
def rebuild_svn_config():
 
59
    """Build the complete SVN configuration file.
 
60
    """
 
61
    conn = db.DB()
 
62
    res = conn.query("SELECT login, rolenm FROM login;").dictresult()
 
63
    groups = {}
 
64
    for r in res:
 
65
        role = r['rolenm']
 
66
        if role not in groups:
 
67
            groups[role] = []
 
68
        groups[role].append(r['login'])
 
69
    f = open(conf.svn_conf + ".new", "w")
 
70
    f.write("# IVLE SVN Repositories Configuration\n")
 
71
    f.write("# Auto-generated on %s\n" % time.asctime())
 
72
    f.write("\n")
 
73
    f.write("[groups]\n")
 
74
    for (g,ls) in groups.iteritems():
 
75
        f.write("%s = %s\n" % (g, ",".join(ls)))
 
76
    f.write("\n")
 
77
    for r in res:
 
78
        login = r['login']
 
79
        f.write("[%s:/]\n" % login)
 
80
        f.write("%s = rw\n" % login)
 
81
        #f.write("@tutor = r\n")
 
82
        #f.write("@lecturer = rw\n")
 
83
        #f.write("@admin = rw\n")
 
84
        f.write("\n")
 
85
    f.close()
 
86
    os.rename(conf.svn_conf + ".new", conf.svn_conf)
 
87
 
 
88
def make_svn_config(login, throw_on_error=True):
 
89
    """Add an entry to the apache-svn config file for the given user.
 
90
       Assumes the given user is either a guest or a student.
 
91
    """
 
92
    f = open(conf.svn_conf, "a")
 
93
    f.write("[%s:/]\n" % login)
 
94
    f.write("%s = rw\n" % login)
 
95
    #f.write("@tutor = r\n")
 
96
    #f.write("@lecturer = rw\n")
 
97
    #f.write("@admin = rw\n")
 
98
    f.write("\n")
 
99
    f.close()
 
100
 
 
101
def make_svn_auth(login, throw_on_error=True):
 
102
    """Setup svn authentication for the given user.
 
103
       FIXME: create local.auth entry
 
104
    """
 
105
    passwd = md5.new(uuid.uuid4().bytes).digest().encode('hex')
 
106
    if os.path.exists(conf.svn_auth_ivle):
 
107
        create = ""
 
108
    else:
 
109
        create = "c"
 
110
 
 
111
    db.DB().update_user(login, svn_pass=passwd)
 
112
 
 
113
    res = os.system("htpasswd -%smb %s %s %s" % (create,
 
114
                                              conf.svn_auth_ivle,
 
115
                                              login, passwd))
 
116
    if res != 0 and throw_on_error:
 
117
        raise Exception("Unable to create ivle-auth for %s" % login)
 
118
 
 
119
    return passwd
 
120
 
 
121
def make_jail(username, uid, force=True):
 
122
    """Creates a new user's jail space, in the jail directory as configured in
 
123
    conf.py.
 
124
 
 
125
    This expects there to be a "template" directory within the jail root which
 
126
    contains all the files for a sample student jail. It creates the student's
 
127
    directory in the jail root, by making a hard-link copy of every file in the
 
128
    template directory, recursively.
 
129
 
 
130
    Returns the path to the user's home directory.
 
131
 
 
132
    Chowns the user's directory within the jail to the given UID.
 
133
 
 
134
    Note: This takes separate username and uid arguments. The UID need not
 
135
    *necessarily* correspond to a Unix username at all, if all you are
 
136
    planning to do is setuid to it. This allows the caller the freedom of
 
137
    deciding the binding between username and uid, if any.
 
138
 
 
139
    force: If false, exception if jail already exists for this user.
 
140
    If true (default), overwrites it, but preserves home directory.
 
141
    """
 
142
    # MUST run as root or some of this may fail
 
143
    if os.getuid() != 0:
 
144
        raise Exception("Must run make_jail as root")
 
145
    
 
146
    templatedir = os.path.join(conf.jail_base, 'template')
 
147
    if not os.path.isdir(templatedir):
 
148
        raise Exception("Template jail directory does not exist: " +
 
149
            templatedir)
 
150
    # tempdir is for putting backup homes in
 
151
    tempdir = os.path.join(conf.jail_base, 'temp')
 
152
    if not os.path.exists(tempdir):
 
153
        os.makedirs(tempdir)
 
154
    elif not os.path.isdir(tempdir):
 
155
        os.unlink(tempdir)
 
156
        os.mkdir(tempdir)
 
157
    userdir = os.path.join(conf.jail_base, username)
 
158
    homedir = os.path.join(userdir, 'home')
 
159
 
 
160
    if os.path.exists(userdir):
 
161
        if not force:
 
162
            raise Exception("User's jail already exists")
 
163
        # User jail already exists. Blow it away but preserve their home
 
164
        # directory.
 
165
        # Ignore warnings about the use of tmpnam
 
166
        warnings.simplefilter('ignore')
 
167
        homebackup = os.tempnam(tempdir)
 
168
        warnings.resetwarnings()
 
169
        # Note: shutil.move does not behave like "mv" - it does not put a file
 
170
        # into a directory if it already exists, just fails. Therefore it is
 
171
        # not susceptible to tmpnam symlink attack.
 
172
        shutil.move(homedir, homebackup)
 
173
        try:
 
174
            # Any errors that occur after making the backup will be caught and
 
175
            # the backup will be un-made.
 
176
            # XXX This will still leave the user's jail in an unusable state,
 
177
            # but at least they won't lose their files.
 
178
            shutil.rmtree(userdir)
 
179
 
 
180
            # Hard-link (copy aliasing) the entire tree over
 
181
            linktree(templatedir, userdir)
 
182
        finally:
 
183
            # Set up the user's home directory (restore backup)
 
184
            # First make sure the directory is empty and its parent exists
 
185
            try:
 
186
                shutil.rmtree(homedir)
 
187
            except:
 
188
                pass
 
189
            # XXX If this fails the user's directory will be lost (in the temp
 
190
            # directory). But it shouldn't fail as homedir should not exist.
 
191
            os.makedirs(homedir)
 
192
            shutil.move(homebackup, homedir)
 
193
        return os.path.join(homedir, username)
 
194
    else:
 
195
        # No user jail exists
 
196
        # Hard-link (copy aliasing) the entire tree over
 
197
        linktree(templatedir, userdir)
 
198
 
 
199
        # Set up the user's home directory
 
200
        userhomedir = os.path.join(homedir, username)
 
201
        os.mkdir(userhomedir)
 
202
        # Chown (and set the GID to the same as the UID).
 
203
        os.chown(userhomedir, uid, uid)
 
204
        # Chmod to rwxr-xr-x (755)
 
205
        os.chmod(userhomedir, 0755)
 
206
        return userhomedir
 
207
 
 
208
def linktree(src, dst):
 
209
    """Recursively hard-link a directory tree using os.link().
 
210
 
 
211
    The destination directory must not already exist.
 
212
    If exception(s) occur, an Error is raised with a list of reasons.
 
213
 
 
214
    Symlinks are preserved (in fact, hard links are created which point to the
 
215
    symlinks).
 
216
 
 
217
    Code heavily based upon shutil.copytree from Python 2.5 library.
 
218
    """
 
219
    names = os.listdir(src)
 
220
    os.makedirs(dst)
 
221
    errors = []
 
222
    for name in names:
 
223
        srcname = os.path.join(src, name)
 
224
        dstname = os.path.join(dst, name)
 
225
        try:
 
226
            if os.path.isdir(srcname):
 
227
                linktree(srcname, dstname)
 
228
            else:
 
229
                os.link(srcname, dstname)
 
230
            # XXX What about devices, sockets etc.?
 
231
        except (IOError, os.error), why:
 
232
            errors.append((srcname, dstname, str(why)))
 
233
        # catch the Error from the recursive copytree so that we can
 
234
        # continue with other files
 
235
        except Exception, err:
 
236
            errors.append(err.args[0])
 
237
    try:
 
238
        shutil.copystat(src, dst)
 
239
    except WindowsError:
 
240
        # can't copy file access times on Windows
 
241
        pass
 
242
    except OSError, why:
 
243
        errors.extend((src, dst, str(why)))
 
244
    if errors:
 
245
        raise Exception, errors
 
246
 
 
247
def make_user_db(**kwargs):
 
248
    """Creates a user's entry in the database, filling in all the fields.
 
249
    All arguments must be keyword args. They are the fields in the table.
 
250
    However, instead of supplying a "passhash", you must supply a
 
251
    "password" argument, which will be hashed internally.
 
252
    Also do not supply a state. All users are created in the "no_agreement"
 
253
    state.
 
254
    Throws an exception if the user already exists.
 
255
    """
 
256
    dbconn = db.DB()
 
257
    dbconn.create_user(**kwargs)
 
258
    dbconn.close()