Skip to content

Instantly share code, notes, and snippets.

@sertraline
Last active October 2, 2023 12:54
Show Gist options
  • Save sertraline/87b36eeff444bd404db0c050f063ff4b to your computer and use it in GitHub Desktop.
Save sertraline/87b36eeff444bd404db0c050f063ff4b to your computer and use it in GitHub Desktop.
Django DRF session auth
# JWT токен не работает в SSR приложениях по типу NextJS/Sveltekit которые не могут передать на сторону сервера заголовки.
# Варианта два, передавать токен в кукисах или отказаться от токена. Это второй вариант решения
from rest_framework.decorators import api_view, authentication_classes
from rest_framework.response import Response
from rest_framework import status
from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from django.contrib.auth import login
from ..serializers.Registration import RegistrationSerializer
from ..models import CustomUser
@swagger_auto_schema(
operation_description="Create a new user",
method="POST",
request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
properties={
"username": openapi.Schema(type=openapi.TYPE_STRING),
"password": openapi.Schema(type=openapi.TYPE_STRING),
},
),
responses={201: "Created"},
)
@authentication_classes([])
@api_view(["POST"])
def register(request):
sz = RegistrationSerializer(data=request.data)
if not sz.is_valid():
return Response(sz.errors, status=status.HTTP_400_BAD_REQUEST)
data = sz.data
queryset = CustomUser.objects.all()
if not queryset.filter(username=data["username"]).exists():
u = CustomUser(username=data["username"])
u.set_password(data["password"])
u.save()
else:
return Response(
"User with this username already exists.",
status=status.HTTP_400_BAD_REQUEST,
)
resp = {k: v for k, v in sz.data.items() if k != "password"}
return Response(resp, status=status.HTTP_201_CREATED)
@swagger_auto_schema(
operation_description="Log in the user",
method="POST",
request_body=openapi.Schema(
type=openapi.TYPE_OBJECT,
properties={
"username": openapi.Schema(type=openapi.TYPE_STRING),
"password": openapi.Schema(type=openapi.TYPE_STRING),
},
),
responses={200: "Success"},
)
@authentication_classes([])
@api_view(["POST"])
def auth_login(request):
sz = RegistrationSerializer(data=request.data)
if not sz.is_valid():
return Response(sz.errors, status=status.HTTP_400_BAD_REQUEST)
data = sz.data
queryset = CustomUser.objects.all()
not_valid = Response(
"Username or password are not valid.", status=status.HTTP_400_BAD_REQUEST
)
u = queryset.filter(username=data["username"]).first()
if not u:
return not_valid
if u.check_password(data["password"]):
login(request._request, u)
x = Response("Success", status=status.HTTP_200_OK)
x.set_cookie("sessionid", request._request.session.session_key)
return x
else:
return not_valid
@swagger_auto_schema(
operation_description="Test if you are logged in",
method="GET",
responses={200: "Success"},
)
@authentication_classes([])
@api_view(["GET"])
def auth_test(request):
return Response(request.user.username, status=status.HTTP_200_OK)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment