forked from tetherless-world/whyis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthenticator.py
More file actions
83 lines (71 loc) · 2.95 KB
/
Copy pathauthenticator.py
File metadata and controls
83 lines (71 loc) · 2.95 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
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
from flask import current_app
from flask_login import AnonymousUserMixin, login_user
import datetime
class InvitedAnonymousUser(AnonymousUserMixin):
'''A user that has been referred via an external application references but does not have a user account.'''
def __init__(self):
self.roles = ImmutableList()
def has_role(self, *args):
"""Returns `False`"""
return False
def is_active(self):
return True
@property
def is_authenticated(self):
return True
class Authenticator:
def authenticate(self, request, datastore, config):
pass
class APIKeyAuthenticator:
def __init__(self, key, request_arg='API_KEY'):
self.key = key
self.request_arg = request_arg
def authenticate(self, request, datastore, config):
if self.request_arg in request.args and request.args[self.request_arg] == self.key:
print 'logging in invited user'
user = InvitedAnonymousUser()
login_user(user)
return user
default_jwt_mapping = {
'identifier':'sub',
'email': 'mail',
'admin': 'isAdmin',
'givenName' : 'givenName',
'roles' : 'roles',
'familyName' : 'sn'
}
class JWTAuthenticator:
def __init__(self, key, cookie="token", algorithm='HS256', mapping=default_jwt_mapping):
import jwt
self.jwt = jwt
self.cookie = cookie
self.key = key
self.algorithm = algorithm
self.mapping = mapping
def authenticate(self, request, datastore, config):
token = request.cookies.get(self.cookie)
if token is not None:
try:
payload = self.jwt.decode(token, self.key, algorithms=[self.algorithm])
user = datastore.get_user(identifier=payload[self.mapping['identifier']])
if user is None:
role_objects = []
if self.mapping['roles'] in payload:
role_objects = payload[self.mapping['roles']]
if self.mapping['admin'] in payload:
if payload[self.mapping['admin']] == True:
role_objects.append('admin')
user = dict(identifier=payload[self.mapping['identifier']],
email=payload[self.mapping['email']],
givenName=payload[self.mapping['givenName']],
familyName=payload[self.mapping['familyName']],
confirmed_at = datetime.datetime.utcnow(),
roles = role_objects)
#user_obj = flask.current_app.datastore.create_user(**user)
user_obj = current_app.datastore.create_user(**user)
else :
user_obj = user
login_user(user_obj)
return user_obj
except self.jwt.ExpiredSignatureError:
return None