github.py 3.6 KB

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