Skip to content

Commit

Permalink
Merge pull request #48 from andela/ft-enable-social-login-160617671
Browse files Browse the repository at this point in the history
#160617671: Enable Social login via Google, Facebook and Twitter
  • Loading branch information
Walukagga Patrick committed Oct 23, 2018
2 parents 45d1f38 + d1c482a commit 3358d41
Show file tree
Hide file tree
Showing 9 changed files with 136 additions and 1 deletion.
2 changes: 2 additions & 0 deletions authors/apps/authentication/migrations/0001_initial.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ class Migration(migrations.Migration):
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(db_index=True, max_length=255, unique=True)),
('first_name', models.CharField(blank=True, max_length=255)),
('last_name', models.CharField(blank=True, max_length=255)),
('email', models.EmailField(db_index=True, max_length=254, unique=True)),
('is_active', models.BooleanField(default=True)),
('is_verified', models.BooleanField(default=False)),
Expand Down
3 changes: 3 additions & 0 deletions authors/apps/authentication/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@ class User(AbstractBaseUser, PermissionsMixin):
# represent the `User` in the UI. We want to index this column in the
# database to improve lookup performance.
username = models.CharField(db_index=True, max_length=255, unique=True)
first_name = models.CharField( max_length=255, blank=True)
last_name = models.CharField( max_length=255, blank=True)


# We also need a way to contact the user and a way for the user to identify
# themselves when logging in. Since we need an email address for contacting
Expand Down
Empty file.
11 changes: 11 additions & 0 deletions authors/apps/social_auth/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from rest_framework import serializers
from authors.apps.authentication.serializers import RegistrationSerializer,LoginSerializer
from authors.apps.authentication.models import User

class FbRegisterSerializer(RegistrationSerializer):
def create(self, validated_data):

user = User.objects.create_user(**validated_data)
user.is_verified =True
user.save()
return user
10 changes: 10 additions & 0 deletions authors/apps/social_auth/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from django.urls import path
from .views import FacebookLogin, TwitterLogin



app_name = 'social_auth'

urlpatterns = [
path('facebook/', FacebookLogin.as_view(), name='login'),
]
60 changes: 60 additions & 0 deletions authors/apps/social_auth/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter
from allauth.socialaccount.providers.twitter.views import TwitterOAuthAdapter
from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
from rest_auth.registration.views import SocialLoginView
import requests
from rest_framework import status
from authors.apps.authentication.models import User

from rest_framework.response import Response
from rest_auth.social_serializers import TwitterLoginSerializer
from authors.apps.authentication.serializers import RegistrationSerializer,LoginSerializer
from .serializers import FbRegisterSerializer
import json

class FacebookLogin(SocialLoginView):
adapter_class = FacebookOAuth2Adapter
client_class = OAuth2Client
FbRegSerializer_class=FbRegisterSerializer

def post(self, request):
data=request.data
token=data['access_token']
url = "https://graph.facebook.com/v3.1/me"

querystring = {"fields":"id,name,email,first_name,last_name","access_token":token}
response = requests.request("GET", url,params=querystring)
i=json.loads(response.text)

data={
"password": 'Ah123456789@',
"username": i['name'],
"email": i['email'],
}


if not User.objects.filter(email=i['email']).exists():

serializer=self.FbRegSerializer_class(data=data)
serializer.is_valid(raise_exception=True)
serializer.save()

else:
loginserializer=LoginSerializer(data=data)
loginserializer.is_valid(raise_exception=True)
import pdb; pdb.set_trace()
return Response("logged in")

return Response(i, status=status.HTTP_200_OK)


class GoogleLogin(SocialLoginView):
adapter_class = GoogleOAuth2Adapter
client_class = OAuth2Client
callback_url = 'localhost:8000'


class TwitterLogin(SocialLoginView):
serializer_class = TwitterLoginSerializer
adapter_class = TwitterOAuthAdapter
31 changes: 31 additions & 0 deletions authors/settings/defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"""

import os
import datetime
from decouple import config, Csv
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
Expand Down Expand Up @@ -64,6 +65,20 @@
'django_cron',
'debug_toolbar',


'django.contrib.sites',

# 'rest_framework.authtoken',
'rest_auth',

'allauth',
'allauth.account',
'allauth.socialaccount',
'rest_auth.registration',
#social login apps
'allauth.socialaccount.providers.facebook',
'allauth.socialaccount.providers.twitter',
'allauth.socialaccount.providers.google',
]


Expand Down Expand Up @@ -97,6 +112,13 @@
},
]

AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
)

SITE_ID = 1

WSGI_APPLICATION = 'authors.wsgi.application'

# Database
Expand Down Expand Up @@ -167,6 +189,7 @@

'DEFAULT_AUTHENTICATION_CLASSES': (
'authors.apps.authentication.backends.JWTAuthentication',
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
),
'DEFAULT_FILTER_BACKENDS': (
'django_filters.rest_framework.DjangoFilterBackend',
Expand Down Expand Up @@ -196,4 +219,12 @@
CRON_CLASSES = [
"authors.apps.notifications.cron_job.EmailNotificationCron",
]
# Configure the JWTs to expire after 1 hour, and allow users to refresh near-expiration tokens
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(hours=1),
'JWT_ALLOW_REFRESH': True,
}

# Enables django-rest-auth to use JWT tokens instead of regular tokens.
REST_USE_JWT = True

15 changes: 14 additions & 1 deletion authors/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,16 @@
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path
from django.urls import include, path, re_path
from django.views.generic.base import RedirectView
from rest_framework.documentation import include_docs_urls
from rest_framework_swagger.views import get_swagger_view
import debug_toolbar

schema_view = get_swagger_view(title="Authors Haven API ")
from authors.apps.social_auth.views import (FacebookLogin,
TwitterLogin,
GoogleLogin)



Expand All @@ -39,5 +42,15 @@
path('coreapi-docs/', include_docs_urls(title='Authors Haven API')),
path('__debug__/', include(debug_toolbar.urls)),


path('rest-auth/', include('rest_auth.urls')),
path('rest-auth/registration/', include('rest_auth.registration.urls')),
path('rest-auth/google/', GoogleLogin.as_view(), name='google_login'),
path('rest-auth/facebook/', FacebookLogin.as_view(), name='fb_login'),
path('rest-auth/twitter/', TwitterLogin.as_view(), name='twitter_login'),
# path('accounts/login/', include('authors.apps.social_auth.urls')),
path('accounts/', include('allauth.urls')),


]

5 changes: 5 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,8 @@ celery==4.2.1
django-redis==4.9.0
django-debug-toolbar==1.10.1
django-cron==0.5.1
django-allauth==0.37.1
social-auth-app-django==2.1.0
rest-social-auth==1.4.0
django-rest-auth==0.9.3
djangorestframework-jwt==1.11.0

0 comments on commit 3358d41

Please sign in to comment.