~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-05 01:51:26 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:411
Renamed lib/fileservice to lib/fileservice_lib (naming conflict).
Added new app: fileservice. This app replaces the old one that was deleted -
it simply calls fileservice_lib.handle, and that's it (so it functions exactly
the same).

Show diffs side-by-side

added added

removed removed

Lines of Context:
17
17
 
18
18
# Module: Database
19
19
# Author: Matt Giuca
20
 
# Date:   15/2/2008
 
20
# Date:   1/2/2008
21
21
 
22
22
# Code to talk to the PostgreSQL database.
23
23
# (This is the Data Access Layer).
34
34
import pg
35
35
import conf
36
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.
 
37
 
 
38
def _escape(str):
 
39
    """Wrapper around pg.escape_string. Escapes the string for use in SQL, and
 
40
    also quotes it to make sure that every string used in a query is quoted.
52
41
    """
53
42
    # "E'" is postgres's way of making "escape" strings.
54
43
    # Such strings allow backslashes to escape things. Since escape_string
56
45
    # into E mode.
57
46
    # Ref: http://www.postgresql.org/docs/8.2/static/sql-syntax-lexical.html
58
47
    # 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")
 
48
    return "E'" + pg.escape_string(str) + "'"
73
49
 
74
50
def _passhash(password):
75
51
    return md5.md5(password).hexdigest()
96
72
        Takes no parameters - gets all the DB info from the configuration."""
97
73
        self.db = pg.connect(dbname=conf.db_dbname, host=conf.db_host,
98
74
                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([]),
 
75
 
 
76
    # USER MANAGEMENT FUNCTIONS #
 
77
 
 
78
    def create_user(self, login, password, nick, fullname, rolenm, studentid,
129
79
        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.
 
80
        """Creates a user login entry in the database.
 
81
        Arguments are the same as those in the "login" table of the schema.
 
82
        The exception is "password", which is a cleartext password. makeuser
 
83
        will hash the password.
 
84
        Raises an exception if the user already exists.
140
85
        """
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))
 
86
        passhash = _passhash(password)
 
87
        query = ("INSERT INTO login (login, passhash, nick, fullname, "
 
88
            "rolenm, studentid) VALUES (%s, %s, %s, %s, %s, %s);" %
 
89
            (_escape(login), _escape(passhash), _escape(nick),
 
90
            _escape(fullname), _escape(rolenm), _escape(studentid)))
154
91
        if dry: return query
155
92
        self.db.query(query)
156
93
 
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.
 
94
    def update_user(self, login, password=None, nick=None,
 
95
        fullname=None, rolenm=None, dry=False):
 
96
        """Updates fields of a particular user. login is the name of the user
 
97
        to update. The other arguments are optional fields which may be
 
98
        modified. If None or omitted, they do not get modified. login and
 
99
        studentid may not be modified.
 
100
 
 
101
        Note that no checking is done. It is expected this function is called
 
102
        by a trusted source. In particular, it allows the password to be
 
103
        changed without knowing the old password. The caller should check
 
104
        that the user knows the existing password before calling this function
 
105
        with a new one.
171
106
        """
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
107
        # Make a list of SQL fragments of the form "field = 'new value'"
177
108
        # These fragments are ALREADY-ESCAPED
178
109
        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:
 
110
        if password is not None:
 
111
            setlist.append("passhash = " + _escape(_passhash(password)))
 
112
        if nick is not None:
 
113
            setlist.append("nick = " + _escape(nick))
 
114
        if fullname is not None:
 
115
            setlist.append("fullname = " + _escape(fullname))
 
116
        if rolenm is not None:
 
117
            setlist.append("rolenm = " + _escape(rolenm))
 
118
        if len(setlist) == 0:
185
119
            return
186
120
        # Join the fragments into a comma-separated string
187
121
        setstring = ', '.join(setlist)
188
 
        wherestring = ' AND '.join(wherelist)
189
122
        # 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))
 
123
        query = ("UPDATE login SET %s WHERE login = %s;"
 
124
            % (setstring, _escape(login)))
 
125
        if dry: return query
 
126
        self.db.query(query)
 
127
 
 
128
    def delete_user(self, login, dry=False):
 
129
        """Deletes a user login entry from the database."""
 
130
        query = "DELETE FROM login WHERE login = %s;" % _escape(login)
 
131
        if dry: return query
 
132
        self.db.query(query)
 
133
 
 
134
    def get_user(self, login, dry=False):
 
135
        """Given a login, returns a dictionary of the user's DB fields,
 
136
        excluding the passhash field.
 
137
 
 
138
        Raises a DBException if the login is not found in the DB.
 
139
        """
 
140
        query = ("SELECT login, nick, fullname, rolenm, studentid FROM login "
 
141
            "WHERE login = %s;" % _escape(login))
240
142
        if dry: return query
241
143
        result = self.db.query(query)
242
144
        # Expecting exactly one
243
145
        if result.ntuples() != 1:
244
146
            # It should not be possible for ntuples to be greater than 1
245
147
            assert (result.ntuples() < 1)
246
 
            raise DBException(error_notfound)
 
148
            raise DBException("get_user: No user with that login name")
247
149
        # Return as a dictionary
248
150
        return result.dictresult()[0]
249
151
 
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
152
    def user_authenticate(self, login, password, dry=False):
337
153
        """Performs a password authentication on a user. Returns True if
338
 
        "passhash" is the correct passhash for the given login, False
339
 
        otherwise.
 
154
        "password" is the correct password for the given login, False
 
155
        otherwise. "password" is cleartext.
340
156
        Also returns False if the login does not exist (so if you want to
341
157
        differentiate these cases, use get_user and catch an exception).
342
158
        """
354
170
        this. (The behaviour of doing so is undefined).
355
171
        """
356
172
        self.db.close()
357
 
        self.open = False