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

« back to all changes in this revision

Viewing changes to lib/common/db.py

  • Committer: dilshan_a
  • Date: 2008-01-24 22:16:41 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:289
Updated tests so it works in the test framework

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
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.db = pg.connect(dbname=conf.db_dbname, host=conf.db_host,
98
 
                port=conf.db_port, user=conf.db_user, passwd=conf.db_password)
99
 
        self.open = True
100
 
 
101
 
    def __del__(self):
102
 
        if self.open:
103
 
            self.db.close()
104
 
 
105
 
    # GENERIC DB FUNCTIONS #
106
 
 
107
 
    @staticmethod
108
 
    def check_dict(dict, tablefields, disallowed=frozenset([]), must=False):
109
 
        """Checks that a dict does not contain keys that are not fields
110
 
        of the specified table.
111
 
        dict: A mapping from string keys to values; the keys are checked to
112
 
            see that they correspond to login table fields.
113
 
        tablefields: Collection of strings for field names in the table.
114
 
            Only these fields will be allowed.
115
 
        disallowed: Optional collection of strings for field names that are
116
 
            not allowed.
117
 
        must: If True, the dict MUST contain all fields in tablefields.
118
 
            If False, it may contain any subset of the fields.
119
 
        Returns True if the dict is valid, False otherwise.
120
 
        """
121
 
        allowed = frozenset(tablefields) - frozenset(disallowed)
122
 
        dictkeys = frozenset(dict.keys())
123
 
        if must:
124
 
            return allowed == dictkeys
125
 
        else:
126
 
            return allowed.issuperset(dictkeys)
127
 
 
128
 
    def insert(self, dict, tablename, tablefields, disallowed=frozenset([]),
129
 
        dry=False):
130
 
        """Inserts a new row in a table, using data from a supplied
131
 
        dictionary (which will be checked by check_dict).
132
 
        dict: Dictionary mapping column names to values. The values may be
133
 
            any of the following types:
134
 
            str, int, long, float, NoneType.
135
 
        tablename: String, name of the table to insert into. Will NOT be
136
 
            escaped - must be a valid identifier.
137
 
        tablefields, disallowed: see check_dict.
138
 
        dry: Returns the SQL query as a string, and does not execute it.
139
 
        Raises a DBException if the dictionary contains invalid fields.
140
 
        """
141
 
        if not DB.check_dict(dict, tablefields, disallowed):
142
 
            raise DBException("Supplied dictionary contains invalid fields.")
143
 
        # Build two lists concurrently: field names and values, as SQL strings
144
 
        fieldnames = []
145
 
        values = []
146
 
        for k,v in dict.items():
147
 
            fieldnames.append(k)
148
 
            values.append(_escape(v))
149
 
        if len(fieldnames) == 0: return
150
 
        fieldnames = ', '.join(fieldnames)
151
 
        values = ', '.join(values)
152
 
        query = ("INSERT INTO %s (%s) VALUES (%s);"
153
 
            % (tablename, fieldnames, values))
154
 
        if dry: return query
155
 
        self.db.query(query)
156
 
 
157
 
    def update(self, primarydict, updatedict, tablename, tablefields,
158
 
        primary_keys, disallowed_update=frozenset([]), dry=False):
159
 
        """Updates a row in a table, matching against primarydict to find the
160
 
        row, and using the data in updatedict (which will be checked by
161
 
        check_dict).
162
 
        primarydict: Dict mapping column names to values. The keys should be
163
 
            the table's primary key. Only rows which match this dict's values
164
 
            will be updated.
165
 
        updatedict: Dict mapping column names to values. The columns will be
166
 
            updated with the given values for the matched rows.
167
 
        tablename, tablefields, disallowed_update: See insert.
168
 
        primary_keys: Collection of strings which together form the primary
169
 
            key for this table. primarydict must contain all of these as keys,
170
 
            and only these keys.
171
 
        """
