|
| 1 | +from requests_oauthlib import OAuth2Session |
| 2 | +from django.conf import settings |
| 3 | +from django.shortcuts import redirect, render |
| 4 | +from django.http import HttpResponseBadRequest |
| 5 | + |
| 6 | +AUTHORIZATION_BASE_URL = "https://github.com/login/oauth/authorize" |
| 7 | +TOKEN_URL = "https://github.com/login/oauth/access_token" |
| 8 | +CLIENT_ID = settings.DECAP_CMS_AUTH["OAUTH_CLIENT_ID"] |
| 9 | +CLIENT_SECRET = settings.DECAP_CMS_AUTH["OAUTH_CLIENT_SECRET"] |
| 10 | +SCOPE = settings.DECAP_CMS_AUTH["SCOPE"] |
| 11 | + |
| 12 | + |
| 13 | +def auth(request): |
| 14 | + """Redirect to Github auth""" |
| 15 | + github = OAuth2Session(client_id=CLIENT_ID, scope=SCOPE) |
| 16 | + authorization_url, _ = github.authorization_url(AUTHORIZATION_BASE_URL) |
| 17 | + return redirect(authorization_url) |
| 18 | + |
| 19 | + |
| 20 | +def callback(request): |
| 21 | + """Retrieve access token""" |
| 22 | + state = request.GET.get("state", "") |
| 23 | + try: |
| 24 | + github = OAuth2Session(CLIENT_ID, state=state, scope=SCOPE) |
| 25 | + token = github.fetch_token( |
| 26 | + TOKEN_URL, |
| 27 | + client_secret=CLIENT_SECRET, |
| 28 | + authorization_response=request.get_full_path(), |
| 29 | + ) |
| 30 | + content = {"token": token.get("access_token", ""), "provider": "github"} |
| 31 | + return render(request, "decapcms_auth/callback.html", {"content": content}) |
| 32 | + |
| 33 | + except BaseException: |
| 34 | + return HttpResponseBadRequest() |
0 commit comments