Skip to content

Commit a1d4f35

Browse files
committed
backend django set jwt token auth
1 parent 4eddcec commit a1d4f35

File tree

7 files changed

+123
-13
lines changed

7 files changed

+123
-13
lines changed

backend/Backend/settings.py

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
1-
from pathlib import Path
21
import os
2+
from datetime import timedelta
3+
from pathlib import Path
4+
from django.conf import settings
35

46
BASE_DIR = Path(__file__).resolve().parent.parent
57

@@ -23,6 +25,41 @@
2325
'core.apps.CoreConfig'
2426
]
2527

28+
REST_FRAMEWORK = {
29+
'DEFAULT_AUTHENTICATION_CLASSES': (
30+
'rest_framework_simplejwt.authentication.JWTAuthentication',
31+
)
32+
}
33+
34+
35+
SIMPLE_JWT = {
36+
'ACCESS_TOKEN_LIFETIME': timedelta(days=30),
37+
'REFRESH_TOKEN_LIFETIME': timedelta(days=1),
38+
'ROTATE_REFRESH_TOKENS': False,
39+
'BLACKLIST_AFTER_ROTATION': True,
40+
'UPDATE_LAST_LOGIN': False,
41+
42+
'ALGORITHM': 'HS256',
43+
'SIGNING_KEY': settings.SECRET_KEY,
44+
'VERIFYING_KEY': None,
45+
'AUDIENCE': None,
46+
'ISSUER': None,
47+
48+
'AUTH_HEADER_TYPES': ('Bearer',),
49+
'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
50+
'USER_ID_FIELD': 'id',
51+
'USER_ID_CLAIM': 'user_id',
52+
53+
'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
54+
'TOKEN_TYPE_CLAIM': 'token_type',
55+
56+
'JTI_CLAIM': 'jti',
57+
58+
'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
59+
'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
60+
'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),
61+
}
62+
2663
MIDDLEWARE = [
2764
'corsheaders.middleware.CorsMiddleware',
2865

backend/Backend/urls.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
from django.contrib import admin
2-
from django.urls import path, include
31
from django.conf import settings
42
from django.conf.urls.static import static
3+
from django.contrib import admin
4+
from django.urls import include, path
55

66
urlpatterns = [
77
path('admin/', admin.site.urls),

backend/Pipfile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ django = "*"
88
djangorestframework = "*"
99
django-cors-headers = "*"
1010
pillow = "*"
11+
djangorestframework-simplejwt = "*"
1112

1213
[dev-packages]
1314
django-linter = "*"

backend/Pipfile.lock

Lines changed: 22 additions & 7 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

backend/core/serializer.py

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,50 @@
11
from django.contrib.auth.models import User
2-
from rest_framework.serializers import ModelSerializer
2+
from rest_framework.serializers import ModelSerializer, SerializerMethodField
3+
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
4+
from rest_framework_simplejwt.tokens import RefreshToken
35

46
from core.models import Order, OrderItem, Product, Review, ShippingAddress
57

68

9+
class UserSerializer(ModelSerializer):
10+
_id = SerializerMethodField(read_only=True)
11+
isAdmin = SerializerMethodField(read_only=True)
12+
13+
class Meta:
14+
model = User
15+
fields = ('_id', 'username', 'email', 'isAdmin')
16+
17+
def get__id(self, obj):
18+
return obj.id
19+
20+
def get_isAdmin(self, obj):
21+
return obj.is_staff
22+
23+
24+
class UserSerializerWithToken(UserSerializer):
25+
token = SerializerMethodField(read_only=True)
26+
27+
class Meta:
28+
model = User
29+
fields = ('_id', 'username', 'email', 'isAdmin', 'token')
30+
31+
def get_token(self, obj):
32+
token = RefreshToken.for_user(obj)
33+
return str(token.access_token)
34+
35+
736
class ProductSerializer(ModelSerializer):
837
class Meta:
938
model = Product
1039
fields = '__all__'
40+
41+
42+
class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
43+
def validate(self, attrs):
44+
data = super().validate(attrs)
45+
46+
serializer = UserSerializerWithToken(self.user).data
47+
for k, v in serializer.items():
48+
data[k] = v
49+
50+
return data

backend/core/urls.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
11
from django.urls import path
2-
from core.views import getProducts, getProduct
2+
3+
from core.views import (MyTokenObtainPairView, getProduct, getProducts,
4+
getUserProfile)
35

46
APP_NAME = 'core'
57

68
urlpatterns = [
9+
path('users/login/', MyTokenObtainPairView.as_view(), name="token_obtain_pair"),
10+
path('users/profile/', getUserProfile, name="user-profile"),
711
path('products/', getProducts, name="get-products"),
812
path('product/<int:id>/', getProduct, name="get-product"),
913
]

backend/core/views.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,21 @@
11
from rest_framework.decorators import api_view
22
from rest_framework.response import Response
3+
from rest_framework_simplejwt.views import TokenObtainPairView
34

45
from core.models import Order, OrderItem, Product, Review, ShippingAddress
5-
from core.serializer import ProductSerializer
6+
from core.serializer import (MyTokenObtainPairSerializer, ProductSerializer,
7+
UserSerializer)
8+
9+
10+
class MyTokenObtainPairView(TokenObtainPairView):
11+
serializer_class = MyTokenObtainPairSerializer
12+
13+
14+
@api_view(['GET'])
15+
def getUserProfile(request):
16+
user = request.user
17+
serializer = UserSerializer(user, many=False)
18+
return Response(serializer.data)
619

720

821
@api_view(['GET'])

0 commit comments

Comments
 (0)