100
# GENERIC DB FUNCTIONS #
103
def check_dict(dict, tablefields, disallowed=frozenset([]), must=False):
104
"""Checks that a dict does not contain keys that are not fields
105
of the specified table.
106
dict: A mapping from string keys to values; the keys are checked to
107
see that they correspond to login table fields.
108
tablefields: Collection of strings for field names in the table.
109
Only these fields will be allowed.
110
disallowed: Optional collection of strings for field names that are
112
must: If True, the dict MUST contain all fields in tablefields.
113
If False, it may contain any subset of the fields.
114
Returns True if the dict is valid, False otherwise.
116
allowed = frozenset(tablefields) - frozenset(disallowed)
117
dictkeys = frozenset(dict.keys())
119
return allowed == dictkeys
121
return allowed.issuperset(dictkeys)
123
def insert(self, dict, tablename, tablefields, disallowed=frozenset([]),
125
"""Inserts a new row in a table, using data from a supplied
126
dictionary (which will be checked by check_dict).
127
dict: Dictionary mapping column names to values. The values may be
128
any of the following types:
129
str, int, long, float, NoneType.
130
tablename: String, name of the table to insert into. Will NOT be
131
escaped - must be a valid identifier.
132
tablefields, disallowed: see check_dict.
133
dry: Returns the SQL query as a string, and does not execute it.
134
Raises a DBException if the dictionary contains invalid fields.
136
if not DB.check_dict(dict, tablefields, disallowed):
137
raise DBException("Supplied dictionary contains invalid fields.")
138
# Build two lists concurrently: field names and values, as SQL strings
141
for k,v in dict.items():
143
values.append(_escape(v))
144
if len(fieldnames) == 0: return
145
fieldnames = ', '.join(fieldnames)
146
values = ', '.join(values)
147
query = ("INSERT INTO %s (%s) VALUES (%s);"
148
% (tablename, fieldnames, values))
152
def update(self, primarydict, updatedict, tablename, tablefields,
153
primary_keys, disallowed_update=frozenset([]), dry=False):
154
"""Updates a row in a table, matching against primarydict to find the
155
row, and using the data in updatedict (which will be checked by
157
primarydict: Dict mapping column names to values. The keys should be
158
the table's primary key. Only rows which match this dict's values
160
updatedict: Dict mapping column names to values. The columns will be
161
updated with the given values for the matched rows.
162
tablename, tablefields, disallowed_update: See insert.
163
primary_keys: Collection of strings which together form the primary
164
key for this table. primarydict must contain all of these as keys,
167
if (not (DB.check_dict(primarydict, primary_keys, must=True)
168
and DB.check_dict(updatedict, tablefields, disallowed_update))):
169
raise DBException("Supplied dictionary contains invalid or "
171
# Make a list of SQL fragments of the form "field = 'new value'"
172
# These fragments are ALREADY-ESCAPED
174
for k,v in updatedict.items():
175
setlist.append("%s = %s" % (k, _escape(v)))
177
for k,v in primarydict.items():
178
wherelist.append("%s = %s" % (k, _escape(v)))
179
if len(setlist) == 0 or len(wherelist) == 0:
181
# Join the fragments into a comma-separated string
182
setstring = ', '.join(setlist)
183
wherestring = ' AND '.join(wherelist)
184
# Build the whole query as an UPDATE statement
185
query = ("UPDATE %s SET %s WHERE %s;"
186
% (tablename, setstring, wherestring))
190
def delete(self, primarydict, tablename, primary_keys, dry=False):
191
"""Deletes a row in the table, matching against primarydict to find
193
primarydict, tablename, primary_keys: See update.
195
if not DB.check_dict(primarydict, primary_keys, must=True):
196
raise DBException("Supplied dictionary contains invalid or "
199
for k,v in primarydict.items():
200
wherelist.append("%s = %s" % (k, _escape(v)))
201
if len(wherelist) == 0:
203
wherestring = ' AND '.join(wherelist)
204
query = ("DELETE FROM %s WHERE %s;" % (tablename, wherestring))
208
def get_single(self, primarydict, tablename, getfields, primary_keys,
209
error_notfound="No rows found", dry=False):
210
"""Retrieves a single row from a table, returning it as a dictionary
211
mapping field names to values. Matches against primarydict to find the
213
primarydict, tablename, primary_keys: See update/delete.
214
getfields: Collection of strings; the field names which will be
215
returned as keys in the dictionary.
216
error_notfound: Error message if 0 rows match.
217
Raises a DBException if 0 rows match, with error_notfound as the msg.
218
Raises an AssertError if >1 rows match (this should not happen if
219
primary_keys is indeed the primary key).
221
if not DB.check_dict(primarydict, primary_keys, must=True):
222
raise DBException("Supplied dictionary contains invalid or "
225
for k,v in primarydict.items():
226
wherelist.append("%s = %s" % (k, _escape(v)))
227
if len(getfields) == 0 or len(wherelist) == 0:
229
# Join the fragments into a comma-separated string
230
getstring = ', '.join(getfields)
231
wherestring = ' AND '.join(wherelist)
232
# Build the whole query as an SELECT statement
233
query = ("SELECT %s FROM %s WHERE %s;"
234
% (getstring, tablename, wherestring))
236
result = self.db.query(query)
237
# Expecting exactly one
238
if result.ntuples() != 1:
239
# It should not be possible for ntuples to be greater than 1
240
assert (result.ntuples() < 1)
241
raise DBException(error_notfound)
242
# Return as a dictionary
243
return result.dictresult()[0]
245
def get_all(self, tablename, getfields, dry=False):
246
"""Retrieves all rows from a table, returning it as a list of
247
dictionaries mapping field names to values.
248
tablename, getfields: See get_single.
250
if len(getfields) == 0:
252
getstring = ', '.join(getfields)
253
query = ("SELECT %s FROM %s;" % (getstring, tablename))
255
return self.db.query(query).dictresult()
85
257
# USER MANAGEMENT FUNCTIONS #
87
def create_user(self, login, password, unixid, email, nick, fullname,
88
rolenm, studentid, acct_exp=None, dry=False):
259
login_primary = frozenset(["login"])
260
login_fields = frozenset([
261
"login", "passhash", "state", "unixid", "email", "nick", "fullname",
262
"rolenm", "studentid", "acct_exp", "pass_exp"
264
# Do not return passhash when reading from the DB
265
login_getfields = login_fields - frozenset(["passhash"])
267
def create_user(self, dict, dry=False):
89
268
"""Creates a user login entry in the database.
90
Arguments are the same as those in the "login" table of the schema.
91
The exception is "password", which is a cleartext password. makeuser
92
will hash the password.
93
Also "state" is not given explicitly; it is implicitly set to
269
dict is a dictionary mapping string keys to values. The string keys
270
are the field names of the "login" table of the DB schema.
271
However, instead of supplying a "passhash", you must supply a
272
"password", which will be hashed internally.
273
Also "state" must not given explicitly; it is implicitly set to
95
Raises an exception if the user already exists.
275
Raises an exception if the user already exists, or the dict contains
276
invalid keys or is missing required keys.
97
passhash = _passhash(password)
98
query = ("INSERT INTO login (login, passhash, state, unixid, email, "
99
"nick, fullname, rolenm, studentid, acct_exp) VALUES "
100
"(%s, %s, 'no_agreement', %d, %s, %s, %s, %s, %s);" %
101
(_escape(login), _escape(passhash), unixid, _escape(email),
102
_escape(nick), _escape(fullname), _escape(rolenm),
103
_escape(studentid), _escape(acct_exp))
278
if 'passhash' in dict:
279
raise DBException("Supplied dictionary contains passhash (invalid).")
280
# Make a copy of the dict. Change password to passhash (hashing it),
281
# and set 'state' to "no_agreement".
282
dict = copy.copy(dict)
283
dict['passhash'] = _passhash(dict['password'])
285
dict['state'] = "no_agreement"
287
return self.insert(dict, "login", self.login_fields, dry=dry)
107
def update_user(self, login, password=None, state=None, email=None,
108
nick=None, fullname=None, rolenm=None, acct_exp=None, pass_exp=None,
109
last_login=None, dry=False):
289
def update_user(self, login, dict, dry=False):
110
290
"""Updates fields of a particular user. login is the name of the user
111
to update. The other arguments are optional fields which may be
112
modified. If None or omitted, they do not get modified. login and
113
studentid may not be modified.
291
to update. The dict contains the fields which will be modified, and
292
their new values. If any value is omitted from the dict, it does not
293
get modified. login and studentid may not be modified.
294
Passhash may be modified by supplying a "password" field, in
295
cleartext, not a hashed password.
115
297
Note that no checking is done. It is expected this function is called
116
298
by a trusted source. In particular, it allows the password to be
117
299
changed without knowing the old password. The caller should check
118
300
that the user knows the existing password before calling this function
121
FIXME: this interface does not allow fields to be set to NULL (None).
123
# Make a list of SQL fragments of the form "field = 'new value'"
124
# These fragments are ALREADY-ESCAPED
126
if passhash is not None:
127
setlist.append("passhash = " + _escape(_passhash(password)))
128
if state is not None:
129
setlist.append("state = " + _escape(state))
130
if email is not None:
131
setlist.append("email = " + _escape(email))
133
setlist.append("nick = " + _escape(nick))
134
if fullname is not None:
135
setlist.append("fullname = " + _escape(fullname))
136
if rolenm is not None:
137
setlist.append("rolenm = " + _escape(rolenm))
138
if pass_exp is not None:
139
setlist.append("pass_exp = " + _escape(pass_exp))
140
if acct_exp is not None:
141
setlist.append("acct_exp = " + _escape(acct_exp))
142
if last_login is not None:
143
setlist.append("last_login = " + _escape(last_login))
144
if len(setlist) == 0:
146
# Join the fragments into a comma-separated string
147
setstring = ', '.join(setlist)
148
# Build the whole query as an UPDATE statement
149
query = ("UPDATE login SET %s WHERE login = %s;"
150
% (setstring, _escape(login)))
154
def delete_user(self, login, dry=False):
155
"""Deletes a user login entry from the database."""
156
query = "DELETE FROM login WHERE login = %s;" % _escape(login)
303
if 'passhash' in dict:
304
raise DBException("Supplied dictionary contains passhash (invalid).")
305
if "password" in dict:
306
dict = copy.copy(dict)
307
dict['passhash'] = _passhash(dict['password'])
309
return self.update({"login": login}, dict, "login", self.login_fields,
310
self.login_primary, ["login", "studentid"], dry=dry)
160
312
def get_user(self, login, dry=False):
161
313
"""Given a login, returns a dictionary of the user's DB fields,