-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.py
84 lines (60 loc) · 2.39 KB
/
main.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
import os
import pathlib
import requests
from flask import Flask, session, abort, redirect, request
from google.oauth2 import id_token
from google_auth_oauthlib.flow import Flow
from pip._vendor import cachecontrol
import google.auth.transport.requests
app = Flask("Google Login App")
app.secret_key = "<Add your own unique secret key here>" # make sure this matches with that's in client_secret.json
os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1" # to allow Http traffic for local dev
GOOGLE_CLIENT_ID = "<Add your own unique Google Client Id from the client_secret.json here>"
client_secrets_file = os.path.join(pathlib.Path(__file__).parent, "client_secret.json")
flow = Flow.from_client_secrets_file(
client_secrets_file=client_secrets_file,
scopes=["https://www.googleapis.com/auth/userinfo.profile", "https://www.googleapis.com/auth/userinfo.email", "openid"],
redirect_uri="http://localhost/callback"
)
def login_is_required(function):
def wrapper(*args, **kwargs):
if "google_id" not in session:
return abort(401) # Authorization required
else:
return function()
return wrapper
@app.route("/login")
def login():
authorization_url, state = flow.authorization_url()
session["state"] = state
return redirect(authorization_url)
@app.route("/callback")
def callback():
flow.fetch_token(authorization_response=request.url)
if not session["state"] == request.args["state"]:
abort(500) # State does not match!
credentials = flow.credentials
request_session = requests.session()
cached_session = cachecontrol.CacheControl(request_session)
token_request = google.auth.transport.requests.Request(session=cached_session)
id_info = id_token.verify_oauth2_token(
id_token=credentials._id_token,
request=token_request,
audience=GOOGLE_CLIENT_ID
)
session["google_id"] = id_info.get("sub")
session["name"] = id_info.get("name")
return redirect("/protected_area")
@app.route("/logout")
def logout():
session.clear()
return redirect("/")
@app.route("/")
def index():
return "Hello World <a href='/login'><button>Login</button></a>"
@app.route("/protected_area")
@login_is_required
def protected_area():
return f"Hello {session['name']}! <br/> <a href='/logout'><button>Logout</button></a>"
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, debug=True)