-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathapp.py
99 lines (77 loc) · 2.62 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
import json
import os
from flask import Flask, flash, redirect, render_template, request, session, url_for
import workos
# Flask Setup
app = Flask(__name__)
app.secret_key = os.getenv("APP_SECRET_KEY")
base_api_url = os.getenv("WORKOS_BASE_API_URL")
# WorkOS Setup
workos_client = workos.WorkOSClient(
api_key=os.getenv("WORKOS_API_KEY"),
client_id=os.getenv("WORKOS_CLIENT_ID"),
base_url=base_api_url,
)
# Enter Organization ID here
CUSTOMER_ORGANIZATION_ID = "" # Use org_test_idp for testing
def to_pretty_json(value):
return json.dumps(value, sort_keys=True, indent=4)
app.jinja_env.filters["tojson_pretty"] = to_pretty_json
@app.route("/")
def login():
try:
return render_template(
"login_successful.html",
first_name=session["first_name"],
raw_profile=session["raw_profile"],
)
except KeyError:
if "error" in session:
return render_template(
"login.html",
error=session.pop("error"),
error_description=session.pop("error_description"),
error_uri=session.pop("error_uri"),
)
else:
return render_template("login.html")
@app.route("/auth", methods=["POST"])
def auth():
login_type = request.form.get("login_method")
if login_type not in (
"saml",
"GoogleOAuth",
"MicrosoftOAuth",
):
return redirect("/")
redirect_uri = url_for("auth_callback", _external=True)
authorization_url = (
workos_client.sso.get_authorization_url(
redirect_uri=redirect_uri, organization_id=CUSTOMER_ORGANIZATION_ID
)
if login_type == "saml"
else workos_client.sso.get_authorization_url(
redirect_uri=redirect_uri, provider=login_type
)
)
return redirect(authorization_url)
@app.route("/auth/callback")
def auth_callback():
if "error" in request.args:
session["error_description"] = request.args.get("error_description")
session["error_uri"] = request.args.get("error_uri")
session["error"] = request.args.get("error")
code = request.args.get("code")
# Why do I always get an error that the target does not belong to the target organization?
if code is None:
return redirect("/")
profile = workos_client.sso.get_profile_and_token(code).profile
session["first_name"] = profile.first_name
session["raw_profile"] = profile.dict()
session["session_id"] = profile.id
return redirect("/")
@app.route("/logout")
def logout():
session.clear()
session["raw_profile"] = ""
return redirect("/")