-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathusers.py
431 lines (368 loc) · 13.3 KB
/
users.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
import eventlet
import fairywren
import hashlib
import psycopg2
import logging
import os
import base64
class UserAlreadyExists(BaseException):
pass
class Users(object):
def __init__(self,salt):
self.salt = salt
self.connPool = None
self.log = logging.getLogger('fairywren.users')
self.log.info('Created')
def createRoles(self,roles):
numCreated = 0
with self.connPool.item() as conn:
for role in roles:
with conn.cursor() as cur:
try:
cur.execute("Select id from roles where name=%s;",(role,))
except psycopg2.DatabaseError as e:
conn.rollback()
self.log.exception('Failed checking for role %s',role, exc_info=True)
raise
result = cur.fetchone()
if result == None:
try:
cur.execute("Insert into roles (name) VALUES(%s);",(role,))
except psycopg2.DatabaseError as e:
conn.rollback()
self.log.exception('Failed creating role %s',role, exc_info=True)
raise
self.log.info("Created role %s",role)
numCreated += 1
conn.commit()
else:
conn.rollback()
return numCreated
def setUserRoles(self,roles,uid):
roles = set(roles)
with self.connPool.item() as conn:
with conn.cursor() as cur:
try:
cur.execute("Select roles.name from rolemember left join roles on rolemember.roleid = roles.id where rolemember.userid = %s",(uid,))
except psycopg2.DatabaseError as e:
self.log.exception('Failed getting roles for user:%.x',uid)
raise
else:
existingRoles = set()
for row in cur:
role, = row
existingRoles.add(role)
finally:
conn.rollback()
addRoles = roles.difference(existingRoles)
removeRoles = existingRoles.difference(roles)
for role in addRoles:
try:
cur.execute("Select id from roles where name = %s",(role,));
except psycopg2.DatabaseError as e:
self.log.exception('Failed selecting role %s',role,exc_info=True)
raise
else:
result = cur.fetchone()
if result == None:
raise ValueError('Role %s does not exist' % role)
roleid, = result
finally:
conn.rollback()
try:
cur.execute("Insert into rolemember(roleid,userid) VALUES(%s,%s) returning userid;",(roleid,uid))
except psycopg2.IntegrityError as e:
conn.rollback()
#The string '23503' is specified in the postgre documentation appendix
#'PostgreSQL Error Codes'. It indicates foreign_key_violation.
#This means the user does not exist.
if e.pgcode == '23503':
self.log.exception('Failed add uid:%x to role %s. User does not exist',uid,role,exc_info=True)
raise ValueError('User with uid:%x does not exist' % uid)
else:
self.log.exception('Failed adding uid:%x to role %s',uid,role,exc_info=True)
raise
else:
conn.commit()
for role in removeRoles:
try:
cur.execute("Select id from roles where name = %s",(role,));
except psycopg2.DatabaseError as e:
self.log.exception('Failed selecting role %s',role,exc_info=True)
raise
else:
result = cur.fetchone()
if result == None:
raise ValueError('Role %s does not exist' % role)
roleid, = result
finally:
conn.rollback()
try:
cur.execute("Delete from rolemember where userid = %s and roleid = %s ;",(uid,roleid));
except psycopg2.DatabaseError as e:
conn.rollback()
self.log.exception('Failed removing uid:%x from role %s',uid,role,exc_info=True)
raise
conn.commit()
return len(addRoles),len(removeRoles)
def getUserRoles(self,uid):
with self.connPool.item() as conn:
with conn.cursor() as cur:
try:
cur.execute('Select roles.name from rolemember left join roles on roles.id = rolemember.roleid where userid = %s',(uid,));
except psycopg2.DatabaseError as e:
self.log.exception('Failed getting roles for user:%.x',uid)
raise
else:
roles = []
for result in cur:
role, = result
roles.append(role)
finally:
conn.rollback()
return roles
def addUserToRole(self,role,uid):
with self.connPool.item() as conn:
with conn.cursor() as cur:
try:
cur.execute("Insert into rolemember (roleid,userid) select roles.id, %s from roles where name = %s returning userid;",(uid,role))
except psycopg2.IntegrityError as e:
conn.rollback()
#The string '23505' is specified in the postgre documentation appendix
# 'PostgreSQL Error Codes' as 'unique_violation' and corresponds
#to primary key violations. If this occurs it just means
#the user is already a member of the role. So it can safely be ignored.
#The string '23503' indicates foreign_key_violation. This means the user
# does not exist and should not be ignored
if e.pgcode == '23505':
return
elif e.pgcode == '23503':
self.log.exception('Failed add uid:%x to role %s. User does not exist',uid,role,exc_info=True)
raise ValueError('User with uid:%x does not exist' % uid)
else:
self.log.exception('Failed adding uid:%x to role %s',uid,role,exc_info=True)
raise
except psycopg2.DatabaseError as e:
conn.rollback()
self.log.exception('Failed adding uid:%x to role %s',uid,role,exc_info=True)
raise
result = cur.fetchone()
if result == None:
conn.rollback()
raise ValueError('Role %s does not exist' % role);
conn.commit()
def removeUserFromRole(self,role,uid):
with self.connPool.item() as conn:
with conn.cursor() as cur:
try:
cur.execute("Select id from roles where name = %s",(role,));
except psycopg2.DatabaseError as e:
conn.rollback()
self.log.exception('Failed selecting role %s',role,exc_info=True)
raise
else:
result = cur.fetchone()
if result == None:
raise ValueError('Role %s does not exist' % role)
roleid, = result
finally:
conn.rollback()
try:
cur.execute("Delete from rolemember where userid = %s and roleid = %s ;",(uid,roleid));
except psycopg2.DatabaseError as e:
conn.rollback()
self.log.exception('Failed removing uid:%x from role %s',uid,role,exc_info=True)
raise
conn.commit()
def setConnectionPool(self,pool):
self.connPool = pool
def _saltPwhash(self,pwHash):
if len(pwHash) != 64:
raise ValueError('password hash should be 64 bytes')
storedHash = hashlib.sha512()
storedHash.update(self.salt)
storedHash.update(pwHash)
return base64.urlsafe_b64encode(storedHash.digest()).replace('=','')
def _genSecretKey(self):
secretKey = hashlib.sha512()
randomValue = os.urandom(1024)
secretKey.update(randomValue)
return base64.urlsafe_b64encode(secretKey.digest()).replace('=','')
def addUser(self,username,pwHash):
'''
username - string, username of new user
pwHash - string, 64 byte password
'''
self.log.debug('Trying to add user %s',username)
secretKey = self._genSecretKey()
saltedPw = self._saltPwhash(pwHash)
with self.connPool.item() as conn:
with conn.cursor() as cur:
try:
cur.execute("INSERT into users (name,password,secretKey) VALUES(%s,%s,%s) returning users.id;",
(username,
saltedPw,
secretKey,) )
except psycopg2.IntegrityError as e:
conn.rollback()
#This string is specified in the postgre documentation appendix
# 'PostgreSQL Error Codes' as 'unique_violation' and corresponds
#to primary key violations
if e.pgcode == '23505':
raise UserAlreadyExists('User with that username already exists')
self.log.exception('Failed adding new user',exc_info=True)
raise
except psycopg2.DatabaseError as e:
conn.rollback()
self.log.exception('Failed adding new user',exc_info=True)
raise
conn.commit()
newId, = cur.fetchone()
self.log.debug('Added user, new id %.8x', newId)
return 'api/users/%.8x' % newId,newId
def claimInvite(self,inviteSecret,username,pwHash):
'''
inviteSecret - string, 32 bytes
username - string, username of new user
pwHash - string, 64 byte password
'''
self.log.debug('Trying to claim invite and create user %s',username)
secretKey = self._genSecretKey()
saltedPw = self._saltPwhash(pwHash)
inviteSecret = base64.urlsafe_b64encode(inviteSecret).replace('=','')
with self.connPool.item() as conn:
with conn.cursor() as cur:
try:
cur.execute('INSERT into users (name,password,secretkey) VALUES(%s,%s,%s) returning users.id;',
(username,saltedPw,secretKey,))
uid, = cur.fetchone()
except psycopg2.IntegrityError as e:
conn.rollback()
#This string is specified in the postgre documentation appendix
# 'PostgreSQL Error Codes' as 'unique_violation' and corresponds
#to primary key violations
if e.pgcode == '23505':
raise UserAlreadyExists('User with that username already exists')
self.log.exception('Failed adding new user',exc_info=True)
raise
except psycopg2.DatabaseError as e:
conn.rollback()
self.log.exception('Failed adding new user',exc_info=True)
raise
try:
cur.execute("UPDATE INVITES set invitee = %s , accepted = timezone('UTC',CURRENT_TIMESTAMP) where secret = %s and invitee is null returning 1;",
(uid,
inviteSecret,))
success = cur.fetchone()
except psycopg2.DatabaseError as e:
conn.rollback()
self.log.exception('Failed accepting invite',exc_info = True)
raise
if success==None:
conn.rollback()
raise ValueError('Invite does not exist or has already been claimed')
conn.commit()
self.log.info('Claimed invite for user %s (%.8x)',username,uid)
return fairywren.USER_FMT % uid
def listInvitesByUser(self,userId):
with self.connPool.item() as conn:
with conn.cursor() as cur:
try:
cur.execute('Select creationdate,secret FROM invites WHERE inviter = %s and invitee is null order by creationdate desc;',(userId,))
except psycopg2.DatabaseError as e:
self.log.exception('Failed listing invites for user %.8x',userId,exc_info=True)
raise
else:
for row in cur:
created,secret = row
secret = base64.urlsafe_b64decode(secret + '=')
yield {'created' : created, 'href' : fairywren.INVITE_FMT % secret}
finally:
conn.rollback()
def getInviteState(self,inviteSecret):
'''
inviteSecret -- string, 32 bytes identifying the invite
Returns True if claimed, False if not
'''
inviteSecret = base64.urlsafe_b64encode(inviteSecret).replace('=','')
with self.connPool.item() as conn:
with conn.cursor() as cur:
try:
cur.execute("Select invitee from invites WHERE secret = %s;", (inviteSecret,))
except psycopg2.DatabaseError as e:
self.log.exception('Failed creating invite',exc_info=True)
raise
else:
row = cur.fetchone()
finally:
conn.rollback()
if row == None:
raise ValueError('No invite exists with that secret')
invitee, = row
return None != invitee
def createInvite(self,creatorId):
h = hashlib.md5()
h.update(os.urandom(1024))
h.update(str(creatorId))
h.update(self.salt)
secret = h.digest()
h.update(h.digest())
h.update(os.urandom(1024))
secret += h.digest()
with self.connPool.item() as conn:
with conn.cursor() as cur:
try:
cur.execute("INSERT into invites (secret,inviter,creationdate) VALUES(%s,%s,timezone('UTC',CURRENT_TIMESTAMP));" , (base64.urlsafe_b64encode(secret).replace('=',''),creatorId,))
except psycopg2.IntegrityError as e:
conn.rollback()
# 'foreign_key_violation' - violation of 'inviter' foreign key
# i.e. user with uid doesn't exist
if e.pgcode == '23503':
raise ValueError('User does not exist with that uid')
self.log.exception('Failed creating invite',exc_info=True)
raise
except psycopg2.DatabaseError as e:
conn.rollback()
self.log.exception('Failed creating invite',exc_info=True)
raise
conn.commit()
self.log.info('Created invite for user %.8x',creatorId)
return fairywren.INVITE_FMT % secret
def getInfo(self,idNumber):
with self.connPool.item() as conn:
with conn.cursor() as cur:
try:
cur.execute("Select users.name,count(torrents.creator) from users left join torrents on (torrents.creator=users.id) where users.id=%s group by users.name;",(idNumber,))
except psycopg2.DatabaseError as e:
self.log.exception('Failed getting info for user',exc_info=True)
raise
else:
result = cur.fetchone()
finally:
conn.rollback()
retval = {}
if result == None:
return None
else:
name,numberOfTorrents = result
retval = {'numberOfTorrents' : numberOfTorrents,
'name':name,
'password' : {'href' : fairywren.USER_PASSWORD_FMT % idNumber },
'invites' : {'href' : fairywren.USER_INVITES_FMT % idNumber } }
return retval
def getUsername(self,idNumber):
with self.connPool.item() as conn:
with conn.cursor() as cur:
try:
cur.execute("Select name from users where users.id = %s;",(idNumber,))
except psycopg2.DatabaseError as e:
self.log.exception('Failed getting name of user',exc_info=True)
raise
else:
result = cur.fetchone()
finally:
conn.rollback()
if result == None:
return None
username, = result
return username