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

« back to all changes in this revision

Viewing changes to lib/common/db.py

  • Committer: mattgiuca
  • Date: 2008-02-21 05:03:21 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:529
setup.py: Fixed copytree; now able to handle copying a directory over itself
(just does nothing).
usrmgt-server: Fixed all the commented out prints, replacing them with calls
to a "log" function which is configurable as to whether it prints or not.
makeuser.py: Removed the creation of jails.
    Now it creates a unix account, and a database entry.
    It *shouldn't* be creating a unix account still. (?)

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: Database
 
19
# Author: Matt Giuca
 
20
# Date:   15/2/2008
 
21
 
 
22
# Code to talk to the PostgreSQL database.
 
23
# (This is the Data Access Layer).
 
24
# All DB code should be in this module to ensure portability if we want to
 
25
# change the DB implementation.
 
26
# This means no SQL strings should be outside of this module. Add functions
 
27
# here to perform the activities needed, and place the SQL code for those
 
28
# activities within.
 
29
 
 
30
# CAUTION to editors of this module.
 
31
# All string inputs must be sanitized by calling _escape before being
 
32
# formatted into an SQL query string.
 
33
 
 
34
import pg
 
35
import conf
 
36
import md5
 
37
import copy
 
38
 
 
39
from common import (caps, user)
 
40
 
 
41
def _escape(val):
 
42
    """Wrapper around pg.escape_string. Prepares the Python value for use in
 
43
    SQL. Returns a string, which may be safely placed verbatim into an SQL
 
44
    query.
 
45
    Handles the following types:
 
46
    * str: Escapes the string, and also quotes it.
 
47
    * int/long/float: Just converts to an unquoted string.
 
48
    * bool: Returns as "TRUE" or "FALSE", unquoted.
 
49
    * NoneType: Returns "NULL", unquoted.
 
50
    * common.caps.Role: Returns the role as a quoted, lowercase string.
 
51
    Raises a DBException if val has an unsupported type.
 
52
    """
 
53
    # "E'" is postgres's way of making "escape" strings.
 
54
    # Such strings allow backslashes to escape things. Since escape_string
 
55
    # converts a single backslash into two backslashes, it needs to be fed
 
56
    # into E mode.
 
57
    # Ref: http://www.postgresql.org/docs/8.2/static/sql-syntax-lexical.html
 
58
    # WARNING: PostgreSQL-specific code
 
59
    if val is None:
 
60
        return "NULL"
 
61
    elif isinstance(val, str):
 
62
        return "E'" + pg.escape_string(val) + "'"
 
63
    elif isinstance(val, bool):
 
64
        return "TRUE" if val else "FALSE"
 
65
    elif isinstance(val, int) or isinstance(val, long) \
 
66
        or isinstance(val, float):
 
67
        return str(val)
 
68
    elif isinstance(val, caps.Role):
 
69
        return _escape(str(val))
 
70
    else:
 
71
        raise DBException("Attempt to insert an unsupported type "
 
72
            "into the database")
 
73
 
 
74
def _passhash(password):
 
75
    return md5.md5(password).hexdigest()
 
76
 
 
77
class DBException(Exception):
 
78
    """A DBException is for bad conditions in the database or bad input to
 
79
    these methods. If Postgres throws an exception it does not get rebadged.
 
80
    This is only for additional exceptions."""
 
81
    pass
 
82
 
 
83
class DB:
 
84
    """An IVLE database object. This object provides an interface to
 
85
    interacting with the IVLE database without using any external SQL.
 
86
 
 
87
    Most methods of this class have an optional dry argument. If true, they
 
88
    will return the SQL query string and NOT actually execute it. (For
 
89
    debugging purposes).
 
90
 
 
91
    Methods may throw db.DBException, or any of the pg exceptions as well.
 
92
    (In general, be prepared to catch exceptions!)
 
93
    """
 
94
    def __init__(self):
 
95
        """Connects to the database and creates a DB object.
 
96
        Takes no parameters - gets all the DB info from the configuration."""
 
97
        self.open = False
 
98
        self.db = pg.connect(dbname=conf.db_dbname, host=conf.db_host,
 
99
                port=conf.db_port, user=conf.db_user, passwd=conf.db_password)
 
100
        self.open = True
 
101
 
 
102
    def __del__(self):
 
103
        if self.open:
 
104
            self.db.close()
 
105
 
 
106
    # GENERIC DB FUNCTIONS #
 
107
 
 
108
    @staticmethod
 
109
    def check_dict(dict, tablefields, disallowed=frozenset([]), must=False):
 
