1+ import json
2+
13from django .conf import settings
2- from django .contrib .auth import get_user_model
4+ from django .contrib .auth import authenticate , get_user_model , login , logout
5+ from django .http import JsonResponse
6+ from django .views .decorators .csrf import ensure_csrf_cookie
7+ from django .views .decorators .http import require_POST
38from requests .exceptions import HTTPError
49from rest_framework import permissions , serializers , status
510from rest_framework .decorators import api_view , permission_classes
1520User = get_user_model ()
1621
1722
23+ @require_POST
24+ def logout_view (request ):
25+ logout (request )
26+ return JsonResponse ({"detail" : "Logout Successful" })
27+
28+
29+ @ensure_csrf_cookie
30+ def login_set_cookie (request ):
31+ """
32+ `login_view` requires that a csrf cookie be set.
33+ `getCsrfToken` in `auth.js` uses this cookie to
34+ make a request to `login_view`
35+ """
36+ return JsonResponse ({"details" : "CSRF cookie set" })
37+
38+
39+ @require_POST
40+ def login_view (request ):
41+ """
42+ This function logs in the user and returns
43+ and HttpOnly cookie, the `sessionid` cookie
44+ """
45+ data = json .loads (request .body )
46+ email = data .get ('email' )
47+ password = data .get ('password' )
48+ if email is None or password is None :
49+ return JsonResponse (
50+ {"errors" : {"__all__" : "Please enter both username and password" }},
51+ status = 400 ,
52+ )
53+ user = authenticate (email = email , password = password )
54+ if user is not None :
55+ login (request , user )
56+ return JsonResponse ({"detail" : "Success" })
57+ return JsonResponse ({"detail" : "Invalid credentials" }, status = 400 )
58+
59+
1860def get_tokens_for_user (user ):
1961 refresh = RefreshToken .for_user (user )
2062
@@ -29,7 +71,10 @@ class SocialSerializer(serializers.Serializer):
2971 Serializer which accepts an OAuth2 code.
3072 """
3173
32- code = serializers .CharField (allow_blank = False , trim_whitespace = True ,)
74+ code = serializers .CharField (
75+ allow_blank = False ,
76+ trim_whitespace = True ,
77+ )
3378
3479
3580@api_view (http_method_names = ["POST" ])
0 commit comments