- Add djangorestframework-simplejwt==5.3.1 to requirements-docker.txt - Configure REST_FRAMEWORK with JWTAuthentication and SIMPLE_JWT settings - Create admin_api Django app with AdminLoginView, MeView, HealthView - Wire /api/v1/ routes without touching existing /api/ mobile endpoints - Resolve pre-existing events migration conflict (0010_merge) - Superuser admin created for initial authentication
53 lines
2.1 KiB
Python
53 lines
2.1 KiB
Python
from django.contrib.auth import authenticate, get_user_model
|
|
from rest_framework.views import APIView
|
|
from rest_framework.response import Response
|
|
from rest_framework.permissions import AllowAny, IsAuthenticated
|
|
from rest_framework import status
|
|
from rest_framework_simplejwt.tokens import RefreshToken
|
|
from rest_framework_simplejwt.views import TokenRefreshView
|
|
from django.db import connection
|
|
from .serializers import UserSerializer
|
|
|
|
User = get_user_model()
|
|
|
|
class AdminLoginView(APIView):
|
|
permission_classes = [AllowAny]
|
|
def post(self, request):
|
|
identifier = request.data.get('username') or request.data.get('email')
|
|
password = request.data.get('password')
|
|
if not identifier or not password:
|
|
return Response({'error': 'username/email and password required'}, status=status.HTTP_400_BAD_REQUEST)
|
|
# Try username first, then email
|
|
user = authenticate(request, username=identifier, password=password)
|
|
if not user:
|
|
try:
|
|
u = User.objects.get(email=identifier)
|
|
user = authenticate(request, username=u.username, password=password)
|
|
except User.DoesNotExist:
|
|
pass
|
|
if not user:
|
|
return Response({'error': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED)
|
|
if not user.is_active:
|
|
return Response({'error': 'Account is disabled'}, status=status.HTTP_403_FORBIDDEN)
|
|
refresh = RefreshToken.for_user(user)
|
|
return Response({
|
|
'access': str(refresh.access_token),
|
|
'refresh': str(refresh),
|
|
'user': UserSerializer(user).data,
|
|
})
|
|
|
|
class MeView(APIView):
|
|
permission_classes = [IsAuthenticated]
|
|
def get(self, request):
|
|
return Response({'user': UserSerializer(request.user).data})
|
|
|
|
class HealthView(APIView):
|
|
permission_classes = [AllowAny]
|
|
def get(self, request):
|
|
try:
|
|
connection.ensure_connection()
|
|
db_status = 'ok'
|
|
except Exception:
|
|
db_status = 'error'
|
|
return Response({'status': 'ok', 'db': db_status})
|