110
        """Checks that a dict does not contain keys that are not fields
 
111
        of the specified table.
 
112
        dict: A mapping from string keys to values; the keys are checked to
 
113
            see that they correspond to login table fields.
 
114
        tablefields: Collection of strings for field names in the table.
 
115
            Only these fields will be allowed.
 
116
        disallowed: Optional collection of strings for field names that are
 
117
            not allowed.
 
118
        must: If True, the dict MUST contain all fields in tablefields.
 
119
            If False, it may contain any subset of the fields.
 
120
        Returns True if the dict is valid, False otherwise.
 
121
        """
 
122
        allowed = frozenset(tablefields) - frozenset(disallowed)
 
123
        dictkeys = frozenset(dict.keys())
 
124
        if must:
 
125
            return allowed == dictkeys
 
126
        else:
 
127
            return allowed.issuperset(dictkeys)
 
128
 
 
129
    def insert(self, dict, tablename, tablefields, disallowed=frozenset([]),
 
130
        dry=False):
 
131
        """Inserts a new row in a table, using data from a supplied
 
132
        dictionary (which will be checked by check_dict).
 
133
        dict: Dictionary mapping column names to values. The values may be
 
134
            any of the following types:
 
135
            str, int, long, float, NoneType.
 
136
        tablename: String, name of the table to insert into. Will NOT be
 
137
            escaped - must be a valid identifier.
 
138
        tablefields, disallowed: see check_dict.
 
139
        dry: Returns the SQL query as a string, and does not execute it.
 
140
        Raises a DBException if the dictionary contains invalid fields.
 
141
        """
 
142
        if not DB.check_dict(dict, tablefields, disallowed):
 
143
            raise DBException("Supplied dictionary contains invalid fields.")
 
144
        # Build two lists concurrently: field names and values, as SQL strings
 
145
        fieldnames = []
 
146
        values = []
 
147
        for k,v in dict.items():
 
148
            fieldnames.append(k)
 
149
            values.append(_escape(v))
 
150
        if len(fieldnames) == 0: return
 
151
        fieldnames = ', '.join(fieldnames)
 
152
        values = ', '.join(values)
 
153
        query = ("INSERT INTO %s (%s) VALUES (%s);"
 
154
            % (tablename, fieldnames, values))
 
155
        if dry: return query
 
156
        self.db.query(query)
 
157
 
 
158
    def update(self, primarydict, updatedict, tablename, tablefields,
 
159
        primary_keys, disallowed_update=frozenset([]), dry=False):
 
160
        """Updates a row in a table, matching against primarydict to find the
 
161
        row, and using the data in updatedict (which will be checked by
 
162
        check_dict).
 
163
        primarydict: Dict mapping column names to values. The keys should be
 
164
            the table's primary key. Only rows which match this dict's values
 
165
            will be updated.
 
166
        updatedict: Dict mapping column names to values. The columns will be
 
167
            updated with the given values for the matched rows.
 
168
        tablename, tablefields, disallowed_update: See insert.
 
169
        primary_keys: Collection of strings which together form the primary
 
170
            key for this table. primarydict must contain all of these as keys,
 
171
            and only these keys.
 
172
        """
 
173
        if (not (DB.check_dict(primarydict, primary_keys, must=True)
 
174
            and DB.check_dict(updatedict, tablefields, disallowed_update))):
 
175
            raise DBException("Supplied dictionary contains invalid or missing fields (1).")
 
176
        # Make a list of SQL fragments of the form "field = 'new value'"
 
177
        # These fragments are ALREADY-ESCAPED
 
178
        setlist = []
 
179
        for k,v in updatedict.items():
 
180
            setlist.append("%s = %s" % (k, _escape(v)))
 
181
        wherelist = []
 
182
        for k,v in primarydict.items():
 
183
            wherelist.append("%s = %s" % (k, _escape(v)))
 
184
        if len(setlist) == 0 or len(wherelist) == 0:
 
185
            return
 
186
        # Join the fragments into a comma-separated string
 
187
        setstring = ', '.join(setlist)
 
188
        wherestring = ' AND '.join(wherelist)
 
189
        # Build the whole query as an UPDATE statement
 
190
        query = ("UPDATE %s SET %s WHERE %s;"
 
191
            % (tablename, setstring, wherestring))
 
192
        if dry: return query
 
193
        self.db.query(query)
 
194
 
 
195
    def delete(self, primarydict, tablename, primary_keys, dry=False):
 
