-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.py
75 lines (58 loc) · 1.95 KB
/
server.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
import jwt, datetime, os
from flask import Flask, request
from flask_mysqldb import MySQL
server = Flask(__name__)
mysql = MySQL(server)
# config
server.config["MYSQL_HOST"] = os.environ.get("MYSQL_HOST")
server.config["MYSQL_USER"] = os.environ.get("MYSQL_USER")
server.config["MYSQL_PASSWORD"] = os.environ.get("MYSQL_PASSWORD")
server.config["MYSQL_DB"] = os.environ.get("MYSQL_DB")
server.config["MYSQL_PORT"] = os.environ.get("MYSQL_PORT")
@server.route("/login", methods=["POST"])
def login():
auth = request.authorization
if not auth:
return "missing credentials", 401
# check db for username and password
cur = mysql.connection.cursor()
res = cur.execute(
"SELECT email, password FROM user WHERE email=%s", (auth.username,)
)
if res > 0:
user_row = cur.fetchone()
email = user_row[0]
password = user_row[1]
if auth.username != email or auth.password != password:
return "invalid credentials", 401
else:
return createJWT(auth.username, os.environ.get("JWT_SECRET"), True)
else:
return "invalide credentials", 401
@server.route("/validate", methods=["POST"])
def validate():
encoded_jwt = request.headers["Authorization"]
if not encoded_jwt:
return "missing credentials", 401
encoded_jwt = encoded_jwt.split(" ")[1]
try:
decoded = jwt.decode(
encoded_jwt, os.environ.get("JWT_SECRET"), algorithms=["HS256"]
)
except:
return "not authorized", 403
return decoded, 200
def createJWT(username, secret, authz):
return jwt.encode(
{
"username": username,
"exp": datetime.datetime.now(tz=datetime.timezone.utc)
+ datetime.timedelta(days=1),
"iat": datetime.datetime.utcnow(),
"admin": authz,
},
secret,
algorithm="HS256",
)
if __name__ == "__main__":
server.run(host="0.0.0.0", port=5000)