forked from pallets-eco/flask-security-3.0
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
84 lines (62 loc) · 2.49 KB
/
utils.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
# -*- coding: utf-8 -*-
"""
utils
~~~~~
Test utils
"""
from flask import Response as BaseResponse, json
from flask_security import Security
from flask_security.utils import encrypt_password
_missing = object
def authenticate(client, email="[email protected]", password="password", endpoint=None, **kwargs):
data = dict(email=email, password=password, remember='y')
return client.post(endpoint or '/login', data=data, **kwargs)
def json_authenticate(client, email="[email protected]", password="password", endpoint=None):
data = '{"email": "%s", "password": "%s"}' % (email, password)
return client.post(endpoint or '/login', content_type="application/json", data=data)
def logout(client, endpoint=None, **kwargs):
return client.get(endpoint or '/logout', **kwargs)
def create_roles(ds):
for role in ('admin', 'editor', 'author'):
ds.create_role(name=role)
ds.commit()
def create_users(ds, count=None):
users = [('[email protected]', 'matt', 'password', ['admin'], True),
('[email protected]', 'joe', 'password', ['editor'], True),
('[email protected]', 'dave', 'password', ['admin', 'editor'], True),
('[email protected]', 'jill', 'password', ['author'], True),
('[email protected]', 'tiya', 'password', [], False),
('[email protected]', 'jess', None, [], True)]
count = count or len(users)
for u in users[:count]:
pw = u[2]
if pw is not None:
pw = encrypt_password(pw)
roles = [ds.find_or_create_role(rn) for rn in u[3]]
ds.commit()
user = ds.create_user(email=u[0], username=u[1], password=pw, active=u[4])
ds.commit()
for role in roles:
ds.add_role_to_user(user, role)
ds.commit()
def populate_data(app, user_count=None):
ds = app.security.datastore
with app.app_context():
create_roles(ds)
create_users(ds, user_count)
class Response(BaseResponse): # pragma: no cover
@property
def jdata(self):
rv = getattr(self, '_cached_jdata', _missing)
if rv is not _missing:
return rv
try:
self._cached_jdata = json.loads(self.data)
except ValueError:
raise Exception('Invalid JSON response')
return self._cached_jdata
def init_app_with_options(app, datastore, **options):
security_args = options.pop('security_args', {})
app.config.update(**options)
app.security = Security(app, datastore=datastore, **security_args)
populate_data(app)