I have the following views:
login_view:
@api_view(['POST'])
def login_view(request):
try:
user_data = request.data
username = user_data["username"]
password = user_data["password"]
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
serializer = UserSerializer(user)
return Response(
{
"user":serializer.data,
"login": True
})
else:
return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST)
except:
raise Http404
logout_view:
@api_view(['POST'])
def logout_view(request):
if request.user.is_authenticated:
logout(request)
return Response(status=status.HTTP_200_OK)
else:
return Response(status=status.HTTP_403_FORBIDDEN)
and fetch function on frontend:
const onSubmit = () => {
fetch('http://127.0.0.1:8000/api/login/',{
method:"POST",
headers: {
'Accept': 'application/json, text/plain',
'Content-Type': 'application/json; charset=UTF-8'
},
body: JSON.stringify({
"username": values.Username,
"password": values.Password
})
}).then((response) => {response.json().then(data => {
if(response.ok){
setError('');
console.log(data);
}
else{
setError('');
setError('Invalid Username or Password');
}
})});
};
and the following problem:
When I try to sign in on frontend I get an expected response:
{
user: {id: 4, username: 'Tester_1', date_joined: '2021-12-02T22:38:29.323393Z', trust_index: 0}
login: true
}
but my user is not logged in Rest Framework and I can't use logout view on Frontend: After login on Frontend
When I use Rest Framework panel for login, everything works fine, user is logged in and I can use logout view: After login in Rest Framework
I've been struggling with this for a while. Any ideas how to solve this problem?
CodePudding user response:
I don't know your global code but it seems you are trying to create a session based login/auth system, bringing the autogenerated drf web panel approach to your front. In this separated structure (front and back) this is not the best approach, at least you build a weird structure where Django encapsulates your front and manage sessions etc.
A probably better way is to use jwt token generation/authentication. Where you authenticate (from front) using a user and password but you receive (from back) a token that you have to store locally (local storage, to emulate a session).
In each request you pass the token in the header and if everything is fine (valid token) drf do the stuff.
I use Simple JWT (https://django-rest-framework-simplejwt.readthedocs.io/en/latest/). Really simple.
Here is an example of urls.py for auth endpoints:
from django.urls import include, path
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
website_v1 = 'website/v1/'
urlpatterns = [
path(f'{website_v1}login/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path(f'{website_v1}login/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]
And in front, Axios (https://axios-http.com/docs/intro) is a good js library to automatize the token passing in data fetching using interceptors.
Good Luck!
