Bläddra i källkod

Feature: Add token creation for auth

pull/323/head
winkidney 2 år sedan
förälder
incheckning
2892ebb333
3 ändrade filer med 21 tillägg och 0 borttagningar
  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 Visa fil

@@ -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 Visa fil

@@ -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 Visa fil

@@ -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

Laddar…
Avbryt
Spara