forked from GoogleCloudPlatform/bank-of-anthos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuserservice.py
214 lines (182 loc) · 6.79 KB
/
userservice.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
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Userservice manages user account creation, user login, and related tasks
"""
import atexit
from datetime import datetime, timedelta
import logging
import os
import sys
from flask import Flask, jsonify, request
import bleach
import bcrypt
import jwt
from db import UserDb
from sqlalchemy.exc import OperationalError, SQLAlchemyError
def create_app():
"""Flask application factory to create instances
of the Userservice Flask App
"""
app = Flask(__name__)
# Disabling unused-variable for lines with route decorated functions
# as pylint thinks they are unused
# pylint: disable=unused-variable
@app.route('/version', methods=['GET'])
def version():
"""
Service version endpoint
"""
return app.config['VERSION'], 200
@app.route('/ready', methods=['GET'])
def readiness():
"""
Readiness probe
"""
return 'ok', 200
@app.route('/users', methods=['POST'])
def create_user():
"""Create a user record.
Fails if that username already exists.
Generates a unique accountid.
request fields:
- username
- password
- password-repeat
- firstname
- lastname
- birthday
- timezone
- address
- state
- zip
- ssn
"""
try:
req = {k: bleach.clean(v) for k, v in request.form.items()}
__validate_new_user(req)
# Check if user already exists
if users_db.get_user(req['username']) is not None:
raise NameError('user {} already exists'.format(req['username']))
# Create password hash with salt
password = req['password']
salt = bcrypt.gensalt()
passhash = bcrypt.hashpw(password.encode('utf-8'), salt)
accountid = users_db.generate_accountid()
# Create user data to be added to the database
user_data = {
'accountid': accountid,
'username': req['username'],
'passhash': passhash,
'firstname': req['firstname'],
'lastname': req['lastname'],
'birthday': req['birthday'],
'timezone': req['timezone'],
'address': req['address'],
'state': req['state'],
'zip': req['zip'],
'ssn': req['ssn'],
}
# Add user_data to database
users_db.add_user(user_data)
except UserWarning as warn:
return jsonify({'msg': str(warn)}), 400
except NameError as err:
return jsonify({'msg': str(err)}), 409
except SQLAlchemyError as err:
app.logger.error(err)
return jsonify({'msg': 'failed to create user'}), 500
return jsonify({}), 201
def __validate_new_user(req):
app.logger.debug('validating create user request: %s', str(req))
# Check if required fields are filled
fields = (
'username',
'password',
'password-repeat',
'firstname',
'lastname',
'birthday',
'timezone',
'address',
'state',
'zip',
'ssn',
)
if any(f not in req for f in fields):
raise UserWarning('missing required field(s)')
if any(not bool(req[f] or req[f].strip()) for f in fields):
raise UserWarning('missing value for input field(s)')
# Check if passwords match
if not req['password'] == req['password-repeat']:
raise UserWarning('passwords do not match')
@app.route('/login', methods=['GET'])
def login():
"""Login a user and return a JWT token
Fails if username doesn't exist or password doesn't match hash
token expiry time determined by environment variable
request fields:
- username
- password
"""
username = bleach.clean(request.args.get('username'))
password = bleach.clean(request.args.get('password'))
# Get user data
try:
user = users_db.get_user(username)
if user is None:
raise LookupError('user {} does not exist'.format(username))
# Validate the password
if not bcrypt.checkpw(password.encode('utf-8'), user['passhash']):
raise PermissionError('invalid login')
full_name = '{} {}'.format(user['firstname'], user['lastname'])
exp_time = datetime.utcnow() + timedelta(seconds=app.config['EXPIRY_SECONDS'])
payload = {
'user': username,
'acct': user['accountid'],
'name': full_name,
'iat': datetime.utcnow(),
'exp': exp_time,
}
token = jwt.encode(payload, app.config['PRIVATE_KEY'], algorithm='RS256')
return jsonify({'token': token.decode("utf-8")}), 200
except LookupError as err:
return jsonify({'msg': str(err)}), 404
except PermissionError as err:
return jsonify({'msg': str(err)}), 401
except SQLAlchemyError as err:
app.logger.error(err)
return jsonify({'msg': 'failed to retrieve user information'}), 500
@atexit.register
def _shutdown():
"""Executed when web app is terminated."""
app.logger.info("Stopping flask.")
# Set up logger
app.logger.handlers = logging.getLogger('gunicorn.error').handlers
app.logger.setLevel(logging.getLogger('gunicorn.error').level)
app.config['VERSION'] = os.environ.get('VERSION')
app.config['EXPIRY_SECONDS'] = int(os.environ.get('TOKEN_EXPIRY_SECONDS'))
app.config['PRIVATE_KEY'] = open(os.environ.get('PRIV_KEY_PATH'), 'r').read()
app.config['PUBLIC_KEY'] = open(os.environ.get('PUB_KEY_PATH'), 'r').read()
# Configure database connection
try:
users_db = UserDb(os.environ.get("ACCOUNTS_DB_URI"), app.logger)
except OperationalError:
app.logger.critical("database connection failed")
sys.exit(1)
return app
if __name__ == "__main__":
# Create an instance of flask server when called directly
USERSERVICE = create_app()
USERSERVICE.run()