172
 
        if (not (DB.check_dict(primarydict, primary_keys, must=True)
173
 
            and DB.check_dict(updatedict, tablefields, disallowed_update))):
174
 
            raise DBException("Supplied dictionary contains invalid or "
175
 
                " missing fields.")
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 "
202
 
                " missing fields.")
203
 
        wherelist = []
204
 
        for k,v in primarydict.items():
205
 
            wherelist.append("%s = %s" % (k, _escape(v)))
206
 
        if len(wherelist) == 0:
207
 
            return
208
 
        wherestring = ' AND '.join(wherelist)
209
 
        query = ("DELETE FROM %s WHERE %s;" % (tablename, wherestring))
210
 
        if dry: return query
211
 
        self.db.query(query)
212
 
 
213
 
    def get_single(self, primarydict, tablename, getfields, primary_keys,
214
 
        error_notfound="No rows found", dry=False):
215
 
        """Retrieves a single row from a table, returning it as a dictionary
216
 
        mapping field names to values. Matches against primarydict to find the
217
 
        row.
218
 
        primarydict, tablename, primary_keys: See update/delete.
219
 
        getfields: Collection of strings; the field names which will be
220
 
            returned as keys in the dictionary.
221
 
        error_notfound: Error message if 0 rows match.
222
 
        Raises a DBException if 0 rows match, with error_notfound as the msg.
223
 
        Raises an AssertError if >1 rows match (this should not happen if
224
 
            primary_keys is indeed the primary key).
225
 
        """
226
 
        if not DB.check_dict(primarydict, primary_keys, must=True):
227
 
            raise DBException("Supplied dictionary contains invalid or "
228
 
                " missing fields.")
229
 
        wherelist = []
230
 
        for k,v in primarydict.items():
231
 
            wherelist.append("%s = %s" % (k, _escape(v)))
232
 
        if len(getfields) == 0 or len(wherelist) == 0:
233
 
            return
234
 
        # Join the fragments into a comma-separated string
235
 
        getstring = ', '.join(getfields)
236
 
        wherestring = ' AND '.join(wherelist)
237
 
        # Build the whole query as an SELECT statement
238
 
        query = ("SELECT %s FROM %s WHERE %s;"
239
 
            % (getstring, tablename, wherestring))
240
 
        if dry: return query
241
 
        result = self.db.query(query)
242
 
        # Expecting exactly one
243
 
        if result.ntuples() != 1:
244
 
            # It should not be possible for ntuples to be greater than 1
245
 
            assert (result.ntuples() < 1)
246
 
            raise DBException(error_notfound)
247
 
        # Return as a dictionary
248
 
        return result.dictresult()[0]
249
 
 
250
 
    def get_all(self, tablename, getfields, dry=False):
251
 
        """Retrieves all rows from a table, returning it as a list of
252
 
        dictionaries mapping field names to values.
253
 
        tablename, getfields: See get_single.
254
 
        """
255
 
        if len(getfields) == 0:
256
 
            return
257
 
        getstring = ', '.join(getfields)
258
 
        query = ("SELECT %s FROM %s;" % (getstring, tablename))
259
 
        if dry: return query
260
 
        return self.db.query(query).dictresult()
261
 
 
262
 
    # USER MANAGEMENT FUNCTIONS #
263
 
 
264
 
    login_primary = frozenset(["login"])
265
 
    login_fields_list = [
266
 
        "login", "passhash", "state", "unixid", "email", "nick", "fullname",
267
 
        "rolenm", "studentid", "acct_exp", "pass_exp", "last_login"
268
 
    ]
269
 
    login_fields = frozenset(login_fields_list)
270
 
    # Do not return passhash when reading from the DB
271
 
    login_getfields = login_fields - frozenset(["passhash"])
272
 
 
273
 
    def create_user(self, dry=False, **kwargs):
