X-Git-Url: https://www.chiark.greenend.org.uk/ucgi/~mdw/git/chopwood/blobdiff_plain/612419ac09c0def4b15b101cf0520a4d21bb9911..82d4f64b774253438506cec05eacad5af158ccac:/backend.py diff --git a/backend.py b/backend.py index 54c5374..7c6645a 100644 --- a/backend.py +++ b/backend.py @@ -25,6 +25,7 @@ from __future__ import with_statement +import itertools as I import os as OS; ENV = OS.environ import config as CONF; CFG = CONF.CFG @@ -38,6 +39,62 @@ CONF.DEFAULTS.update( ## A directory in which we can create lockfiles. LOCKDIR = OS.path.join(ENV['HOME'], 'var', 'lock', 'chpwd')) +###-------------------------------------------------------------------------- +### Utilities. + +def fill_in_fields(fno_user, fno_passwd, fno_map, user, passwd, args): + """ + Return a vector of filled-in fields. + + The FNO_... arguments give field numbers: FNO_USER and FNO_PASSWD give the + positions for the username and password fields, respectively; and FNO_MAP + is a sequence of (NAME, POS) pairs. The USER and PASSWD arguments give the + actual user name and password values; ARGS are the remaining arguments, + maybe in the form `NAME=VALUE'. + """ + + ## Prepare the result vector, and set up some data structures. + n = 2 + len(fno_map) + fmap = {} + rmap = map(int, xrange(n)) + ok = True + if fno_user >= n or fno_passwd >= n: ok = False + for k, i in fno_map: + fmap[k] = i + rmap[i] = "`%s'" % k + if i >= n: ok = False + if not ok: + raise U.ExpectedError, \ + (500, "Fields specified aren't contiguous") + + ## Prepare the new record's fields. + f = [None]*n + f[fno_user] = user + f[fno_passwd] = passwd + + for a in args: + if '=' in a: + k, v = a.split('=', 1) + try: i = fmap[k] + except KeyError: raise U.ExpectedError, (400, "Unknown field `%s'" % k) + else: + for i in xrange(n): + if f[i] is None: break + else: + raise U.ExpectedError, (500, "All fields already populated") + v = a + if f[i] is not None: + raise U.ExpectedError, (400, "Field %s is already set" % rmap[i]) + f[i] = v + + ## Check that the vector of fields is properly set up. + for i in xrange(n): + if f[i] is None: + raise U.ExpectedError, (500, "Field %s is unset" % rmap[i]) + + ## Done. + return f + ###-------------------------------------------------------------------------- ### Protocol. ### @@ -76,6 +133,8 @@ class BasicRecord (object): me._be = backend def write(me): me._be._update(me) + def remove(me): + me._be._remove(me) class TrivialRecord (BasicRecord): """ @@ -181,6 +240,24 @@ class FlatFileBackend (object): return rec raise UnknownUser, user + def create(me, user, passwd, args): + """ + Create a new record for the USER. + + The new record has the given PASSWD, and other fields are set from ARGS. + Those ARGS of the form `KEY=VALUE' set the appropriately named fields (as + set up by the constructor); other ARGS fill in unset fields, left to + right. + """ + + f = fill_in_fields(me._fmap['user'], me._fmap['passwd'], + [(k[2:], i) + for k, i in me._fmap.iteritems() + if k.startswith('f_')], + user, passwd, args) + r = FlatFileRecord(':'.join(f), me._delim, me._fmap, backend = me) + me._rewrite('create', r) + def _rewrite(me, op, rec): """ Rewrite the file, according to OP. @@ -266,6 +343,10 @@ class FlatFileBackend (object): """Update the record REC in the file.""" me._rewrite('update', rec) + def _remove(me, rec): + """Update the record REC in the file.""" + me._rewrite('remove', rec) + CONF.export('FlatFileBackend') ###-------------------------------------------------------------------------- @@ -322,6 +403,36 @@ class DatabaseBackend (object): setattr(rec, 'f_' + f, v) return rec + def create(me, user, passwd, args): + """ + Create a new record for the named USER. + + The new record has the given PASSWD, and other fields are set from ARGS. + Those ARGS of the form `KEY=VALUE' set the appropriately named fields (as + set up by the constructor); other ARGS fill in unset fields, left to + right, in the order given to the constructor. + """ + + tags = ['user', 'passwd'] + \ + ['t_%d' % 0 for i in xrange(len(me._fields))] + f = fill_in_fields(0, 1, list(I.izip(me._fields, I.count(2))), + user, passwd, args) + me._connect() + with me._db: + me._db.execute("INSERT INTO %s (%s) VALUES (%s)" % + (me._table, + ', '.join([me._user, me._passwd] + me._fields), + ', '.join(['$%s' % t for t in tags])), + **dict(I.izip(tags, f))) + + def _remove(me, rec): + """Remove the record REC from the database.""" + me._connect() + with me._db: + me._db.execute("DELETE FROM %s WHERE %s = $user" % + (me._table, me._user), + user = rec.user) + def _update(me, rec): """Update the record REC in the database.""" me._connect()