-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrun.py
More file actions
executable file
·71 lines (56 loc) · 1.99 KB
/
Copy pathrun.py
File metadata and controls
executable file
·71 lines (56 loc) · 1.99 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
#!/usr/bin/env python
import json
import os
import datetime
import jwt
from flask import Flask, jsonify
from flask import current_app
from flask import request
app = Flask(__name__)
# In-memory user database
with open(os.path.join(os.path.dirname(__file__), 'users.json'), 'rb') as f:
users = json.load(f)
@app.route('/token', methods=['POST'])
def create_token():
"""
Authenticates a user by username and password, returning an authentication token (valid for 30s)
that can be used to make authenticated requests to other microservices.
"""
username: str = request.form.get('username')
password: str = request.form.get('password')
if not username:
return jsonify(error='Username is blank'), 422
if not password:
return jsonify(error='Password is blank'), 422
for user in users:
# Find user by username
if user['username'] == username:
# Validate password
if user['password'] == password:
payload = {
'user_id': user['id'],
'username': user['username'],
'can_transact': user['can_transact'],
'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=30), # jwt expiration time claim
}
token = jwt.encode(
payload,
current_app.config['JWT_SECRET'],
algorithm='HS256',
)
return jsonify(token=token.decode('utf-8'))
else:
return jsonify(error='Invalid password'), 401
else:
return jsonify(error='User not found'), 404
@app.route('/health')
def health():
return jsonify(healthy=True)
if __name__ == '__main__':
# Env
http_port: int = int(os.getenv('HTTP_PORT', 5000))
jwt_secret: str = os.environ['JWT_SECRET']
# Flask config
app.config['JWT_SECRET'] = jwt_secret
# Run app
app.run(host='0.0.0.0', port=http_port, threaded=True)