Skip to content

Commit

Permalink
API Modified with Token Authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
DEKHTIARJonathan committed Sep 4, 2017
1 parent e6b5d53 commit 5ab367e
Show file tree
Hide file tree
Showing 6 changed files with 82 additions and 16 deletions.
13 changes: 12 additions & 1 deletion application/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,7 @@ def assign_env_value(var_name):
'django_extensions',
'django_ses',
'rest_framework',
'rest_framework.authtoken',
'encrypted_model_fields',
'storages',
'django_celery_monitor',
Expand Down Expand Up @@ -182,6 +183,16 @@ def assign_env_value(var_name):
},
]

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
}

if DEBUG or TESTING:
TEMPLATES[0]['OPTIONS']['loaders'] = [
'django.template.loaders.filesystem.Loader',
Expand Down Expand Up @@ -255,8 +266,8 @@ def assign_env_value(var_name):
os.path.join(PROJECT_ROOT, 'static'),
)

USER_PHOTO_PATH = "images/user_photos/"
USER_ESTIMATOR_PATH = "estimators/"
USER_PHOTO_PATH = "images/user_photos/"
INTEREST_PHOTO_PATH = "images/interest_photos/"

RSS_SUBS_LOOKUP_PERIOD = 3 # (days) Every people visiting the RSS/ATOM feeds over the N last days are count as a subscriber
Expand Down
20 changes: 20 additions & 0 deletions feedcrunch/migrations/0023_FeedUser_default_desc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-04 09:08
from __future__ import unicode_literals

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('feedcrunch', '0022_rssfeed_error'),
]

operations = [
migrations.AlterField(
model_name='feeduser',
name='description',
field=models.TextField(blank=True, default='Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam dui nisl, aliquam nec quam nec, laoreet porta odio. Morbi ultrices sagittis ligula ut consectetur. Aenean quis facilisis augue. Vestibulum maximus aliquam augue, ut lobortis turpis euismod vel. Sed in mollis tellus, eget eleifend turpis. Vivamus aliquam ornare felis at dignissim. Integer vitae cursus eros, non dignissim dui. Suspendisse porttitor justo nec lacus dictum commodo. Sed in fringilla tortor, at pharetra tortor.', null=True),
),
]
2 changes: 1 addition & 1 deletion feedcrunch/model_files/models_user.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def _validate_email(self, email):
raise ValueError("The given email is not valid or not doesn''t exist.")

def _validate_password(self, password):
if re.match(r'(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z\d]{8,}', password) == None:
if re.match("(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}", password) == None:
raise ValueError("The password doesn't fit in our policies : At least 8 characters, 1 Uppercase letter 'A-Z', 1 Lowercase letter 'a-z', and 1 number '0-9'")

def _validate_firstname(self, firstname):
Expand Down
4 changes: 4 additions & 0 deletions feedcrunch_api_v1/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

#from .admin import admin_site
from .views import *
import rest_framework.authtoken.views

urlpatterns = [

Expand All @@ -17,6 +18,9 @@
url(r'^public/post/validate/rssfeed/$', rssfeed_Validation.as_view(), name='validate_username'),

# ====================== Authentication Required API Routes ====================== #
# Login/Logout Route
url(r'^get_auth_token/$', rest_framework.authtoken.views.obtain_auth_token, name='get_auth_token'),
url(r'^logout/$', django.contrib.auth.views.logout, {'next_page': '/login',}, name='logout'),

# User Routes
url(r'^authenticated/get/user/publications_stats/$', User_Stats_Publications.as_view(), name='publications_stats'),
Expand Down
47 changes: 39 additions & 8 deletions feedcrunch_api_v1/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@

from __future__ import unicode_literals

from django.contrib.auth import authenticate, login, logout
from django.core.exceptions import ValidationError, ObjectDoesNotExist
from django.core.validators import URLValidator
from django.http import HttpResponse

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.authtoken.models import Token
from rest_framework.parsers import FileUploadParser, MultiPartParser
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView

from feedcrunch.models import Post, FeedUser, Tag, Country, RSSFeed, RSSArticle, RSSFeed_Sub, RSSArticle_Assoc
from feedcrunch import tasks
Expand Down Expand Up @@ -42,6 +45,32 @@ def mark_RSSArticle_Assoc_as_read(RSSArticle_AssocID, user):
RSSArticle_Assoc_obj.marked_read = True
RSSArticle_Assoc_obj.save()

class Authentication_Login_View(APIView):

def post(self, request):

if request.method == 'POST':
username = request.POST['username'].lower()
password = request.POST['password']

user = authenticate(username=username, password=password)
if user is not None:

login(request, user)

payload = {
'user': request.user,
'auth': request.auth, # None
}

else:
payload = {
"success": False,
"error": "Login and Password does not match or the requested user does not exist."
}

return Response(payload)

class Username_Validation(APIView):

def post(self, request):
Expand Down Expand Up @@ -302,16 +331,18 @@ def get(self, request):
return Response(payload)

class Tags(APIView):
def get(self, request):
try:
permission_classes = (IsAuthenticated, )
#permission_classes = (AllowAny, )

payload = dict()
check_passed = check_admin_api(request.user)
#Authorization: Token xxxxxxxxxxxxxxxxxxxxxxxxx

if check_passed != True:
raise Exception(check_passed)
def get(self, request):

payload = dict()
try:

tags = Tag.objects.all().order_by('name')

payload["tags"] = [tag.name for tag in tags]

payload ["success"] = True
Expand Down
12 changes: 6 additions & 6 deletions feedcrunch_home/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,19 +35,16 @@ def terms(request):
return render(request, 'terms.html', {})

def loginView(request):
context = RequestContext(request)
if request.method == 'POST':
username = request.POST['username'].lower()
password = request.POST['password']

user = authenticate(username=username, password=password)

if user is not None:
if user.is_active:
login(request, user)
return HttpResponseRedirect('/@'+request.user.username+'/admin')
login(request, user)
return HttpResponseRedirect('/@'+request.user.username+'/admin')

else:
return HttpResponse("Your account is inactive.")
else:
return HttpResponseRedirect('/login/')
else:
Expand All @@ -74,6 +71,9 @@ def signUPView(request):
user = authenticate(username=username, password=password)
login(request, user)

# We create an associated token for the user
Token.objects.create(user=user)

return HttpResponseRedirect('/@'+request.user.username+'/admin')

else:
Expand Down

0 comments on commit 5ab367e

Please sign in to comment.