So, this is the final round of this tutorial.....😁😁😁😁😁
Let create a JWT Authentication:
- helper file to create a token and authentication using cookies.
- create a helper.py file inside a accounts app.
from django.contrib.auth import get_user_model
import jwt
import datetime
from django.conf import settings
from rest_framework.authentication import BaseAuthentication
from rest_framework import exceptions
User = get_user_model()
def generate_access_token(user, *args, **kwargs):
payload = {
"user_id": user.id,
"exp": datetime.datetime.utcnow() + datetime.timedelta(minutes=60),
"iat": datetime.datetime.utcnow(),
}
return jwt.encode(payload, settings.SECRET_KEY, algorithm='HS256').decode("utf-8")
class JWTauthentication(BaseAuthentication):
def authenticate(self, request):
token = request.COOKIES.get("jwt")
if not token:
return None
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])
except jwt.ExpiredSignatureError:
raise exceptions.AuthenticationFailed("Unauthenticated")
user = User.objects.filter(id=payload["user_id"]).first()
if user is None:
raise exceptions.AuthenticationFailed("User Not Found")
return (user, None)
Let's march to views.py file to create login and logout api view.
@api_view(["POST"])
def login_view(request, *args, **kwargs):
if request.user.is_authenticated:
return Response({'Message': 'You are already logged in ...'}, status=400)
username = request.data.get("username")
password = request.data.get("password")
user = (
User.objects.filter(Q(username__iexact=username)
| Q(email__iexact=username))
.distinct()
.first()
)
if user is None:
raise exceptions.AuthenticationFailed("user not found")
if not user.check_password(password):
raise exceptions.AuthenticationFailed("Incorrect password")
response = Response()
token = generate_access_token(user)
response.set_cookie(key="jwt", value=token, httponly=True)
response.data = {"jwt": token}
return response
@api_view(["POST"])
def logout_view(request):
response = Response()
response.delete_cookie(key="jwt")
response.data = {"message": "success"}
return response
Our Login and logout views are done. Now we are registering login and logout views on urls.py file.
from django.urls import path
from .views import register_view, login_view, logout_view
urlpatterns = [
path('register', register_view, name="register"),
path('login', login_view, name="login"),
path('logout', logout_view, name="logout")
]
Now our test begins with postman:
Our Registerseems like this:
An our Login with token💪💪💪💪💪
[Note: our login will support both username and email]
Finally It is over.. 💥💥💥.
Hope you guys enjoyed it.... bye bye till next tuts ✋✋