Guest User

Untitled

a guest
May 19th, 2016
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.60 KB | None | 0 0
  1. models.py
  2. from __future__ import unicode_literals
  3. import uuid
  4. from django.utils import timezone
  5. from django.db import models
  6. from django.conf import settings
  7. from django.db.models.signals import post_save
  8. from django.dispatch import receiver
  9. from rest_framework.authtoken.models import Token
  10. from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
  11. from django.contrib.auth.models import BaseUserManager
  12. from django.utils import timezone
  13.  
  14. class CustomUserManager(BaseUserManager):
  15.     def _create_user(self, email, password, is_staff, is_superuser, **extra_fields):
  16.         """
  17.        Creates and saves a User with the given email and password.
  18.        """
  19.         now = timezone.now()
  20.         if not email:
  21.             raise ValueError('The given email must be set')
  22.         email = self.normalize_email(email)
  23.         user = self.model(email=email,
  24.                           is_staff=is_staff, is_active=True,
  25.                           is_superuser=is_superuser, last_login=now,
  26.                           date_joined=now, **extra_fields)
  27.         user.set_password(password)
  28.         user.save(using=self._db)
  29.         return user
  30.  
  31.     def create_user(self, email, password=None, **extra_fields):
  32.         return self._create_user(email, password, False, False,
  33.                                  **extra_fields)
  34.  
  35.     def create_superuser(self, email, password, **extra_fields):
  36.         return self._create_user(email, password, True, True,
  37.                                  **extra_fields)
  38.  
  39. class CustomUser(AbstractBaseUser):
  40.     GENDER_TYPES = (
  41.             ('M', 'Male'),
  42.             ('F', 'Female'),
  43.             ('O', 'Other')
  44.         )
  45.     MEMBER_TYPES = (
  46.             ('F', 'Free'),
  47.             ('P', 'Paid')
  48.     )
  49.     email = models.EmailField(max_length=254, unique=True)
  50.     first_name = models.CharField(max_length=30, blank=True)
  51.     last_name = models.CharField(max_length=30, blank=True)
  52.     is_staff = models.BooleanField(default=False)
  53.     is_superuser = models.BooleanField(default=False)
  54.     is_active = models.BooleanField(default=True)
  55.     date_joined = models.DateTimeField(default=timezone.now)
  56.     profile_picture = models.CharField(max_length=36, null=True)
  57.     primary_num = models.CharField(max_length=100, unique=True, blank=True, null=True)
  58.     secondary_num = models.CharField(max_length=100, unique=True, null=True)
  59.     gender = models.CharField(max_length=1, choices=GENDER_TYPES, blank=True, null=True)
  60.     birth_date = models.DateField(null=True)
  61.     account_type = models.CharField(max_length=1, choices=MEMBER_TYPES, null=True)
  62.     bio = models.TextField(null=True)
  63.     modified_at = models.DateTimeField()
  64.  
  65.     objects = CustomUserManager()
  66.  
  67.     USERNAME_FIELD = 'email'
  68.     REQUIRED_FIELDS = []
  69.  
  70.     class Meta:
  71.         verbose_name = 'CustomUserProfile'
  72.         verbose_name_plural = 'CustomUserProfiles'
  73.  
  74.     def save(self, *args, **kwargs):
  75.         #On save, update timestamps
  76.         self.modified_at = timezone.now()
  77.         return super(CustomUser, self).save(*args, **kwargs)
  78.  
  79.     def get_absolute_url(self):
  80.         return "/users/%s/" % urlquote(self.email)
  81.  
  82.     def has_perm(self, perm, obj=None):
  83.         return self.is_superuser
  84.  
  85.     def has_module_perms(self, app_label):
  86.         return self.is_superuser
  87.  
  88.     def get_short_name(self):
  89.         "Returns the short name for the user."
  90.         return self.first_name
  91.  
  92. #Create a token for each User created
  93. @receiver(post_save, sender=settings.AUTH_USER_MODEL)
  94. def create_auth_token(sender, instance=None, created=False, **kwargs):
  95.     if created:
  96.         Token.objects.create(user=instance)
  97.  
  98. permissions.py
  99. from rest_framework import permissions
  100. from rest_framework.permissions import SAFE_METHODS
  101.  
  102. class IsSuperUserOrTargetUser(permissions.BasePermission):
  103.     def has_object_permission(self, request, view, obj):
  104.     # Read permissions are allowed to any request,
  105.         # so we'll always allow GET, HEAD or OPTIONS requests.
  106.         if request.method in permissions.SAFE_METHODS:
  107.             return True
  108.         # Write permissions are only allowed to the owner of the snippet.
  109.     return request.user.is_superuser or request.user == obj
  110.  
  111. serializer.py
  112. from rest_framework import serializers
  113. from .models import CustomUser
  114.  
  115. # Serializers define the API representation.
  116. class UserSerializer(serializers.ModelSerializer):
  117.     class Meta:
  118.     model = CustomUser
  119.     fields = ('password', 'first_name', 'last_name', 'bio', 'email')
  120.         write_only_fields = ('password',)
  121.         read_only_fields = ('is_staff', 'is_superuser', 'is_active', 'date_joined',)
  122.  
  123.  
  124.     def create(self, attrs, instance=None):
  125.         # call set_password on user object. Without this
  126.         # the password will be stored in plain text.
  127.         user = super(UserSerializer, self).create(attrs)
  128.         user.set_password(attrs['password'])
  129.         user.save()
  130.         return user
  131.  
  132.     def update(self, instance, validated_data):
  133.         for attr, value in validated_data.items():
  134.             if attr == 'password':
  135.                 instance.set_password(value)
  136.             else:
  137.                 setattr(instance, attr, value)
  138.         instance.save()
  139.         return instance
  140.  
  141.     def __unicode__(self):
  142.         return 'user_serializer'
  143.  
  144. urls.py
  145. from django.conf.urls import url, include
  146. from rest_framework import routers, serializers, viewsets
  147. from rest_framework.authtoken import views as authviews
  148. from . import views
  149. from . import permissions
  150.  
  151. # Routers provide an easy way of automatically determining the URL conf.
  152. router = routers.DefaultRouter()
  153. router.register(r'users', views.UserView, 'list')
  154.  
  155. # Wire up our API using automatic URL routing.
  156. # Additionally, we include login URLs for the browsable API.
  157. urlpatterns = [
  158.     url(r'^', include(router.urls)),
  159.     url(r'^token-auth/', authviews.obtain_auth_token),
  160. ]
  161.  
  162. views.py\from django.shortcuts import render
  163. from django.contrib.auth.models import User
  164. from rest_framework import status, serializers
  165. from rest_framework.decorators import api_view
  166. from rest_framework.views import APIView
  167. from rest_framework.response import Response
  168. from rest_framework import authentication, permissions
  169. from users.serializers import UserSerializer
  170. from rest_framework import viewsets
  171. from .permissions import IsSuperUserOrTargetUser
  172. from .models import CustomUser
  173.  
  174. class UserView(viewsets.ModelViewSet):
  175.     serializer_class = UserSerializer
  176.     queryset = CustomUser.objects.all()
  177.     model = CustomUser
  178.     permission_classes = (IsSuperUserOrTargetUser,)
  179.  
  180.     def put(self, request, *args, **kwargs):
  181.         return self.update(request, *args, **kwargs)
Add Comment
Please, Sign In to add comment