-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
80 lines (59 loc) · 2.37 KB
/
Copy pathapp.py
File metadata and controls
80 lines (59 loc) · 2.37 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
72
73
74
75
76
77
78
79
80
"""Flask app that demonstrates the Authorization Code Grant Flow."""
from flask import session, redirect, render_template, Flask, request, current_app
from auth.proof_key_for_token_exchange import generate_pkce, build_authorization_server_url
from auth.token import ensure_fresh_token, store_token
from auth.user_info import get_user_info
from services.oidc import get_token_request, logout_request
from settings import SECRET_KEY, OIDC_BASE_AUTH_URL, REALM, CLIENT_ID, REDIRECT_URI
app = Flask(__name__)
app.config.from_pyfile("settings.py")
app.secret_key = SECRET_KEY
AUTH_URL = f"{OIDC_BASE_AUTH_URL}/realms/{REALM}/protocol/openid-connect/auth"
@app.route("/")
def index():
"""
Home
Here the user will be welcomed and can log in or log out.
:return: If there is a session, it will render the user information.
"""
if "access_token" in session:
ensure_fresh_token()
get_user_info(session.get("access_token"))
return render_template("index.html", session=session, pretty=session.get("userinfo"))
return render_template("index.html", session=None)
@app.route("/login")
def login():
"""
It will generate a code_verifier and code_challenge to build the redirection URL
:return: redirect to the AuthN server for the user to perform a login.
"""
code_verifier, code_challenge = generate_pkce()
session['code_verifier'] = code_verifier
authn_server_url = build_authorization_server_url(
AUTH_URL, CLIENT_ID, REDIRECT_URI, code_challenge)
current_app.logger.info(f"Redirecting to: {authn_server_url}")
return redirect(authn_server_url)
@app.route("/callback")
def callback():
"""
During AuthN, it will request the token and save it in the session.
:return: redirect Home
"""
if "error" in request.args:
return f"Error: {request.args['error']}"
code = request.args.get("code")
code_verifier = session.pop("code_verifier", None)
token_json = get_token_request(code, code_verifier)
store_token(token_json)
return redirect("/")
@app.route("/logout")
def logout():
"""
Will end the user session in the AuthN server and clear the session in the app
:return: redirects Home
"""
if logout_request(session.get("refresh_token")):
session.clear()
return redirect("/")
if __name__ == "__main__":
app.run(host="0.0.0.0", port=3000, debug=True)