196
        """Deletes a row in the table, matching against primarydict to find
 
197
        the row.
 
198
        primarydict, tablename, primary_keys: See update.
 
199
        """
 
200
        if not DB.check_dict(primarydict, primary_keys, must=True):
 
201
            raise DBException("Supplied dictionary contains invalid or missing fields (2).")
 
202
        wherelist = []
 
203
        for k,v in primarydict.items():
 
204
            wherelist.append("%s = %s" % (k, _escape(v)))
 
205
        if len(wherelist) == 0:
 
206
            return
 
207
        wherestring = ' AND '.join(wherelist)
 
208
        query = ("DELETE FROM %s WHERE %s;" % (tablename, wherestring))
 
209
        if dry: return query
 
210
        self.db.query(query)
 
211
 
 
212
    def get_single(self, primarydict, tablename, getfields, primary_keys,
 
213
        error_notfound="No rows found", dry=False):
 
214
        """Retrieves a single row from a table, returning it as a dictionary
 
215
        mapping field names to values. Matches against primarydict to find the
 
216
        row.
 
217
        primarydict, tablename, primary_keys: See update/delete.
 
218
        getfields: Collection of strings; the field names which will be
 
219
            returned as keys in the dictionary.
 
220
        error_notfound: Error message if 0 rows match.
 
221
        Raises a DBException if 0 rows match, with error_notfound as the msg.
 
222
        Raises an AssertError if >1 rows match (this should not happen if
 
223
            primary_keys is indeed the primary key).
 
224
        """
 
225
        if not DB.check_dict(primarydict, primary_keys, must=True):
 
226
            raise DBException("Supplied dictionary contains invalid or missing fields (3).")
 
227
        wherelist = []
 
228
        for k,v in primarydict.items():
 
229
            wherelist.append("%s = %s" % (k, _escape(v)))
 
230
        if len(getfields) == 0 or len(wherelist) == 0:
 
231
            return
 
232
        # Join the fragments into a comma-separated string
 
233
        getstring = ', '.join(getfields)
 
234
        wherestring = ' AND '.join(wherelist)
 
235
        # Build the whole query as an SELECT statement
 
236
        query = ("SELECT %s FROM %s WHERE %s;"
 
237
            % (getstring, tablename, wherestring))
 
238
        if dry: return query
 
239
        result = self.db.query(query)
 
240
        # Expecting exactly one
 
241
        if result.ntuples() != 1:
 
242
            # It should not be possible for ntuples to be greater than 1
 
243
            assert (result.ntuples() < 1)
 
244
            raise DBException(error_notfound)
 
245
        # Return as a dictionary
 
246
        return result.dictresult()[0]
 
247
 
 
248
    def get_all(self, tablename, getfields, dry=False):
 
249
        """Retrieves all rows from a table, returning it as a list of
 
250
        dictionaries mapping field names to values.
 
251
        tablename, getfields: See get_single.
 
252
        """
 
253
        if len(getfields) == 0:
 
254
            return
 
255
        getstring = ', '.join(getfields)
 
256
        query = ("SELECT %s FROM %s;" % (getstring, tablename))
 
257
        if dry: return query
 
258
        return self.db.query(query).dictresult()
 
259
 
 
260
    def start_transaction(self, dry=False):
 
261
        """Starts a DB transaction.
 
262
        Will not commit any changes until self.commit() is called.
 
263
        """
 
264
        query = "START TRANSACTION;"
 
265
        if dry: return query
 
266
        self.db.query(query)
 
267
 
 
268
    def commit(self, dry=False):
 
269
        """Commits (ends) a DB transaction.
 
270
        Commits all changes since the call to start_transaction.
 
271
        """
 
272
        query = "COMMIT;"
 
273
        if dry: return query
 
274
        self.db.query(query)
 
275
 
 
276
    def rollback(self, dry=False):
 
277
        """Rolls back (ends) a DB transaction, undoing all changes since the
 
278
        call to start_transaction.
 
279
        """
 
280
        query = "ROLLBACK;"
 
281
        if dry: return query
 
282
        self.db.query(query)
 
283
 
 
284
    # USER MANAGEMENT FUNCTIONS #
 
285
 
 
286
    login_primary = frozenset(["login"])
 
287
    login_fields_list = [
 
288
        "login", "passhash", "state", "unixid", "email", "nick", "fullname",
 
289
        "rolenm", "studentid", "acct_exp", "pass_exp", "last_login", "svn_pass"
 
290
    ]
 
291
    login_fields = frozenset(login_fields_list)
 
292
    # Do not return passhash when reading from the DB
 
