-
Notifications
You must be signed in to change notification settings - Fork 3
/
simple.py
85 lines (70 loc) · 2.19 KB
/
simple.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
from flask import (
Flask,
make_response,
render_template,
request,
redirect,
url_for,
)
from utils import (
create_access_token,
get_user,
setup_assets,
valid_user,
)
from typing import Any
from flask.typing import ResponseReturnValue
app = Flask(__name__)
app.config["SECRET"] = "mysecret"
app.config["ALGORITHMS"] = ["none", "HS256"]
app.config["DEFAULT_ALGORITHM"] = "HS256"
setup_assets(app)
def validate_user() -> Any:
return get_user(
request.cookies.get("access_token", ""),
app.config["SECRET"],
app.config["ALGORITHMS"],
)
@app.route("/")
@app.route("/login", methods=["GET"])
def index() -> ResponseReturnValue:
token = request.cookies.get("access_token")
if token:
try:
validate_user()
except Exception:
response = make_response(render_template("index.html"))
response.delete_cookie("access_token")
return response
else:
return redirect(url_for("protected"))
return render_template("index.html")
@app.route("/login", methods=["POST"])
def login() -> ResponseReturnValue:
username = request.form["username"]
password = request.form["password"]
if valid_user(username, password):
access_token = create_access_token(
username, app.config["SECRET"], algorithm=app.config["DEFAULT_ALGORITHM"]
)
response = make_response(redirect(url_for("protected")))
response.set_cookie("access_token", access_token)
return response
else:
return render_template("index.html", error_msg="Invalid credentials")
@app.route("/protected", methods=["GET"])
def protected() -> ResponseReturnValue:
try:
current_user = validate_user()
except Exception:
response = make_response(redirect(url_for("index")))
response.delete_cookie("access_token")
return response
return render_template("protected.html", username=current_user)
@app.route("/logout")
def logout() -> ResponseReturnValue:
response = make_response(redirect(url_for("index")))
response.delete_cookie("access_token")
return response
if __name__ == "__main__":
app.run(debug=True)