Files
gitrusprusandCursor 4eb4c145b6 Add JWT auth with per-user data isolation and account settings.
Users can register, log in, and manage profile/password in a personal account page; server data is scoped by owner across contacts, maps, tags, and import.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-28 21:10:16 +03:00

67 lines
1.9 KiB
Python

from rest_framework import status
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import RefreshToken
from contacts.bootstrap import ensure_user_defaults
from core.drf_mixins import JwtAuthMixin
from .auth_serializers import (
ChangePasswordSerializer,
RegisterSerializer,
UpdateProfileSerializer,
UserSerializer,
)
def tokens_for_user(user):
refresh = RefreshToken.for_user(user)
return {
'refresh': str(refresh),
'access': str(refresh.access_token),
'user': UserSerializer(user).data,
}
class RegisterView(JwtAuthMixin, APIView):
def get_permissions(self):
return [AllowAny()]
def post(self, request):
serializer = RegisterSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.save()
ensure_user_defaults(user)
return Response(tokens_for_user(user), status=status.HTTP_201_CREATED)
class MeView(JwtAuthMixin, APIView):
def get_permissions(self):
return [IsAuthenticated()]
def get(self, request):
return Response(UserSerializer(request.user).data)
def patch(self, request):
serializer = UpdateProfileSerializer(
data=request.data,
context={'request': request},
)
serializer.is_valid(raise_exception=True)
user = serializer.save()
return Response(UserSerializer(user).data)
class ChangePasswordView(JwtAuthMixin, APIView):
def get_permissions(self):
return [IsAuthenticated()]
def post(self, request):
serializer = ChangePasswordSerializer(
data=request.data,
context={'request': request},
)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response({'detail': 'Пароль изменён.'})