implement auth (register, login, logout)
This commit is contained in:
75
api/serializers.py
Normal file
75
api/serializers.py
Normal file
@@ -0,0 +1,75 @@
|
||||
from django.contrib.auth import authenticate, get_user_model
|
||||
from django.core.validators import validate_email
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from rest_framework import serializers
|
||||
from rest_framework_simplejwt.tokens import RefreshToken
|
||||
|
||||
User = get_user_model()
|
||||
|
||||
|
||||
class RegistrationSerializer(serializers.Serializer):
|
||||
email = serializers.EmailField()
|
||||
password = serializers.CharField(min_length=8, write_only=True)
|
||||
|
||||
def validate_email(self, value):
|
||||
validate_email(value)
|
||||
if User.objects.filter(email__iexact=value).exists():
|
||||
raise serializers.ValidationError(_("Email is already registered."))
|
||||
return value
|
||||
|
||||
def create(self, validated_data):
|
||||
email = validated_data["email"].lower()
|
||||
password = validated_data["password"]
|
||||
user = User.objects.create_user(
|
||||
username=email,
|
||||
email=email,
|
||||
password=password,
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
class LoginSerializer(serializers.Serializer):
|
||||
email = serializers.EmailField()
|
||||
password = serializers.CharField(write_only=True)
|
||||
|
||||
def validate(self, attrs):
|
||||
email = attrs.get("email", "").lower()
|
||||
password = attrs.get("password")
|
||||
if not email or not password:
|
||||
raise serializers.ValidationError(_("Email and password are required."))
|
||||
|
||||
user = authenticate(
|
||||
request=self.context.get("request"),
|
||||
username=email,
|
||||
password=password,
|
||||
)
|
||||
if user is None:
|
||||
raise serializers.ValidationError(_("Invalid email or password."))
|
||||
if not user.is_active:
|
||||
raise serializers.ValidationError(_("User account is disabled."))
|
||||
|
||||
attrs["user"] = user
|
||||
return attrs
|
||||
|
||||
def create(self, validated_data):
|
||||
user = validated_data["user"]
|
||||
refresh = RefreshToken.for_user(user)
|
||||
return {
|
||||
"refresh": str(refresh),
|
||||
"access": str(refresh.access_token),
|
||||
}
|
||||
|
||||
|
||||
class LogoutSerializer(serializers.Serializer):
|
||||
refresh = serializers.CharField()
|
||||
|
||||
def validate(self, attrs):
|
||||
refresh = attrs.get("refresh")
|
||||
if not refresh:
|
||||
raise serializers.ValidationError(_("Refresh token is required."))
|
||||
return attrs
|
||||
|
||||
def create(self, validated_data):
|
||||
refresh = RefreshToken(validated_data["refresh"])
|
||||
refresh.blacklist()
|
||||
return {}
|
||||
Reference in New Issue
Block a user