|
@@ -3,25 +3,13 @@ from django.shortcuts import redirect
|
|
|
from django.urls import reverse
|
|
|
import google_auth_oauthlib.flow
|
|
|
from django.contrib.auth.decorators import login_required
|
|
|
+from django.contrib.auth.models import User
|
|
|
|
|
|
-from .utils import get_access_token, has_expired
|
|
|
+from .utils import get_access_token, get_google_account_id
|
|
|
|
|
|
from .models import UserModel
|
|
|
|
|
|
|
|
|
-@login_required
|
|
|
-def google_auth(request):
|
|
|
- uid = request.user.id
|
|
|
- user = UserModel.objects.filter(pk=uid).first()
|
|
|
- if not user:
|
|
|
- return redirect(reverse('authorize'))
|
|
|
- if 'credentials' not in request.session or has_expired(request.session['credentials']):
|
|
|
- get_access_token(request)
|
|
|
- cred = request.session['credentials']
|
|
|
-
|
|
|
- return HttpResponse(cred['access_token'])
|
|
|
-
|
|
|
-
|
|
|
CLIENT_SECRETS_FILE = "client_secrets.json"
|
|
|
SCOPES = ['https://www.googleapis.com/auth/business.manage']
|
|
|
flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
|
|
@@ -30,6 +18,20 @@ flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file(
|
|
|
redirect_uri="http://127.0.0.1:8000/oauth2callback")
|
|
|
|
|
|
|
|
|
+def index(request):
|
|
|
+ get_access_token(request)
|
|
|
+ cred = request.session['credentials']
|
|
|
+ return HttpResponse(cred['access_token'])
|
|
|
+
|
|
|
+
|
|
|
+@login_required
|
|
|
+def google_auth(request):
|
|
|
+ user = User.objects.filter(username='admin@ercare').first()
|
|
|
+ if not user:
|
|
|
+ return HttpResponse('<h1>You have to have a user account with username "admin@ercare". Please create a superuser using manage.py createsuperuser</h2>')
|
|
|
+ return redirect(reverse('authorize'))
|
|
|
+
|
|
|
+
|
|
|
def authorize(request):
|
|
|
authorization_url, state = flow.authorization_url(access_type='offline')
|
|
|
|
|
@@ -47,12 +49,14 @@ def oauth2callback(request):
|
|
|
flow.fetch_token(code=code)
|
|
|
|
|
|
credentials = flow.credentials
|
|
|
- request.session['credentials'] = credentials_to_dict(credentials)
|
|
|
- refresh_token = credentials.refresh_token
|
|
|
-
|
|
|
- user_model = UserModel.objects.create(user=request.user, refresh_token=refresh_token)
|
|
|
+ account_id = get_google_account_id(credentials.token)
|
|
|
+ user = User.objects.filter(username='admin@ercare').first()
|
|
|
+ user_model, created = UserModel.objects.get_or_create(user=user)
|
|
|
+ user_model.refresh_token = credentials.refresh_token
|
|
|
+ user_model.gmb_account_id = account_id
|
|
|
user_model.save()
|
|
|
- return redirect(reverse('gmb-auth'))
|
|
|
+ request.session['credentials'] = credentials_to_dict(credentials)
|
|
|
+ return redirect(reverse('home'))
|
|
|
|
|
|
|
|
|
def credentials_to_dict(credentials):
|