Skip to content

Commit

Permalink
Merge 0d660f5 into f1b9de3
Browse files Browse the repository at this point in the history
  • Loading branch information
AGMETEOR committed Aug 16, 2018
2 parents f1b9de3 + 0d660f5 commit 856ade4
Show file tree
Hide file tree
Showing 18 changed files with 353 additions and 29 deletions.
15 changes: 1 addition & 14 deletions authors/apps/articles/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,14 @@
# Generated by Django 2.0.7 on 2018-08-13 11:45
# Generated by Django 2.0.7 on 2018-08-15 18:40

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import taggit.managers


class Migration(migrations.Migration):

initial = True

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('taggit', '0002_auto_20150616_2121'),
]

operations = [
Expand All @@ -31,11 +27,6 @@ class Migration(migrations.Migration):
('rating', models.PositiveIntegerField(blank=True, editable=False, null=True)),
('likesCount', models.IntegerField(default=0)),
('dislikesCount', models.IntegerField(default=0)),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_articles', to=settings.AUTH_USER_MODEL)),
('dislikes', models.ManyToManyField(blank=True, related_name='dislikes', to=settings.AUTH_USER_MODEL)),
('favorites', models.ManyToManyField(blank=True, related_name='favorites', to=settings.AUTH_USER_MODEL)),
('likes', models.ManyToManyField(blank=True, related_name='likes', to=settings.AUTH_USER_MODEL)),
('tags', taggit.managers.TaggableManager(blank=True, help_text='A comma-separated list of tags.', through='taggit.TaggedItem', to='taggit.Tag', verbose_name='Tags')),
],
options={
'ordering': ('-created_at',),
Expand All @@ -46,7 +37,6 @@ class Migration(migrations.Migration):
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('image', models.ImageField(upload_to='')),
('article', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='article_images', to='articles.Article')),
],
),
migrations.CreateModel(
Expand All @@ -56,8 +46,6 @@ class Migration(migrations.Migration):
('body', models.TextField()),
('created_at', models.DateTimeField(auto_now=True)),
('updated_at', models.DateTimeField(auto_now_add=True, null=True)),
('article', models.ForeignKey(blank=True, on_delete=django.db.models.deletion.CASCADE, related_name='user_comments', to='articles.Article')),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comment_author', to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ('-created_at',),
Expand All @@ -69,7 +57,6 @@ class Migration(migrations.Migration):
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('amount', models.PositiveIntegerField(choices=[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)])),
('article', models.ForeignKey(blank=True, on_delete=django.db.models.deletion.CASCADE, related_name='article_ratings', to='articles.Article')),
('user', models.ForeignKey(blank=True, on_delete=django.db.models.deletion.CASCADE, related_name='user_article_rating', to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ('-amount',),
Expand Down
65 changes: 65 additions & 0 deletions authors/apps/articles/migrations/0002_auto_20180815_1840.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Generated by Django 2.0.7 on 2018-08-15 18:40

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import taggit.managers


class Migration(migrations.Migration):

initial = True

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('articles', '0001_initial'),
('taggit', '0002_auto_20150616_2121'),
]

operations = [
migrations.AddField(
model_name='rating',
name='user',
field=models.ForeignKey(blank=True, on_delete=django.db.models.deletion.CASCADE, related_name='user_article_rating', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='comment',
name='article',
field=models.ForeignKey(blank=True, on_delete=django.db.models.deletion.CASCADE, related_name='user_comments', to='articles.Article'),
),
migrations.AddField(
model_name='comment',
name='author',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comment_author', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='articleimage',
name='article',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='article_images', to='articles.Article'),
),
migrations.AddField(
model_name='article',
name='author',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_articles', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='article',
name='dislikes',
field=models.ManyToManyField(blank=True, related_name='dislikes', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='article',
name='favorites',
field=models.ManyToManyField(blank=True, related_name='favorites', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='article',
name='likes',
field=models.ManyToManyField(blank=True, related_name='likes', to=settings.AUTH_USER_MODEL),
),
migrations.AddField(
model_name='article',
name='tags',
field=taggit.managers.TaggableManager(blank=True, help_text='A comma-separated list of tags.', through='taggit.TaggedItem', to='taggit.Tag', verbose_name='Tags'),
),
]
2 changes: 1 addition & 1 deletion authors/apps/authentication/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ class UserAdmin(BaseUserAdmin):
list_display = ('email','is_staff')
list_filter = ('is_staff',)
fieldsets = (
(None, {'fields': ('email', 'password','username','bio','image','is_verified')}),
(None, {'fields': ('email', 'password','username','bio','image','is_verified','fb_social_id','google_social_id')}),
('Permissions', {'fields': ('is_staff',)}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
Expand Down
6 changes: 4 additions & 2 deletions authors/apps/authentication/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Generated by Django 2.0.7 on 2018-08-10 08:12
# Generated by Django 2.0.7 on 2018-08-15 18:43

from django.db import migrations, models

Expand All @@ -25,8 +25,10 @@ class Migration(migrations.Migration):
('is_staff', models.BooleanField(default=False)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('fb_social_id', models.CharField(blank=True, db_index=True, max_length=255, null=True)),
('google_social_id', models.CharField(blank=True, db_index=True, max_length=255, null=True)),
('bio', models.CharField(blank=True, max_length=255)),
('image', models.ImageField(blank=True, upload_to='profile_image')),
('image', models.ImageField(blank=True, max_length=800, upload_to='profile_image')),
],
options={
'abstract': False,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Generated by Django 2.0.7 on 2018-08-10 08:12
# Generated by Django 2.0.7 on 2018-08-15 18:43

from django.conf import settings
from django.db import migrations, models
Expand All @@ -9,9 +9,9 @@ class Migration(migrations.Migration):
initial = True

dependencies = [
('follower', '0001_initial'),
('authentication', '0001_initial'),
('auth', '0009_alter_user_last_name_max_length'),
('follower', '0001_initial'),
]

operations = [
Expand Down
16 changes: 14 additions & 2 deletions authors/apps/authentication/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class UserManager(BaseUserManager):
to create `User` objects.
"""

def create_user(self, username, email, password=None):
def create_user(self, username, email, password=None, fb_social_id = None, google_social_id = None, image = None, is_verified = None):
"""Create and return a `User` with an email, username and password."""

if not username:
Expand All @@ -34,6 +34,12 @@ def create_user(self, username, email, password=None):
raise TypeError('Users must have an email address.')

user = self.model(username=username, email=self.normalize_email(email))
if fb_social_id and is_verified:
user = self.model(username=username, email=self.normalize_email(email), fb_social_id = fb_social_id, is_verified = is_verified, image = image)

if google_social_id and is_verified:
user = self.model(username=username, email=self.normalize_email(email), google_social_id = google_social_id, is_verified = is_verified, image = image)

user.set_password(password)
user.save()

Expand Down Expand Up @@ -99,9 +105,15 @@ class User(AbstractBaseUser, PermissionsMixin):
# A timestamp reprensenting when this object was last updated.
updated_at = models.DateTimeField(auto_now=True)

#social auth fields

fb_social_id = models.CharField(db_index = True, max_length = 255, null = True, blank = True)
google_social_id = models.CharField(db_index = True, max_length = 255, null = True, blank = True)


# More fields required by Django when specifying a custom user model.
bio = models.CharField(max_length=255, blank=True)
image = models.ImageField(upload_to='profile_image', blank=True)
image = models.ImageField(upload_to='profile_image', blank=True, max_length = 800)

# The `USERNAME_FIELD` property tells us which field we will use to log in.
# In this case, we want that to be the email field.
Expand Down
28 changes: 28 additions & 0 deletions authors/apps/authentication/renderers.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,31 @@ def render(self, data, media_type=None, renderer_context=None):
'user': data
})


class FBAuthJSONRenderer(JSONRenderer):
charset = 'utf-8'

def render(self, data, media_type=None, renderer_context=None):
errors = data.get('errors', None)
if errors is not None:
# As mentioned about, we will let the default JSONRenderer handle
# rendering errors.
return super(FBAuthJSONRenderer, self).render(data)

data = data['fbauth_token']

return json.dumps({"user":data})

class GoogleAuthJSONRenderer(JSONRenderer):
charset = 'utf-8'

def render(self, data, media_type=None, renderer_context=None):
errors = data.get('errors', None)
if errors is not None:
# As mentioned about, we will let the default JSONRenderer handle
# rendering errors.
return super(GoogleAuthJSONRenderer, self).render(data)

data = data['googleauth_token']

return json.dumps({"user":data})
71 changes: 70 additions & 1 deletion authors/apps/authentication/serializers.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
from django.contrib.auth import authenticate
from rest_framework import serializers
from .models import User

import re
from authors.apps.authentication.social_auth.facebook_auth import FacebookValidation
from authors.apps.authentication.social_auth.google_auth import GoogleValidation
from authors.apps.authentication.models import User
from django.shortcuts import get_object_or_404


class RegistrationSerializer(serializers.ModelSerializer):
Expand Down Expand Up @@ -172,3 +175,69 @@ def update(self, instance, validated_data):
instance.save()

return instance


class FacebookAPISerializer(serializers.Serializer):
fbauth_token = serializers.CharField(max_length=800)

def validate_fbauth_token(self, fbauth_token):

fb_user_info = FacebookValidation.validate_facebook_token(fbauth_token)

user_fb_social_id = fb_user_info["id"]

qs = User.objects.filter(fb_social_id = user_fb_social_id)

if not qs:
data = {"username":fb_user_info["name"],"email":fb_user_info["email"],"fb_social_id":fb_user_info["id"], "image":fb_user_info["picture"]["data"]["url"],"is_verified":True}
User.objects.create_user(**data)
new_user = User.objects.filter(fb_social_id = user_fb_social_id)
return {
'email':new_user[0].email,
'username':new_user[0].username,
'token': new_user[0].token,
'message': 'You signed up with Facebook!'
}

#update email incase user changed their fb email

qs.update(email = fb_user_info["email"])

return {
'email':qs[0].email,
'username':qs[0].username,
'token': qs[0].token
}

class GoogleAPISerializer(serializers.Serializer):
googleauth_token = serializers.CharField()

def validate_googleauth_token(self, googleauth_token):

google_user_info = GoogleValidation.validate_google_token(googleauth_token)

google_email = google_user_info["email"]

user_google_social_id = google_user_info["sub"]

qs = User.objects.filter(email = google_email)

if not qs:
data = {"username":google_user_info["family_name"],"email":google_user_info["email"],"google_social_id":google_user_info["sub"], "image":google_user_info["picture"],"is_verified":google_user_info["email_verified"]}
User.objects.create_user(**data)
new_user = User.objects.filter(google_social_id = user_google_social_id)
return {
'email':new_user[0].email,
'username':new_user[0].username,
'token': new_user[0].token,
'message': 'You signed up with Google!'
}
qs.update(google_social_id = google_user_info["sub"], is_verified = True)

return {
'email':qs[0].email,
'username':qs[0].username,
'token': qs[0].token
}


Empty file.
19 changes: 19 additions & 0 deletions authors/apps/authentication/social_auth/facebook_auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import facebook
from rest_framework import serializers

class FacebookValidation:

@staticmethod
def validate_facebook_token(auth_token):

try:

graph = facebook.GraphAPI(access_token = auth_token, version = "2.7")

profile = graph.request('/me?fields=id,name,email,picture')

return profile

except:

raise serializers.ValidationError("The Facebook token provided is not valid!")
21 changes: 21 additions & 0 deletions authors/apps/authentication/social_auth/google_auth.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from google.oauth2 import id_token
from google.auth.transport import requests
from rest_framework import serializers
import os

class GoogleValidation:

@staticmethod
def validate_google_token(google_token):

CLIENT_ID = "341988301600-odl0nb10vaim96gsdhpa6vun7iog5pl0.apps.googleusercontent.com"

try:
idinfo = id_token.verify_oauth2_token(google_token, requests.Request(), CLIENT_ID)

return idinfo


except:
raise serializers.ValidationError("Your google token is not valid!")

Loading

0 comments on commit 856ade4

Please sign in to comment.