-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
94 lines (74 loc) · 2.84 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
import logging
from flask import Flask, request, redirect, flash, url_for
from flask import session, make_response, g
from flask import current_app
from forms import RegistrationForm, LoginForm
from keycloak_utils import get_admin, create_user, get_oidc, get_token, check_token
logging.basicConfig(level=logging.DEBUG)
app = Flask(__name__)
app.config.from_object("settings")
@app.before_request
def load_user():
g.username = session.get("username")
g.access_token = session.get("access_token")
@app.route("/")
def home():
return "HOME"
@app.route("/login", methods=["GET", "POST"])
def login():
form = LoginForm(request.form)
if request.method == "POST" and form.validate():
oidc_obj = get_oidc()
token = get_token(oidc_obj, form.username.data, form.password.data)
print("\nTOKEN: %s\n" % token)
response = make_response(redirect(url_for("home")))
if token:
response.set_cookie("access_token", token["access_token"])
session["access_token"] = token["access_token"]
session["username"] = form.username.data
return response
return "LOGIN FAILED"
@app.route("/logout")
def logout():
session.pop("username", None)
session.pop("access_token", None)
return redirect(url_for("home"))
@app.route("/register", methods=["GET", "POST"])
def register():
form = RegistrationForm(request.form)
if request.method == "POST" and form.validate():
admin = get_admin()
create_user(admin, form.username.data, form.email.data, form.password.data)
flash("Thanks for registering")
return "Registration successful"
return "Registration failed"
@app.route("/headers")
def headers():
return dict(request.headers)
@app.route("/protected")
def protected():
resp = "Forbidden!"
access_token = session.get("access_token")
if access_token:
if check_token(access_token):
headers = {"Authorization": "Bearer " + access_token}
resp = "Protected resource is accessible. Yay! Here is the response: Hello"
return resp
@app.route("/rbac")
def rbac():
resp = "Forbidden!"
access_token = session.get("access_token")
oidc_obj = get_oidc()
oidc_obj.load_authorization_config("test-authz-config.json")
policies = oidc_obj.get_policies(access_token)
print("\nPOLICIES: %s\n" % policies)
permissions = oidc_obj.get_permissions(access_token, method_token_info="introspect")
print("\nPERMISSIONS: %s\n" % permissions)
resourrceBasedPermissions = oidc_obj.uma_permissions(
access_token, "Protected-Resource"
) # check permissions for specific resource
print("\nRESOURCE BASED PERMISSIONS: %s\n" % resourrceBasedPermissions)
if resourrceBasedPermissions:
resp = "You have permissions to access this resource."
return resp
return "Forbidden!"