add authentication module using Token Auth
authorrougeronj
Thu, 02 Apr 2015 11:57:39 +0200
changeset 51 032280909e65
parent 50 c641b33f910f
child 52 ce9aefce6e41
add authentication module using Token Auth
server/ammico/admin.py
server/ammico/models.py
server/ammico/urls.py
server/ammico/views.py
server/authentication/__init__.py
server/authentication/models.py
server/authentication/urls.py
server/authentication/views.py
server/settings.py
--- a/server/ammico/admin.py	Tue Mar 31 15:27:26 2015 +0200
+++ b/server/ammico/admin.py	Thu Apr 02 11:57:39 2015 +0200
@@ -1,7 +1,9 @@
 from django.contrib import admin
-from .models import Slide, AmmicoUser, Book
+
+from ammico.models import Slide, Book
+from django.contrib.auth import get_user_model
 
 
 admin.site.register(Slide)
-admin.site.register(AmmicoUser)
+admin.site.register(get_user_model())
 admin.site.register(Book)
\ No newline at end of file
--- a/server/ammico/models.py	Tue Mar 31 15:27:26 2015 +0200
+++ b/server/ammico/models.py	Thu Apr 02 11:57:39 2015 +0200
@@ -1,25 +1,18 @@
 import datetime
 
-from django.contrib.auth.models import User
 from django.db import models
 from taggit.managers import TaggableManager
 
+from authentication.models import AmmicoUser
 
-class AmmicoUser(models.Model):
-    user = models.OneToOneField(User)
-    idUser = models.CharField(max_length=512, unique=True)
-    image = models.URLField(max_length=2048, blank=True)
-    
-    def __str__(self):
-        return self.user.username
 
 class Book(models.Model):
-    user = models.ForeignKey(AmmicoUser)
+    user = models.ForeignKey(AmmicoUser, related_name = "books")
     idArticle = models.CharField(max_length=512, unique=True)
     title = models.CharField(max_length=512, blank=True)
     description = models.CharField(max_length=512, blank=True, null=True)
     image = models.URLField(max_length=2048, blank=True)
-    date = models.DateTimeField(null=True)
+    date = models.DateTimeField(default=datetime.datetime.now)
     
     def __str__(self):
         return self.title
--- a/server/ammico/urls.py	Tue Mar 31 15:27:26 2015 +0200
+++ b/server/ammico/urls.py	Thu Apr 02 11:57:39 2015 +0200
@@ -11,5 +11,5 @@
     url(r'^books/(?P<idBook>[0-9]+)/slides$', BookSlides.as_view()),
     url(r'^slides$', ListSlides.as_view()),
     url(r'^slides/(?P<idSlide>[0-9]+)$', InfoSlide.as_view()),
-    url(r'^api-auth', include('rest_framework.urls', namespace='rest_framework')),
+    url(r'^auth/', include('authentication.urls')),
 )
--- a/server/ammico/views.py	Tue Mar 31 15:27:26 2015 +0200
+++ b/server/ammico/views.py	Thu Apr 02 11:57:39 2015 +0200
@@ -2,23 +2,27 @@
 from datetime import datetime
 import json
 
-#from django.contrib.auth import login, logout
-from django.contrib.auth.models import User
+from django.contrib.auth import get_user_model
 from django.http import HttpResponse
 from django.utils.dateparse import parse_datetime
 import requests
 from rest_framework import permissions, status
+from rest_framework.authentication import TokenAuthentication
+from rest_framework.permissions import IsAuthenticated
 from rest_framework.response import Response
 from rest_framework.views import APIView
 
-from ammico.models import Book, AmmicoUser, Slide
+from ammico.models import Book, Slide
 from ammico.serializers import BookSerializer, SlideSerializer
 from settings import URL_JAMESPOT
 
 
+#from django.contrib.auth import login, logout
+User = get_user_model()
+
 def populateUser(request):
     usermail = request.GET["email"]
-    user = AmmicoUser.objects.get(user=User.objects.get(email=usermail))
+    user = User.objects.get(email=usermail)
     data = {"user": usermail, "idUser": user.idUser}
     populateVisite(user)
     return HttpResponse(content=json.dumps(data), content_type='application/json')
@@ -70,9 +74,9 @@
     """
     Views to list all books.
     """
-    #authentication_classes = (authentication.TokenAuthentication,)
-    #permission_classes = (permissions.IsAdminUser,)
-    permission_classes = (permissions.AllowAny,)
+    
+    authentication_classes = (TokenAuthentication,)
+    permission_classes = (IsAuthenticated,)
 
     def get(self, request):
         """
@@ -86,9 +90,9 @@
     """
     View to get book informations.
     """
-    #authentication_classes = (authentication.TokenAuthentication,)
-    #permission_classes = (permissions.IsAdminUser,)
-    permission_classes = (permissions.AllowAny,)
+    
+    authentication_classes = (TokenAuthentication,)
+    permission_classes = (IsAuthenticated,)
 
     def get(self, request, idBook):
         try:
@@ -108,9 +112,9 @@
     """
     View to get book informations.
     """
-    #authentication_classes = (authentication.TokenAuthentication,)
-    #permission_classes = (permissions.IsAdminUser,)
-    permission_classes = (permissions.AllowAny,)
+
+    authentication_classes = (TokenAuthentication,)
+    permission_classes = (IsAuthenticated,)
 
     def get(self, request, idBook):
         try:
@@ -126,9 +130,9 @@
     """
     Get/Set Slides order
     """
-    #authentication_classes = (authentication.TokenAuthentication,)
-    #permission_classes = (permissions.IsAdminUser,)
-    permission_classes = (permissions.AllowAny,)
+    
+    authentication_classes = (TokenAuthentication,)
+    permission_classes = (IsAuthenticated,)
 
     def get(self, request, idBook):
         try:
@@ -152,9 +156,9 @@
     """
     Views to list all books.
     """
-    #authentication_classes = (authentication.TokenAuthentication,)
-    #permission_classes = (permissions.IsAdminUser,)
-    permission_classes = (permissions.AllowAny,)
+    
+    authentication_classes = (TokenAuthentication,)
+    permission_classes = (IsAuthenticated,)
 
     def get(self, request):
         """
