|
@@ -1,5 +1,54 @@
|
|
from django.http import HttpResponse
|
|
from django.http import HttpResponse
|
|
|
|
+from django.shortcuts import redirect
|
|
|
|
+from django.urls import reverse
|
|
|
|
+import google_auth_oauthlib.flow
|
|
|
|
+from django.contrib.auth.decorators import login_required
|
|
|
|
|
|
|
|
+from .models import UserModel
|
|
|
|
|
|
|
|
+
|
|
|
|
+@login_required
|
|
def index(request):
|
|
def index(request):
|
|
- return HttpResponse("<h1>Hello, world.</h1>")
|
|
|
|
|
|
+ if 'credentials' not in request.session:
|
|
|
|
+ return redirect(reverse('authorize'))
|
|
|
|
+ cred = request.session['credentials']
|
|
|
|
+ return HttpResponse(cred['access_token'])
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+CLIENT_SECRETS_FILE = "client_secrets.json"
|
|
|
|
+SCOPES = ['https://www.googleapis.com/auth/analytics.readonly']
|
|
|
|
+flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
|
|
|
|
+ CLIENT_SECRETS_FILE,
|
|
|
|
+ scopes=SCOPES,
|
|
|
|
+ redirect_uri="http://127.0.0.1:8000/oauth2callback")
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+def authorize(request):
|
|
|
|
+ authorization_url, state = flow.authorization_url(access_type='offline')
|
|
|
|
+
|
|
|
|
+ # Store the state so the callback can verify the auth server response.
|
|
|
|
+ request.session['state'] = state
|
|
|
|
+
|
|
|
|
+ return redirect(authorization_url)
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+def oauth2callback(request):
|
|
|
|
+ state = request.session['state']
|
|
|
|
+
|
|
|
|
+ flow.state = state
|
|
|
|
+ code = request.GET.get('code', False)
|
|
|
|
+ flow.fetch_token(code=code)
|
|
|
|
+
|
|
|
|
+ credentials = flow.credentials
|
|
|
|
+ request.session['credentials'] = credentials_to_dict(credentials)
|
|
|
|
+ refresh_token = credentials.refresh_token
|
|
|
|
+ user_token = UserModel(user=request.user, refresh_token=refresh_token)
|
|
|
|
+ user_token.save()
|
|
|
|
+ return redirect(reverse('home'))
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+def credentials_to_dict(credentials):
|
|
|
|
+ return {
|
|
|
|
+ 'access_token': credentials.token,
|
|
|
|
+ 'expiry': credentials.expiry
|
|
|
|
+ }
|