Created
January 23, 2015 11:27
-
-
Save wwnbb/f90a2b3abac41f569f42 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 'use strict'; | |
| angular.module('auth') | |
| .directive('authApplication', function($http, localStorageService, User) { | |
| return { | |
| restrict: 'A', | |
| scope: false, | |
| link: function (scope, elem, attrs) { | |
| var main = document.getElementById("main"); | |
| var login = document.getElementById("login-holder"); | |
| var applyLogin = function(good) { | |
| if (good) { | |
| main.style.display = "block"; | |
| login.style.display = "none"; | |
| } else { | |
| main.style.display = "none"; | |
| login.style.display = "block"; | |
| } | |
| }; | |
| applyLogin(true) | |
| if (localStorageService.get('token')) { | |
| applyLogin(true); | |
| } | |
| scope.$on('event:auth-loginRequired', function () { | |
| applyLogin(false); | |
| }); | |
| scope.$on('event:auth-loginConfirmed', function () { | |
| applyLogin(true); | |
| }); | |
| } | |
| }; | |
| }) | |
| .directive('hasPermission', function(permissions) { | |
| return { | |
| scope: false, | |
| link: function(scope, element, attrs) { | |
| if(!_.isString(attrs.hasPermission)){ | |
| throw "hasPermission value must be a string"; | |
| } | |
| var value = attrs.hasPermission.trim(); | |
| var notPermissionFlag = value[0] === '!'; | |
| if(notPermissionFlag) { | |
| value = value.slice(1).trim(); | |
| } | |
| function toggleVisibilityBasedOnPermission() { | |
| var hasPermission = permissions.hasPermission(value); | |
| if(hasPermission && !notPermissionFlag || !hasPermission && notPermissionFlag) { | |
| element.show(); | |
| } | |
| else { | |
| element.hide(); | |
| } | |
| } | |
| toggleVisibilityBasedOnPermission(); | |
| scope.$on('permissionsChanged', toggleVisibilityBasedOnPermission); | |
| } | |
| }; | |
| }) | |
| .directive('login', function($http, api, localStorageService, authService) { | |
| return { | |
| restrict: 'E', | |
| scope: false, | |
| transclude: false, | |
| templateUrl: 'static/src/auth/templates/login.html', | |
| link: function(scope, elem, attrs) { | |
| elem.bind('submit', function() { | |
| localStorageService.remove('token'); | |
| var userData = { | |
| "username": scope.username, | |
| "password": scope.password | |
| }; | |
| api.all('api-token-auth/').customPOST(userData).then(function(response){ | |
| localStorageService.set('token', 'Token ' + response.data.token); | |
| authService.loginConfirmed(); | |
| }, function (res) { | |
| scope.status = res; | |
| alert('Неправильный логи или пароль'); | |
| scope.error = 'Неправильный логин или пароль'; | |
| }); | |
| }); | |
| } | |
| }; | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # coding=utf-8 | |
| from django.db import models | |
| from django.utils import timezone | |
| from django.utils.http import urlquote | |
| from django.core.mail import send_mail | |
| from django.contrib.auth.models import ( | |
| AbstractBaseUser, PermissionsMixin, BaseUserManager) | |
| class CustomUserManager(BaseUserManager): | |
| def _create_user(self, email, password, | |
| is_staff, is_superuser, **extra_fields): | |
| now = timezone.now() | |
| if not email: | |
| raise ValueError('The given email must be set') | |
| email = self.normalize_email(email) | |
| user = self.model(email=email, | |
| is_staff=is_staff, is_active=True, | |
| is_superuser=is_superuser, last_login=now, | |
| date_joined=now, **extra_fields) | |
| user.set_password(password) | |
| user.save(using=self._db) | |
| return user | |
| def create_user(self, email, password=None, **extra_fields): | |
| return self._create_user(email, password, False, False, **extra_fields) | |
| def create_superuser(self, email, password, **extra_fields): | |
| return self._create_user(email, password, True, True, **extra_fields) | |
| class UserPermissions(models.Model): | |
| permission = models.CharField(max_length=40, verbose_name=u'Разрешение') | |
| def __unicode__(self): | |
| return '%s' % self.permission | |
| class CustomUser(AbstractBaseUser, PermissionsMixin): | |
| email = models.EmailField(u'Электронная почта', max_length=254, unique=True) | |
| first_name = models.CharField(u'Имя', max_length=30, blank=True) | |
| last_name = models.CharField(u'Фамилия', max_length=30, blank=True) | |
| is_staff = models.BooleanField(u'Статус персонала', default=False) | |
| is_active = models.BooleanField(u'Активность', default=True) | |
| date_joined = models.DateTimeField( | |
| u'Дата регистрации', | |
| default=timezone.now) | |
| cash = models.IntegerField(u'Кошелек', blank=True, null=True) | |
| permissions = models.ManyToManyField( | |
| UserPermissions, | |
| verbose_name=u'Привилегии пользователя') | |
| objects = CustomUserManager() | |
| USERNAME_FIELD = 'email' | |
| REQUIRED_FIELDS = [] | |
| class Meta: | |
| verbose_name = u'Аккаунт' | |
| verbose_name_plural = u'Аккаунты' | |
| def get_absolute_url(self): | |
| return "/users/%s/" % urlquote(self.email) | |
| def get_full_name(self): | |
| full_name = '%s %s' % (self.first_name, self.last_name) | |
| return full_name.strip() | |
| def get_short_name(self): | |
| return self.first_name | |
| def email_user(self, subject, message, from_email=None): | |
| send_mail(subject, message, from_email, [self.email]) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from django.contrib.auth.models import Group | |
| from rest_framework import serializers | |
| from cmanager.models import UserPermissions | |
| from django.contrib.auth import get_user_model | |
| User = get_user_model() | |
| class PermissionSerializer(serializers.ModelSerializer): | |
| class Meta: | |
| model = UserPermissions | |
| class UserSerializer(serializers.ModelSerializer): | |
| class Meta: | |
| model = User | |
| write_only_fields = ('password',) | |
| def restore_object(self, attrs, instance=None): | |
| user = super(UserSerializer, self).restore_object(attrs, instance) | |
| user.set_password(attrs['password']) | |
| return user | |
| class CustomerAccountSerializer(serializers.ModelSerializer): | |
| class Meta: | |
| model = User | |
| write_only_fields = ('password',) | |
| depth = 1 | |
| class ProfileSerializer(serializers.ModelSerializer): | |
| permissions_names = serializers.SlugRelatedField( | |
| many=True, | |
| source='permissions', | |
| slug_field='permission', | |
| read_only=True) | |
| class Meta: | |
| model = User | |
| fields = ( | |
| 'id', | |
| 'email', | |
| 'first_name', | |
| 'last_name', | |
| 'date_joined', | |
| 'permissions', | |
| 'permissions_names') | |
| read_only_fields = ('date_joined',) | |
| class GroupSerializer(serializers.ModelSerializer): | |
| class Meta: | |
| model = Group | |
| class UserPermissionsSerializer(serializers.ModelSerializer): | |
| class Meta: | |
| model = UserPermissions |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # -*- coding: utf-8 -*- | |
| from django.contrib.auth.models import Group | |
| from rest_framework import viewsets, permissions, filters, generics | |
| from rest_framework.views import APIView | |
| from .serializers import User | |
| from . import serializers | |
| from rest_framework.response import Response | |
| from cmanager.models import UserPermissions | |
| class UserViewSet(viewsets.ModelViewSet): | |
| queryset = User.objects.all() | |
| serializer_class = serializers.ProfileSerializer | |
| filter_backends = ( | |
| filters.DjangoFilterBackend, | |
| filters.OrderingFilter, | |
| filters.SearchFilter, | |
| ) | |
| permission_classes = (permissions.IsAuthenticated,) | |
| filter_fields = ('email') | |
| search_fields = ('email', 'first_name', 'last_name') | |
| class CurrentUserView(APIView): | |
| permission_classes = (permissions.IsAuthenticated,) | |
| def get(self, request): | |
| serializer = serializers.ProfileSerializer(request.user) | |
| return Response(serializer.data) | |
| class RegistrationView(generics.ListCreateAPIView): | |
| model = User | |
| serializer_class = serializers.UserSerializer | |
| class PermissionsListView(generics.ListAPIView): | |
| model = UserPermissions | |
| serializer_class = serializers.PermissionSerializer | |
| permission_classes = (permissions.IsAuthenticated,) | |
| class GroupViewSet(viewsets.ModelViewSet): | |
| queryset = Group.objects.all() | |
| serializer_class = serializers.GroupSerializer | |
| permission_classes = (permissions.IsAuthenticated,) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment