-
Notifications
You must be signed in to change notification settings - Fork 11
/
main.py
64 lines (47 loc) · 1.58 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
# main.py
from flask import Flask, jsonify, redirect, render_template, url_for
from flask_dance.contrib.github import github
from flask_dance.contrib.google import google
from flask_login import logout_user, login_required
from oauthlib.oauth2.rfc6749.errors import TokenExpiredError
from app.models import db, login_manager
from app.oauth import github_blueprint, google_blueprint
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///./users.db"
app.secret_key = "supersecretkey"
app.register_blueprint(github_blueprint, url_prefix="/login")
app.register_blueprint(google_blueprint, url_prefix="/login")
db.init_app(app)
login_manager.init_app(app)
with app.app_context():
db.create_all()
@app.route("/ping")
def ping():
return jsonify(ping="pong")
@app.route("/")
def homepage():
return render_template("index.html")
@app.route("/github")
def login_github():
if not github.authorized:
return redirect(url_for("github.login"))
res = github.get("/user")
username = res.json()["login"]
return f"You are @{username} on GitHub"
@app.route("/google")
def login_google():
try:
if not google.authorized:
return redirect(url_for("google.login"))
res = google.get("/oauth2/v2/userinfo")
username = res.json()["email"]
return f"You are @{username} on Google"
except TokenExpiredError as e:
return redirect(url_for("google.login"))
@app.route("/logout")
@login_required
def logout():
logout_user()
return redirect(url_for("homepage"))
if __name__ == "__main__":
app.run(debug=True)