2 # Copyright (C) 2018 rubenwardy
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <https://www.gnu.org/licenses/>.
19 from flask_user import *
20 from flask_login import login_user, logout_user
21 from sqlalchemy import func
22 import flask_menu as menu
23 from flask_github import GitHub
24 from app import app, github
25 from app.models import *
26 from app.utils import loginUser
28 @app.route("/user/github/start/")
29 def github_signin_page():
30 return github.authorize("")
32 @app.route("/user/github/callback/")
33 @github.authorized_handler
34 def github_authorized(oauth_token):
35 next_url = request.args.get("next")
36 if oauth_token is None:
37 flash("Authorization failed [err=gh-oauth-login-failed]", "danger")
38 return redirect(url_for("user.login"))
43 url = "https://api.github.com/user"
44 r = requests.get(url, headers={"Authorization": "token " + oauth_token})
45 username = r.json()["login"]
47 # Get user by github username
48 userByGithub = User.query.filter(func.lower(User.github_username) == func.lower(username)).first()
50 # If logged in, connect
51 if current_user and current_user.is_authenticated:
52 if userByGithub is None:
53 current_user.github_username = username
56 return redirect(url_for("gitAccount", id=auth.id))
58 flash("Github account is already associated with another user", "danger")
59 return redirect(url_for("home_page"))
61 # If not logged in, log in
63 if userByGithub is None:
64 flash("Unable to find an account for that Github user", "error")
65 return redirect(url_for("user_claim_page"))
66 elif loginUser(userByGithub):
67 if current_user.password is None:
68 return redirect(next_url or url_for("set_password_page", optional=True))
70 return redirect(next_url or url_for("home_page"))
72 flash("Authorization failed [err=gh-login-failed]", "danger")
73 return redirect(url_for("user.login"))