Explorar o código

setting up basig structure with a new model to store token

Mohidul Islam %!s(int64=5) %!d(string=hai) anos
pai
achega
192e6c7fa5
Modificáronse 9 ficheiros con 112 adicións e 7 borrados
  1. 1 0
      .gitignore
  2. 16 0
      client_secrets.json
  3. 3 1
      gauth/admin.py
  4. 25 0
      gauth/migrations/0001_initial.py
  5. 8 1
      gauth/models.py
  6. 5 4
      gauth/urls.py
  7. 0 0
      gauth/utils.py
  8. 50 1
      gauth/views.py
  9. 4 0
      goauth/settings.py

+ 1 - 0
.gitignore

@@ -3,6 +3,7 @@ __pycache__/
 *.py[cod]
 *$py.class
 .vscode
+.idea
 # C extensions
 *.so
 

+ 16 - 0
client_secrets.json

@@ -0,0 +1,16 @@
+{
+    "web": {
+        "client_id": "734645063035-g7l3ntqfqc3b0q2bkil21lk0edt1gb32.apps.googleusercontent.com",
+        "project_id": "atomic-byway-261007",
+        "auth_uri": "https://accounts.google.com/o/oauth2/auth",
+        "token_uri": "https://oauth2.googleapis.com/token",
+        "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
+        "client_secret": "brHZSIvHaXiYDli-ooReb-D4",
+        "redirect_uris": [
+            "http://127.0.0.1:8000/oauth2callback"
+        ],
+        "javascript_origins": [
+            "http://127.0.0.1:8000"
+        ]
+    }
+}

+ 3 - 1
gauth/admin.py

@@ -1,3 +1,5 @@
 from django.contrib import admin
+from .models import UserModel
 
-# Register your models here.
+
+admin.site.register(UserModel)

+ 25 - 0
gauth/migrations/0001_initial.py

@@ -0,0 +1,25 @@
+# Generated by Django 3.0 on 2019-12-12 09:13
+
+from django.conf import settings
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+    initial = True
+
+    dependencies = [
+        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+    ]
+
+    operations = [
+        migrations.CreateModel(
+            name='UserModel',
+            fields=[
+                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
+                ('refresh_token', models.CharField(max_length=30)),
+                ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='token_of', to=settings.AUTH_USER_MODEL)),
+            ],
+        ),
+    ]

+ 8 - 1
gauth/models.py

@@ -1,3 +1,10 @@
 from django.db import models
+from django.contrib.auth.models import User
 
-# Create your models here.
+
+class UserModel(models.Model):
+    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='token_of')
+    refresh_token = models.CharField(max_length=30)
+
+    def __repr__(self):
+        self.user.username

+ 5 - 4
gauth/urls.py

@@ -1,7 +1,8 @@
 from django.urls import path
-
-from . import views
+from .views import index, authorize, oauth2callback
 
 urlpatterns = [
-    path('', views.index, name='index'),
-]
+    path('', index, name='home'),
+    path('authorize/', authorize, name='authorize'),
+    path('oauth2callback', oauth2callback, name='oauth2callback'),
+]

+ 0 - 0
gauth/utils.py


+ 50 - 1
gauth/views.py

@@ -1,5 +1,54 @@
 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):
-    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
+    }

+ 4 - 0
goauth/settings.py

@@ -101,3 +101,7 @@ USE_TZ = True
 # Static files (CSS, JavaScript, Images)
 
 STATIC_URL = '/static/'
+
+
+LOGIN_URL = '/admin/login'
+LOGIN_REDIRECT_URL = '/'