@@ -175,9 +179,9 @@
     """
     View to get book informations.
     """
-    #authentication_classes = (authentication.TokenAuthentication,)
-    #permission_classes = (permissions.IsAdminUser,)
-    permission_classes = (permissions.AllowAny,)
+    
+    authentication_classes = (TokenAuthentication,)
+    permission_classes = (IsAuthenticated,)
 
     def get(self, request, idSlide):
         try:
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/server/authentication/models.py	Thu Apr 02 11:57:39 2015 +0200
@@ -0,0 +1,15 @@
+import json
+
+from django.contrib.auth.models import AbstractUser, BaseUserManager
+from django.db import models
+from django.utils import timezone
+import requests
+
+from config import URL_JAMESPOT
+
+class AmmicoUser(AbstractUser):
+    idUser = models.CharField(max_length=50, unique=True, blank=True)
+    
+class Profile(models.Model):
+    user = models.OneToOneField(AmmicoUser)
+    image = models.URLField(max_length=2048, blank=True)
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/server/authentication/urls.py	Thu Apr 02 11:57:39 2015 +0200
@@ -0,0 +1,11 @@
+from django.conf.urls import patterns, url
+from rest_framework.authtoken import views
+
+from authentication.views import User, AuthView
+
+
+urlpatterns = patterns('',
+    url(r'^user', User.as_view()),
+    url(r'^auth', AuthView.as_view(), name='auth-view'),
+    url(r'^api-token-auth', views.obtain_auth_token)
+)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/server/authentication/views.py	Thu Apr 02 11:57:39 2015 +0200
@@ -0,0 +1,66 @@
+
+import json
+
+from django.contrib.auth import get_user_model
+import requests
+from rest_framework import serializers, status, permissions
+from rest_framework.authentication import TokenAuthentication
+from rest_framework.authtoken.models import Token
+from rest_framework.exceptions import ParseError
+from rest_framework.permissions import IsAuthenticated
+from rest_framework.response import Response
+from rest_framework.views import APIView
+
+from config import URL_JAMESPOT
+
+
+class UserSerializer(serializers.ModelSerializer):
+    class Meta:
+        model = get_user_model()
+
+class User(APIView):
+    """
+    get list user or add user
+    """
+    permission_classes = (permissions.AllowAny,)
+    
+    def get(self, request):
+        print ("here ?")
+        user = get_user_model().objects.all()
+        serializer = UserSerializer(user, many=True)
+        return Response(serializer.data)
+        
+    def post(self, request):
+        VALID_USER_FIELDS = [f.name for f in get_user_model()._meta.fields]
+        DEFAULTS = {
+            "groups":"",
+            "user_permissions":""
+        }
+        request.data.update(DEFAULTS)
+        serialized = UserSerializer(data=request.data)
+        
+        if serialized.is_valid():
+            user_data = {field: data for (field, data) in request.DATA.items() if field in VALID_USER_FIELDS}
+            
+            params = {'o': 'user', 'f': 'get', 'mail': user_data['email']}
+            r = requests.get(URL_JAMESPOT, params=params)
+            infoUser = json.loads(r.content.decode('utf-8'))
+            
+            user_data.update({"idUser":infoUser['VAL']['idUser']})
+            
+            user = get_user_model().objects.create_user(
+                **user_data
+            )
+            return Response(UserSerializer(instance=user).data, status=status.HTTP_201_CREATED)
+        else:
+            return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
+
+class AuthView(APIView):
+    """
+    Authentication is needed for this methods
+    """
+    authentication_classes = (TokenAuthentication,)
+    permission_classes = (IsAuthenticated,)
+ 
+    def get(self, request, format=None):
+        return Response({'detail': "I suppose you are authenticated"})
\ No newline at end of file
--- a/server/settings.py	Tue Mar 31 15:27:26 2015 +0200
+++ b/server/settings.py	Thu Apr 02 11:57:39 2015 +0200
@@ -32,10 +32,12 @@
     'django.contrib.messages',
     'django.contrib.staticfiles',
     'rest_framework',
+    'rest_framework.authtoken',
     'corsheaders',
     'requests',
     'taggit',
     'ammico',
+    'authentication'
 )
 
 MIDDLEWARE_CLASSES = (
@@ -59,7 +61,7 @@
     # Use Django's standard `django.contrib.auth` permissions,
     # or allow read-only access for unauthenticated users.
     'DEFAULT_PERMISSION_CLASSES': [
-        'rest_framework.authentication.SessionAuthentication'
+        'rest_framework.authentication.TokenAuthentication'
     ]
 }
 
@@ -70,6 +72,9 @@
     }
 }
 
+AUTH_USER_MODEL = 'authentication.AmmicoUser'
+AUTH_PROFILE_MODULE = 'authentication.Profile'
+
 # Internationalization
 # https://docs.djangoproject.com/en/1.7/topics/i18n/