github.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. from flask import request, session, redirect, flash
  2. from flask_login import login_user
  3. from requests_oauthlib import OAuth2Session
  4. from app import email_utils
  5. from app.auth.base import auth_bp
  6. from app.auth.views.login_utils import after_login
  7. from app.config import GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, URL
  8. from app.extensions import db
  9. from app.log import LOG
  10. from app.models import User
  11. from app.utils import encode_url
  12. _authorization_base_url = "https://github.com/login/oauth/authorize"
  13. _token_url = "https://github.com/login/oauth/access_token"
  14. # need to set explicitly redirect_uri instead of leaving the lib to pre-fill redirect_uri
  15. # when served behind nginx, the redirect_uri is localhost... and not the real url
  16. _redirect_uri = URL + "/auth/github/callback"
  17. @auth_bp.route("/github/login")
  18. def github_login():
  19. next_url = request.args.get("next")
  20. if next_url:
  21. redirect_uri = _redirect_uri + "?next=" + encode_url(next_url)
  22. else:
  23. redirect_uri = _redirect_uri
  24. github = OAuth2Session(
  25. GITHUB_CLIENT_ID, scope=["user:email"], redirect_uri=redirect_uri
  26. )
  27. authorization_url, state = github.authorization_url(_authorization_base_url)
  28. # State is used to prevent CSRF, keep this for later.
  29. session["oauth_state"] = state
  30. return redirect(authorization_url)
  31. @auth_bp.route("/github/callback")
  32. def github_callback():
  33. # user clicks on cancel
  34. if "error" in request.args:
  35. flash("Please use another sign in method then", "warning")
  36. return redirect("/")
  37. github = OAuth2Session(
  38. GITHUB_CLIENT_ID,
  39. state=session["oauth_state"],
  40. scope=["user:email"],
  41. redirect_uri=_redirect_uri,
  42. )
  43. token = github.fetch_token(
  44. _token_url,
  45. client_secret=GITHUB_CLIENT_SECRET,
  46. authorization_response=request.url,
  47. )
  48. # a dict with "name", "login"
  49. github_user_data = github.get("https://api.github.com/user").json()
  50. LOG.d("user login with github %s", github_user_data)
  51. # return list of emails
  52. # {
  53. # 'email': 'abcd@gmail.com',
  54. # 'primary': False,
  55. # 'verified': True,
  56. # 'visibility': None
  57. # }
  58. emails = github.get("https://api.github.com/user/emails").json()
  59. # only take the primary email
  60. email = None
  61. for e in emails:
  62. if e.get("verified") and e.get("primary"):
  63. email = e.get("email")
  64. break
  65. if not email:
  66. raise Exception("cannot get email for github user")
  67. user = User.get_by(email=email)
  68. # create user
  69. if not user:
  70. LOG.d("create github user")
  71. user = User.create(
  72. email=email, name=github_user_data.get("name") or "", activated=True
  73. )
  74. db.session.commit()
  75. login_user(user)
  76. email_utils.send_welcome_email(user.email, user.name)
  77. flash(f"Welcome to SimpleLogin {user.name}!", "success")
  78. # The activation link contains the original page, for ex authorize page
  79. next_url = request.args.get("next") if request.args else None
  80. return after_login(user, next_url)