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

« back to all changes in this revision

Viewing changes to lib/common/makeuser.py

  • Committer: mattgiuca
  • Date: 2008-02-15 03:40:10 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:469
db.py: Changed interface (again) to user management methods: Changed the dict
argument to **kwargs.
(Did not do this for the low-level db methods, as all accesses to them should
just be passing a dict anyway).

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