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
25 from app import github
26 from app.models import *
27 from app.utils import loginUser
29 @bp.route("/user/github/start/")
31 return github.authorize("")
33 @bp.route("/user/github/callback/")
34 @github.authorized_handler
35 def github_authorized(oauth_token):
36 next_url = request.args.get("next")
37 if oauth_token is None:
38 flash("Authorization failed [err=gh-oauth-login-failed]", "danger")
39 return redirect(url_for("user.login"))
44 url = "https://api.github.com/user"
45 r = requests.get(url, headers={"Authorization": "token " + oauth_token})
46 username = r.json()["login"]
48 # Get user by github username
49 userByGithub = User.query.filter(func.lower(User.github_username) == func.lower(username)).first()
51 # If logged in, connect
52 if current_user and current_user.is_authenticated:
53 if userByGithub is None:
54 current_user.github_username = username
56 flash("Linked github to account", "success")
57 return redirect(url_for("homepage.home"))
59 flash("Github account is already associated with another user", "danger")
60 return redirect(url_for("homepage.home"))
62 # If not logged in, log in
64 if userByGithub is None:
65 flash("Unable to find an account for that Github user", "error")
66 return redirect(url_for("users.claim"))
67 elif loginUser(userByGithub):
68 if current_user.password is None:
69 return redirect(next_url or url_for("users.set_password", optional=True))
71 return redirect(next_url or url_for("homepage.home"))
73 flash("Authorization failed [err=gh-login-failed]", "danger")
74 return redirect(url_for("user.login"))