Explorar el Código

Feature: Add token creation for auth

pull/323/head
winkidney hace 2 años
padre
commit
2892ebb333
Se han modificado 3 ficheros con 21 adiciones y 0 borrados
  1. +1
    -0
      pinry/settings/base.py
  2. +15
    -0
      users/models.py
  3. +5
    -0
      users/serializers.py

+ 1
- 0
pinry/settings/base.py Ver fichero

@@ -15,6 +15,7 @@ INSTALLED_APPS = [
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'django_filters',
'taggit',
'compressor',


+ 15
- 0
users/models.py Ver fichero

@@ -1,6 +1,8 @@
import hashlib

from django.contrib.auth.models import User as BaseUser
from django.db.models.signals import post_save
from django.dispatch import receiver


class User(BaseUser):
@@ -10,3 +12,16 @@ class User(BaseUser):

class Meta:
proxy = True

def create_token_if_necessary(self):
from rest_framework.authtoken.models import Token
token = Token.objects.filter(user=self).first()
if token is not None:
return token
else:
return Token.objects.create(user=self)


@receiver(post_save, sender=User)
def create_profile(sender, instance: User, **kwargs):
instance.create_token_if_necessary()

+ 5
- 0
users/serializers.py Ver fichero

@@ -26,6 +26,7 @@ class UserSerializer(serializers.HyperlinkedModelSerializer):
model = User
fields = (
'username',
'token',
'email',
'gravatar',
'password',
@@ -52,6 +53,7 @@ class UserSerializer(serializers.HyperlinkedModelSerializer):
min_length=6,
max_length=32,
)
token = serializers.SerializerMethodField(read_only=True)

def create(self, validated_data):
if validated_data['password'] != validated_data['password_repeat']:
@@ -73,3 +75,6 @@ class UserSerializer(serializers.HyperlinkedModelSerializer):
backend=settings.AUTHENTICATION_BACKENDS[0],
)
return user

def get_token(self, obj: User):
return obj.create_token_if_necessary().key

Cargando…
Cancelar
Guardar