-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpasswordtype.py
More file actions
43 lines (31 loc) · 1.08 KB
/
passwordtype.py
File metadata and controls
43 lines (31 loc) · 1.08 KB
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
import bcrypt
from sqlalchemy import types
def encode(s):
return s.encode('utf8')
def hashpassword(password):
return bcrypt.hashpw(encode(password), bcrypt.gensalt())
class Password(object):
def __init__(self, hashed):
self.hashed = hashed
def verify(self, password):
password = encode(password)
hashed = encode(self.hashed)
return bcrypt.hashpw(password, hashed) == hashed
def __eq__(self, password):
return self.verify(password)
def __ne__(self, password):
return not self == password
class PasswordType(types.TypeDecorator):
impl = types.VARCHAR
python_type = Password
def process_bind_param(self, value, dialect):
if isinstance(value, Password):
r = value.hashed
elif isinstance(value, basestring):
r = hashpassword(value)
else:
raise RuntimeError('Unable to process bind parameter: %s.' % (value, ))
return encode(r)
def process_result_value(self, value, dialect):
if value is not None:
return Password(value)