This repository has been archived by the owner on Sep 17, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.py
483 lines (429 loc) · 16.3 KB
/
database.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
""" WhoYou: Simple accounts database for web applications.
Interface to the database.
"""
import sqlite3
import json
import hashlib
from wrapid.utils import rstr
from whoyou import configuration
class Database(object):
"Interface to the WhoYou database."
def __init__(self, path=configuration.MASTER_DB_FILE):
self.path = path
def open(self):
assert not self.opened
self.cnx = sqlite3.connect(self.path)
self.cnx.text_factory = str
self.account_cache = dict()
self.team_cache = dict()
def close(self):
try:
self.cnx.close()
except AttributeError:
pass
else:
del self.cnx
@property
def opened(self):
return hasattr(self, 'cnx')
def execute(self, sql, *values):
assert self.opened
cursor = self.cnx.cursor()
cursor.execute(sql, values)
return cursor
def commit(self):
assert self.opened
self.cnx.commit()
def create_account(self, name, password=None, description=None):
try:
self.get_account(name)
except KeyError:
pass
else:
raise ValueError("account '%s' already exists", name)
account = Account(self)
account.name = name
if password:
account.password = password
account.description = description
account.save()
return account
def get_accounts(self):
"Return list of all accounts."
assert self.opened
cursor = self.execute('SELECT name FROM account ORDER BY name')
result = []
for record in cursor:
result.append(self.get_account(record[0]))
return result
def get_account(self, name, password=None):
"""Return the Account instance.
If the password is given, then authenticate.
Raise KeyError if no such account.
Raise ValueError if incorrect password.
"""
assert self.opened
try:
account = self.account_cache[name]
except KeyError:
account = Account(self, name=name)
self.account_cache[account.name] = account
if password:
account.check_password(password)
return account
def create_team(self, name, description=None):
try:
self.get_team(name)
except KeyError:
pass
else:
raise ValueError("team '%s' already exists", name)
team = Team(self)
team.name = name
team.description = description
team.save()
return team
def get_teams(self):
"Return list of all teams."
assert self.opened
cursor = self.execute('SELECT name FROM team ORDER BY name')
result = []
for record in cursor:
result.append(self.get_team(record[0]))
return result
def get_team(self, name):
"""Return the Team instance for the name.
Raise KeyError if no such team.
"""
assert self.opened
try:
return self.team_cache[name]
except KeyError:
team = Team(self, name=name)
self.team_cache[team.name] = team
return team
def save(self, item):
"Save the instance (Account or Team)."
item.save(self)
def create(self):
assert self.opened
self.execute('CREATE TABLE account'
'(id INTEGER PRIMARY KEY,'
' name TEXT UNIQUE NOT NULL,'
' password TEXT,' # Stored as hexdigest
' email TEXT,'
' description TEXT,'
' properties TEXT)')
self.execute('CREATE TABLE team'
'(id INTEGER PRIMARY KEY,'
' name TEXT UNIQUE NOT NULL,'
' description TEXT,'
' properties TEXT)')
self.execute('CREATE TABLE account_team'
'(account INTEGER NOT NULL REFERENCES account(id)'
' ON DELETE RESTRICT,'
' team INTEGER NOT NULL REFERENCES team(id)'
' ON DELETE RESTRICT,'
' admin INTEGER,'
' UNIQUE (account, team))')
class Account(object):
"User account."
def __init__(self, db, name=None):
self.db = db
if name:
self.fetch(name)
else:
self.id = None
self.name = None
self._hexdigest = None
self.description = None
self.email = None
self.properties = dict()
def __str__(self):
return self.name
def __repr__(self):
return "Account '%s'" % self.name
def fetch(self, name):
"Raise KeyError if no such account."
cursor = self.db.execute('SELECT id,password,description,email,'
' properties FROM account WHERE name=?',
name)
record = cursor.fetchone()
if not record:
raise KeyError("no such Account '%s'" % name)
self.id = record[0]
self.name = str(name)
self._hexdigest = record[1]
self.description = record[2]
self.email = record[3]
self.properties = rstr(json.loads(record[4]))
def save(self):
assert self.name
assert len(self.name.split()) == 1
cursor = self.db.execute('SELECT id FROM account WHERE name=?',
self.name)
record = cursor.fetchone()
if record:
if record[0] != self.id:
raise ValueError("id mismatch for Account '%s'" % self.name)
self.db.execute('UPDATE account SET password=?,description=?,'
' email=?,properties=? WHERE id=?',
self.password,
self.description,
self.email,
json.dumps(self.properties),
self.id)
else:
cursor = self.db.execute('INSERT INTO account'
' (name,password,description,'
' email,properties)'
' VALUES(?,?,?,?,?)',
self.name,
self.password,
self.description,
self.email,
json.dumps(self.properties))
self.id = cursor.lastrowid
self.db.commit()
def get_data(self):
"Return the account data in a dictionary."
return dict(name=str(self.name),
teams=[str(t) for t in self.get_teams()],
description=self.description,
email=self.email,
properties=self.properties)
def get_teams(self):
"Return all teams this account is a member of."
assert self.id
cursor = self.db.execute('SELECT t.name'
' FROM team AS t, account_team AS at'
' WHERE t.id=at.team AND at.account=?'
' ORDER BY t.name',
self.id)
result = []
for record in cursor.fetchall():
result.append(self.db.get_team(record[0]))
return result
def set_teams(self, teamnames):
"""Set the account's teams to the ones named in the given list.
Remove from those teams not mentioned.
Add to those mentioned, and not already member of.
"""
current = set([str(t) for t in self.get_teams()])
new = set(teamnames or [])
for name in current.difference(new):
try:
team = self.db.get_team(name)
except KeyError:
pass
else:
team.remove_member(self)
for name in new.difference(current):
try:
team = self.db.get_team(name)
except KeyError:
pass
else:
team.add_member(self)
self.db.commit()
@staticmethod
def get_password_hexdigest(password):
"Convert the password to its hexdigest."
md5 = hashlib.md5(configuration.SALT)
md5.update(password)
return md5.hexdigest()
def get_password(self):
"Return the hexdigest of the password."
return self._hexdigest
def set_password(self, password):
"Set the hexdigest of the password for the account."
self._hexdigest = self.get_password_hexdigest(password)
password = property(get_password, set_password)
def check_password(self, password):
"""Raise ValueError if the password does not match.
The given password must be in the clear;
it must *not* have been converted to its hexdigest."""
if self.password:
if self.get_password_hexdigest(password) != self.password:
raise ValueError('incorrect password')
class Team(object):
"Team: group of user accounts."
def __init__(self, db, name=None):
self.db = db
if name:
self.fetch(name)
else:
self.id = None
self.name = None
self.description = None
self.properties = dict()
def __str__(self):
return self.name
def __repr__(self):
return "Team '%s'" % self.name
def fetch(self, name):
"Raise KeyError if no such team."
cursor = self.db.execute('SELECT id,description,properties'
' FROM team WHERE name=?',
name)
record = cursor.fetchone()
if not record:
raise KeyError("no such Team '%s'" % name)
self.id = record[0]
self.name = str(name)
self.description = record[1]
self.properties = rstr(json.loads(record[2]))
def save(self):
assert self.name
assert len(self.name.split()) == 1
cursor = self.db.execute('SELECT id FROM team WHERE name=?', self.name)
record = cursor.fetchone()
if record:
if record[0] != self.id:
raise ValueError("id mismatch for Team '%s'" % self.name)
self.db.execute('UPDATE team SET description=?,properties=?'
' WHERE id=?',
self.description,
json.dumps(self.properties),
self.id)
else:
cursor = self.db.execute('INSERT INTO team'
' (name,description,properties)'
' VALUES(?,?,?)',
self.name,
self.description,
json.dumps(self.properties))
self.id = cursor.lastrowid
self.db.commit()
def get_data(self):
"Return the team data in a dictionary."
return dict(name=self.name,
members=[str(m) for m in self.get_members()],
admins=[str(m) for m in self.get_admins()],
description=self.description,
properties=self.properties)
def get_members(self):
"Return all accounts being members of this team."
assert self.id
cursor = self.db.execute('SELECT a.name'
' FROM account AS a, account_team AS at'
' WHERE a.id=at.account AND at.team=?',
self.id)
return [self.db.get_account(record[0]) for record in cursor]
def get_admins(self):
"Return all accounts being admin members of this team."
assert self.id
cursor = self.db.execute('SELECT a.name'
' FROM account AS a, account_team AS at'
' WHERE a.id=at.account AND at.team=?'
' AND at.admin=1',
self.id)
return [self.db.get_account(record[0]) for record in cursor]
def add_member(self, account, admin=False):
assert self.id
assert isinstance(account, Account)
assert account.id
if self.is_member(account): return
self.db.execute('INSERT INTO account_team (account, team, admin)'
' VALUES(?,?,?)',
account.id,
self.id,
int(bool(admin)))
def remove_member(self, account):
assert self.id
assert isinstance(account, Account)
assert account.id
if not self.is_member(account): return
self.db.execute('DELETE FROM account_team WHERE account=? AND team=?',
account.id,
self.id)
def set_admin(self, account, admin=True):
assert self.id
assert isinstance(account, Account)
assert account.id
assert self.is_member(account)
self.db.execute('UPDATE account_team SET admin=?'
' WHERE account=? AND team=?',
int(bool(admin)),
account.id,
self.id)
def set_admins(self, accountnames):
"""Set the team's administrators to the ones named in the given list.
Remove administrators not mentioned.
Add administrators mentioned, and not already set.
"""
current = set([str(a) for a in self.get_admins()])
new = set(accountnames)
for name in current.difference(new):
try:
account = self.db.get_account(name)
except KeyError:
pass
else:
self.set_admin(account, admin=False)
for name in new.difference(current):
try:
account = self.db.get_account(name)
except KeyError:
pass
else:
self.set_admin(account, admin=True)
self.db.commit()
def is_member(self, account):
"Is the given account a member of this team?"
assert self.id
assert isinstance(account, Account)
assert account.id
cursor = self.db.execute('SELECT COUNT(*) FROM account_team'
' WHERE account_team.account=?'
' AND account_team.team=?',
account.id,
self.id)
return bool(cursor.fetchone()[0])
def is_admin(self, account):
"Is the given account an admin member of this team?"
assert self.id
assert isinstance(account, Account)
assert account.id
cursor = self.db.execute('SELECT COUNT(*) FROM account_team'
' WHERE account_team.account=?'
' AND account_team.team=?'
' AND account_team.admin=1',
account.id,
self.id)
return bool(cursor.fetchone()[0])
if __name__ == '__main__':
import os.path
import getpass
db = Database()
if os.path.exists(configuration.MASTER_DB_FILE):
db.open()
print 'WhoYou database exists.'
else:
db.open()
db.create()
print 'Created WhoYou database.'
password = getpass.getpass("Give password for 'admin' account > ")
admin = db.create_account('admin',
password=password,
description='Site administrator.')
team = db.create_team('admin',
description='Accounts with admin privileges.')
team.add_member(admin, admin=True)
db.create_account('anonymous',
description='Anonymous user without password.')
try:
from whoyou import tests
except ImportError:
pass
else:
db.create_account(tests.ACCOUNT,
password=tests.PASSWORD,
description='Test account.')
print 'Accounts:'
for a in db.get_accounts():
print a.get_data()
print 'Teams:'
for t in db.get_teams():
print t.get_data()
db.close()