Reputation: 453
I have an APi that supports log-in functionality and whenever i switch page to index page, user is not logged in anymore at this point i have no idea what am i doing wrong tbh.
this is my views for logging in
@csrf_exempt
@api_view(["POST", "GET"])
@permission_classes((AllowAny,))
def login(request):
username = request.data.get("username")
password = request.data.get("password")
if username is None or password is None:
return Response({'error': 'Please provide both username and password'},
status=HTTP_400_BAD_REQUEST)
user = authenticate(username=username, password=password)
if not user:
return Response({'error': 'Invalid Credentials'},
status=HTTP_404_NOT_FOUND)
request.session.save()
return Response({'Success': 'Logged in'},
status=HTTP_200_OK)
and this is a simple test view for index page, my session.items()
is blank and request.user
outputs AnonymousUser
def test_view(request):
print(request.session.items())
print(request.user)
return HttpResponse(request.COOKIES.keys())
and in my settings i have
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.SessionAuthentication',
),
Upvotes: 0
Views: 887
Reputation: 437
You have to login()
your user after authenticate
user = authenticate(username=username, password=password)
if not user:
. . .
login(request, user)
Upvotes: 1