-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Ivan
committed
May 2, 2023
1 parent
aa5b373
commit 3a5c0bc
Showing
2 changed files
with
81 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
from django.contrib.auth.models import update_last_login | ||
from django.db.utils import IntegrityError | ||
from rest_framework import serializers | ||
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer | ||
from rest_framework_simplejwt.settings import api_settings | ||
|
||
from accounts.models import User | ||
from api.exceptions import UserAlreadyExists | ||
|
||
|
||
class UserSerializer(serializers.ModelSerializer): | ||
class Meta: | ||
model = User | ||
fields = [ | ||
'id', 'username', 'email', | ||
'first_name', 'last_name', 'is_active', | ||
] | ||
read_only_field = ['is_active'] | ||
|
||
|
||
class SignInSerializer(TokenObtainPairSerializer): | ||
|
||
def validate(self, attrs): | ||
data = super().validate(attrs) | ||
token = self.get_token(self.user) | ||
|
||
data['user'] = UserSerializer(self.user).data | ||
data['refresh'] = str(token) | ||
data['access'] = str(token.access_token) | ||
|
||
if api_settings.UPDATE_LAST_LOGIN: | ||
update_last_login(None, self.user) | ||
|
||
return data | ||
|
||
|
||
class SignUpSerializer(UserSerializer): | ||
username = serializers.CharField( | ||
max_length=64, | ||
min_length=3, | ||
write_only=True, | ||
required=True | ||
) | ||
first_name = serializers.CharField( | ||
max_length=150, | ||
min_length=3 | ||
) | ||
last_name = serializers.CharField( | ||
max_length=50, | ||
min_length=3 | ||
) | ||
password = serializers.CharField( | ||
max_length=128, | ||
min_length=8, | ||
write_only=True, | ||
required=True | ||
) | ||
email = serializers.EmailField( | ||
max_length=254, | ||
write_only=True, | ||
required=True | ||
) | ||
|
||
class Meta: | ||
model = User | ||
fields = [ | ||
'username', 'password', 'email', | ||
'first_name', 'last_name', 'is_active', | ||
] | ||
|
||
def create(self, validated_data): | ||
try: | ||
return User.objects.create_user(**validated_data) | ||
except IntegrityError: | ||
raise UserAlreadyExists() |