c3lf-system-3/core/authentication/api_v2.py

58 lines
1.6 KiB
Python
Raw Normal View History

2023-11-23 22:17:20 +00:00
from rest_framework import routers, viewsets, serializers
2023-12-08 23:57:09 +00:00
from rest_framework.decorators import api_view, permission_classes, authentication_classes
from rest_framework.response import Response
from rest_framework.authentication import BasicAuthentication
2023-11-23 22:17:20 +00:00
from django.contrib.auth.models import User
2023-12-09 00:07:01 +00:00
from django.urls import path
2023-11-23 22:17:20 +00:00
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username', 'email', 'first_name', 'last_name')
2023-12-08 23:57:09 +00:00
class RegisterUserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'password', 'email')
extra_kwargs = {
'password': {'write_only': True},
}
2023-11-23 22:17:20 +00:00
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
2023-12-08 23:57:09 +00:00
authentication_classes = [BasicAuthentication]
2023-11-23 22:17:20 +00:00
permission_classes = []
2023-12-08 23:57:09 +00:00
@api_view(['GET'])
@permission_classes([])
@authentication_classes([BasicAuthentication])
def token(request):
return Response({
'token': request.user.auth_token.key
})
@api_view(['POST'])
@permission_classes([])
@authentication_classes([])
def registerUser(request):
serializer = RegisterUserSerializer(data=request.data)
if serializer.is_valid():
user = serializer.save()
return Response({'username': user.username, 'email': user.email}, status=201)
return Response(serializer.errors, status=400)
2023-11-23 22:17:20 +00:00
router = routers.SimpleRouter()
router.register(r'users', UserViewSet, basename='users')
2023-12-09 00:07:01 +00:00
urlpatterns = router.urls + [
path('token/', token),
path('register/', registerUser),
]