293
    login_getfields = login_fields - frozenset(["passhash"])
 
294
 
 
295
    def create_user(self, dry=False, **kwargs):
 
296
        """Creates a user login entry in the database.
 
297
        All user fields are to be passed as args. The argument names
 
298
        are the field names of the "login" table of the DB schema.
 
299
        However, instead of supplying a "passhash", you must supply a
 
300
        "password" argument, which will be hashed internally.
 
301
        Also "state" must not given explicitly; it is implicitly set to
 
302
        "no_agreement".
 
303
        Raises an exception if the user already exists, or the dict contains
 
304
        invalid keys or is missing required keys.
 
305
        """
 
306
        if 'passhash' in kwargs:
 
307
            raise DBException("Supplied arguments include passhash (invalid) (1).")
 
308
        # Make a copy of the dict. Change password to passhash (hashing it),
 
309
        # and set 'state' to "no_agreement".
 
310
        kwargs = copy.copy(kwargs)
 
311
        if 'password' in kwargs:
 
312
            kwargs['passhash'] = _passhash(kwargs['password'])
 
313
            del kwargs['password']
 
314
        kwargs['state'] = "no_agreement"
 
315
        # Execute the query.
 
316
        return self.insert(kwargs, "login", self.login_fields, dry=dry)
 
317
 
 
318
    def update_user(self, login, dry=False, **kwargs):
 
319
        """Updates fields of a particular user. login is the name of the user
 
320
        to update. The dict contains the fields which will be modified, and
 
321
        their new values. If any value is omitted from the dict, it does not
 
322
        get modified. login and studentid may not be modified.
 
323
        Passhash may be modified by supplying a "password" field, in
 
324
        cleartext, not a hashed password.
 
325
 
 
326
        Note that no checking is done. It is expected this function is called
 
327
        by a trusted source. In particular, it allows the password to be
 
328
        changed without knowing the old password. The caller should check
 
329
        that the user knows the existing password before calling this function
 
330
        with a new one.
 
331
        """
 
332
        if 'passhash' in kwargs:
 
333
            raise DBException("Supplied arguments include passhash (invalid) (2).")
 
334
        if "password" in kwargs:
 
335
            kwargs = copy.copy(kwargs)
 
336
            kwargs['passhash'] = _passhash(kwargs['password'])
 
337
            del kwargs['password']
 
338
        return self.update({"login": login}, kwargs, "login",
 
339
            self.login_fields, self.login_primary, ["login", "studentid"],
 
340
            dry=dry)
 
341
 
 
342
    def get_user(self, login, dry=False):
 
343
        """Given a login, returns a User object containing details looked up
 
344
        in the DB.
 
345
 
 
346
        Raises a DBException if the login is not found in the DB.
 
347
        """
 
348
        userdict = self.get_single({"login": login}, "login",
 
349
            self.login_getfields, self.login_primary,
 
350
            error_notfound="get_user: No user with that login name", dry=dry)
 
351
        if dry:
 
352
            return userdict     # Query string
 
353
        # Package into a User object
 
354
        return user.User(**userdict)
 
355
 
 
356
    def get_users(self, dry=False):
 
357
        """Returns a list of all users in the DB, as User objects.
 
358
        """
 
359
        userdicts = self.get_all("login", self.login_getfields, dry=dry)
 
360
        if dry:
 
361
            return userdicts    # Query string
 
362
        # Package into User objects
 
363
        return [user.User(**userdict) for userdict in userdicts]
 
364
 
 
365
    def user_authenticate(self, login, password, dry=False):
 
366
        """Performs a password authentication on a user. Returns True if
 
367
        "passhash" is the correct passhash for the given login, False
 
368
        if the passhash does not match the password in the DB,
 
369
        and None if the passhash in the DB is NULL.
 
370
        Also returns False if the login does not exist (so if you want to
 
371
        differentiate these cases, use get_user and catch an exception).
 
372
        """
 
373
        query = "SELECT passhash FROM login WHERE login = '%s';" % login
 
374
        if dry: return query
 
375
        result = self.db.query(query)
 
376
        if result.ntuples() == 1:
 
377
            # Valid username. Check password.
 
378
            passhash = result.getresult()[0][0]
 
379
            if passhash is None:
 
380
                return None
 
381
            return _passhash(password) == passhash
 
382
        else:
 
383
            return False
 
384
 
 
385
    def close(self):
 
386
        """Close the DB connection. Do not call any other functions after
 
387
        this. (The behaviour of doing so is undefined).
 
388
        """
 
389
        self.db.close()
 
390
        self.open = False