274
 
        """Creates a user login entry in the database.
275
 
        All user fields are to be passed as args. The argument names
276
 
        are the field names of the "login" table of the DB schema.
277
 
        However, instead of supplying a "passhash", you must supply a
278
 
        "password" argument, which will be hashed internally.
279
 
        Also "state" must not given explicitly; it is implicitly set to
280
 
        "no_agreement".
281
 
        Raises an exception if the user already exists, or the dict contains
282
 
        invalid keys or is missing required keys.
283
 
        """
284
 
        if 'passhash' in kwargs:
285
 
            raise DBException("Supplied arguments include passhash (invalid).")
286
 
        # Make a copy of the dict. Change password to passhash (hashing it),
287
 
        # and set 'state' to "no_agreement".
288
 
        kwargs = copy.copy(kwargs)
289
 
        if 'password' in kwargs:
290
 
            kwargs['passhash'] = _passhash(kwargs['password'])
291
 
            del kwargs['password']
292
 
        kwargs['state'] = "no_agreement"
293
 
        # Execute the query.
294
 
        return self.insert(kwargs, "login", self.login_fields, dry=dry)
295
 
 
296
 
    def update_user(self, login, dry=False, **kwargs):
297
 
        """Updates fields of a particular user. login is the name of the user
298
 
        to update. The dict contains the fields which will be modified, and
299
 
        their new values. If any value is omitted from the dict, it does not
300
 
        get modified. login and studentid may not be modified.
301
 
        Passhash may be modified by supplying a "password" field, in
302
 
        cleartext, not a hashed password.
303
 
 
304
 
        Note that no checking is done. It is expected this function is called
305
 
        by a trusted source. In particular, it allows the password to be
306
 
        changed without knowing the old password. The caller should check
307
 
        that the user knows the existing password before calling this function
308
 
        with a new one.
309
 
        """
310
 
        if 'passhash' in kwargs:
311
 
            raise DBException("Supplied arguments include passhash (invalid).")
312
 
        if "password" in kwargs:
313
 
            kwargs = copy.copy(kwargs)
314
 
            kwargs['passhash'] = _passhash(kwargs['password'])
315
 
            del kwargs['password']
316
 
        return self.update({"login": login}, kwargs, "login",
317
 
            self.login_fields, self.login_primary, ["login", "studentid"],
318
 
            dry=dry)
319
 
 
320
 
    def get_user(self, login, dry=False):
321
 
        """Given a login, returns a dictionary of the user's DB fields,
322
 
        excluding the passhash field.
323
 
 
324
 
        Raises a DBException if the login is not found in the DB.
325
 
        """
326
 
        return self.get_single({"login": login}, "login",
327
 
            self.login_getfields, self.login_primary,
328
 
            error_notfound="get_user: No user with that login name", dry=dry)
329
 
 
330
 
    def get_users(self, dry=False):
331
 
        """Returns a list of all users. The list elements are a dictionary of
332
 
        the user's DB fields, excluding the passhash field.
333
 
        """
334
 
        return self.get_all("login", self.login_getfields, dry=dry)
335
 
 
336
 
    def user_authenticate(self, login, password, dry=False):
337
 
        """Performs a password authentication on a user. Returns True if
338
 
        "passhash" is the correct passhash for the given login, False
339
 
        otherwise.
340
 
        Also returns False if the login does not exist (so if you want to
341
 
        differentiate these cases, use get_user and catch an exception).
342
 
        """
343
 
        query = ("SELECT login FROM login "
344
 
            "WHERE login = '%s' AND passhash = %s;"
345
 
            % (login, _escape(_passhash(password))))
346
 
        if dry: return query
347
 
        result = self.db.query(query)
348
 
        # If one row was returned, succeed.
349
 
        # Otherwise, fail to authenticate.
350
 
        return result.ntuples() == 1
351
 
 
352
 
    def close(self):
353
 
        """Close the DB connection. Do not call any other functions after
354
 
        this. (The behaviour of doing so is undefined).
355
 
        """
356
 
        self.db.close()
357
 
        self.open = False