100 lines
3.4 KiB
Python
100 lines
3.4 KiB
Python
from django.contrib.auth.models import User
|
|
from rest_framework.views import APIView
|
|
from rest_framework.response import Response
|
|
from rest_framework import serializers
|
|
# from drf_spectacular.utils import extend_schema, inline_serializer
|
|
from drf_yasg import openapi
|
|
from drf_yasg.utils import swagger_auto_schema
|
|
|
|
|
|
class Register(APIView):
|
|
|
|
@swagger_auto_schema(
|
|
request_body=openapi.Schema(
|
|
type=openapi.TYPE_OBJECT,
|
|
required=["username", "password"],
|
|
properties={
|
|
"username": openapi.Schema(
|
|
type=openapi.TYPE_STRING,
|
|
description="Username"
|
|
),
|
|
"password": openapi.Schema(
|
|
type=openapi.TYPE_STRING,
|
|
description="Password"
|
|
),
|
|
},
|
|
),
|
|
responses={
|
|
201: "User created",
|
|
409: "Duplicated username",
|
|
}
|
|
)
|
|
def post(self, request):
|
|
body = request.data
|
|
username = body['username']
|
|
password = body['password']
|
|
if User.objects.filter(username=username).exists():
|
|
return Response({"massage:duplicated username"}, 409)
|
|
User.objects.create_user(username=username, password=password)
|
|
return Response({
|
|
"massage":"user created"
|
|
},201)
|
|
|
|
class login (APIView):
|
|
@swagger_auto_schema(
|
|
operation_summary="Login",
|
|
operation_description="Authenticate a user and return a token.",
|
|
request_body=openapi.Schema(
|
|
type=openapi.TYPE_OBJECT,
|
|
required=["username", "password"],
|
|
properties={
|
|
"username": openapi.Schema(
|
|
type=openapi.TYPE_STRING,
|
|
description="Username"
|
|
),
|
|
"password": openapi.Schema(
|
|
type=openapi.TYPE_STRING,
|
|
description="Password"
|
|
),
|
|
},
|
|
),
|
|
responses={
|
|
200: openapi.Response(
|
|
description="Login successful",
|
|
schema=openapi.Schema(
|
|
type=openapi.TYPE_OBJECT,
|
|
properties={
|
|
"message": openapi.Schema(
|
|
type=openapi.TYPE_STRING,
|
|
example="token is : 123456abcdef"
|
|
)
|
|
},
|
|
),
|
|
),
|
|
401: openapi.Response(
|
|
description="Invalid username or password",
|
|
schema=openapi.Schema(
|
|
type=openapi.TYPE_OBJECT,
|
|
properties={
|
|
"message": openapi.Schema(
|
|
type=openapi.TYPE_STRING,
|
|
example="Invalid username or password"
|
|
)
|
|
},
|
|
),
|
|
),
|
|
},
|
|
)
|
|
def post (self,request):
|
|
username = request.data.get("username")
|
|
password = request.data.get("password")
|
|
User = authenticate(username=username,password=password)
|
|
if User is None:
|
|
return Response ({
|
|
"massage":"token created"
|
|
},401)
|
|
|
|
token, created = Token.pbjects.get_or_create(User=User)
|
|
return Response ({
|
|
"massage":{f"token is :{token}"}
|
|
},200) |