-
Notifications
You must be signed in to change notification settings - Fork 17
/
auth.py
119 lines (84 loc) · 2.61 KB
/
auth.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
import eventlet
import eventlet.db_pool
import base64
import hashlib
import os
from psycopg2 import IntegrityError
import logging
class Auth(object):
def __init__(self,salt):
self.salt = salt
self.log = logging.getLogger('fairywren.auth')
self.log.info('Created')
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 setConnectionPool(self,pool):
self.connPool = pool
def isUserMemberOfRole(self,userId,roles):
with self.connPool.item() as conn:
cur = conn.cursor()
cur.execute("SELECT roles.name from rolemember left join roles on roles.id=rolemember.roleid where userid=%s;",(userId,));
retVal = False
for role, in iter(cur.fetchone,None):
if role in roles:
retVal = True
conn.rollback()
cur.close()
return retVal
def changePassword(self,userId,pwHash):
saltedPw = self._saltPwhash(pwHash)
with self.connPool.item() as conn:
cur = conn.cursor()
try:
cur.execute("UPDATE users SET password=%s where id=%s;",
(saltedPw,userId,))
except StandardError as e :
self.log.error(e)
return None
finally:
conn.commit()
cur.close()
return True
def authenticateSecretKey(self,key):
with self.connPool.item() as conn:
cur = conn.cursor()
cur.execute("Select id from users where secretKey=%s and password is not null;",
(base64.urlsafe_b64encode(key).replace('=','') ,))
r = cur.fetchone()
if r != None:
r, = r
cur.close()
conn.rollback()
return r
def authorizeInfoHash(self,info_hash):
with self.connPool.item() as conn:
cur = conn.cursor()
cur.execute("Select id from torrents where infoHash=%(infoHash)s",
{'infoHash' : base64.urlsafe_b64encode(info_hash).replace('=','') })
result = cur.fetchone()
cur.close()
conn.rollback()
if result!= None:
result, = result
return result
def authenticateUser(self,username,password):
passwordHash = hashlib.sha512()
passwordHash.update(self.salt)
passwordHash.update(password)
passwordHash = base64.urlsafe_b64encode(passwordHash.digest()).replace('=','')
with self.connPool.item() as conn:
cur = conn.cursor()
cur.execute("Select id from users where name=%s and password=%s ;",
(username,passwordHash))
allowed = cur.fetchone()
cur.close()
conn.rollback()
if allowed == None:
return None
userId, = allowed
return userId