-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
136 lines (102 loc) · 3.33 KB
/
app.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
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/')
def index():
return jsonify({
"hello": "world"
})
import boto3
session = boto3.Session()
dynDB = session.resource('dynamodb')
table = dynDB.Table('PYKC-Auth')
import bcrypt
import time
@app.route('/register', methods=['POST'])
def register():
data = request.get_json()
# REQUIRE AN EMAIL AND PASSWORD
if not data.get('email', None) or not data.get('password', False):
return jsonify({'error': 'must provide email and password'})
# VERIFY THAT THIS USER DOES NOT ALREADY EXIST
check_status = table.get_item(Key={"email": str(data['email']).upper()})
if(check_status.get('Item')):
return jsonify({'error': 'profile exists already'})
#CREATE A HASHED PASSWORD AND POST OBJECT
hashed_password = bcrypt.hashpw(str(data['password']), bcrypt.gensalt())
post_obj = {
'email': data['email'].upper(),
'password_hash': hashed_password,
'created_at': int(time.time())
}
save_user = table.put_item(
Item=post_obj
)
return jsonify({'message': 'user created'})
import jwt
import datetime
#put this in an env variable
SECRET_KEY='pykc'
@app.route('/login', methods=['POST'])
def login():
data = request.get_json()
error = {'error': 'invalid user email or password'}
if not data.get('email', None) or not data.get('password', False):
return jsonify(error)
get_user = table.get_item(Key={"email": str(data['email']).upper()})
user = get_user.get('Item', None)
if not user:
return jsonify(error)
password_hash = user.get('password_hash', None)
if not bcrypt.checkpw(str(data['password']), str(password_hash)):
return jsonify(error)
payload = jwt.encode(
{
"sub": user['email'],
"exp": datetime.datetime.utcnow() + datetime.timedelta(hours=1)
},
SECRET_KEY,
algorithm='HS256'
)
return jsonify({'token': payload})
from functools import wraps
from flask import g
def unauthorized(message):
response = jsonify({'error': 'unauthorized', 'message': message})
response.status_code = 401
return response
def AuthRequired(f):
@wraps(f)
def decorated(*args, **kwargs):
authhead = request.headers.get('Authorization', None)
if not authhead:
return unauthorized('authorization required')
data = str(authhead).encode('ascii','ignore')
token = str.replace(data, 'Bearer ', '')
try:
g.user = jwt.decode(token, SECRET_KEY, algorithms=['HS256'])
except jwt.ExpiredSignatureError:
return unauthorized('authorization error')
return f(*args, **kwargs)
return decorated
@app.route('/auth')
@AuthRequired
def authcheck():
return jsonify({"message": "wooohoo"})
lam = boto3.client('lambda')
import json
@app.route('/execute')
@AuthRequired
def execute():
payload = {
'email': g.user.get('sub', ''),
'timestamp': int(time.time())
}
send_user = lam.invoke(
FunctionName='pykc-print-user',
InvocationType='Event',
Payload=json.dumps(payload)
)
status = send_user.get('StatusCode', None)
return jsonify({'status': status, 'user': payload['email'], 'execution': 'pykc-print-user'})
if __name__ == "__main__":
app.run(debug=True)