Skip to content

Commit 8d30fb5

Browse files
committed
Created complete autheticated Rest API)
1 parent 440eeb5 commit 8d30fb5

File tree

11 files changed

+70
-51
lines changed

11 files changed

+70
-51
lines changed
Binary file not shown.
824 Bytes
Binary file not shown.
2.2 KB
Binary file not shown.

backend/api/serializer.py

Lines changed: 20 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ def get_token(cls, user):
2121
token['username'] = user.username
2222
token['email'] = user.email
2323
token['bio'] = user.profile.bio
24-
token['image'] = user.profile.image
24+
token['image'] = str(user.profile.image)
2525
token['verified'] = user.profile.verified
2626

2727
return token
@@ -30,30 +30,28 @@ class RegisterSerializer(serializers.ModelSerializer):
3030
password = serializers.CharField(
3131
write_only=True, validators=[validate_password]
3232
)
33-
password2= serializers.CharField(
34-
write_only=True, validators=True
33+
password2 = serializers.CharField(
34+
write_only=True, validators=[validate_password]
3535
)
3636

3737
class Meta:
3838
model = User
39-
fields = ['email', 'username', 'password2']
39+
fields = ['email', 'username', 'password', 'password2']
40+
41+
def validate(self, attrs):
42+
if attrs['password'] != attrs['password2']:
43+
raise serializers.ValidationError({
44+
"password": "Passwords do not match"
45+
})
46+
return attrs
47+
48+
def create(self, validated_data):
49+
user = User.objects.create(
50+
username=validated_data['username'],
51+
email=validated_data['email'],
52+
)
4053

41-
def validate(self, attrs):
42-
if attrs['password'] != attrs['password2']:
43-
raise serializers.ValidationError({
44-
"password": "Password Fields doesnt match"
45-
})
46-
47-
return attrs
54+
user.set_password(validated_data['password'])
55+
user.save()
4856

49-
def create(self, validated_data):
50-
user = User.objects.create(
51-
username=validated_data['username'],
52-
email=validated_data['email'],
53-
)
54-
55-
user.set_password(validated_data['password'])
56-
user.save()
57-
58-
return user
59-
57+
return user

backend/api/urls.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
1-
from rest_framework_simplejwt.tokens import Token
2-
31
from django.urls import path
2+
from rest_framework_simplejwt.views import TokenRefreshView
3+
from api import views
44

5-
from . import views
5+
urlpatterns = [
6+
path('token/', views.MyTokenObtainPairView.as_view(), name='token_obtain_pair'),
7+
path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
8+
path('register/', views.RegisterView.as_view(), name='register'),
9+
path('dashboard/', views.DashboardView, name='dashboard'),
10+
]

backend/api/views.py

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,29 @@
11
from django.shortcuts import render
2+
from api.models import Profile, User # Corrected capitalization of Profile and User
3+
from api.serializer import UserSerializer, MyTokenObtainPairSerializer, RegisterSerializer
4+
from rest_framework.response import Response # Corrected import statement for Response
5+
from rest_framework import status
6+
from rest_framework.decorators import api_view, permission_classes # Corrected import statement for decorators
7+
from rest_framework.permissions import AllowAny, IsAuthenticated
8+
from rest_framework_simplejwt.views import TokenObtainPairView
9+
from rest_framework import generics
210

3-
# Create your views here.
11+
class MyTokenObtainPairView(TokenObtainPairView):
12+
serializer_class = MyTokenObtainPairSerializer
13+
14+
class RegisterView(generics.CreateAPIView):
15+
queryset = User.objects.all() # Corrected typo in queryset definition
16+
permission_classes = (AllowAny,) # Corrected tuple syntax for permission_classes
17+
serializer_class = RegisterSerializer
18+
19+
@api_view(['GET', 'POST']) # Corrected syntax for specifying HTTP methods
20+
@permission_classes([IsAuthenticated]) # Corrected syntax for specifying permission_classes
21+
def DashboardView(request):
22+
if request.method == 'GET':
23+
context = f"Hey {request.user}, You are seeing a GET response"
24+
return Response({'response': context}, status=status.HTTP_200_OK) # Corrected status code syntax
25+
elif request.method == 'POST':
26+
text = request.data.get("text") # Changed request.POST to request.data for REST framework
27+
context = f"Hey {request.user}, You are seeing a POST response. Your text is {text}" # Changed response to context for correct variable usage
28+
return Response({'response': context}, status=status.HTTP_200_OK) # Corrected status code syntax
29+
return Response({}, status=status.HTTP_400_BAD_REQUEST) # Corrected status code syntax
Binary file not shown.
-586 Bytes
Binary file not shown.

backend/backend/settings.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -60,13 +60,6 @@
6060
'django.middleware.common.CommonMiddleware',
6161
]
6262

63-
REST_FRAMEWORK = {
64-
# Use Django's standard `django.contrib.auth` permissions,
65-
# or allow read-only access for unauthenticated users.
66-
'DEFAULT_AUTHENTICATION_CLASSES': [
67-
'rest_framework_simplejwt.authentication.JWTAuthetication',
68-
]
69-
}
7063

7164
ROOT_URLCONF = 'backend.urls'
7265

@@ -188,4 +181,16 @@
188181
"SLIDING_TOKEN_REFRESH_SERIALIZER": "rest_framework_simplejwt.serializers.TokenRefreshSlidingSerializer",
189182
}
190183

191-
AUTH_USER_MODEL = 'api.User'
184+
# settings.py
185+
186+
REST_FRAMEWORK = {
187+
'DEFAULT_AUTHENTICATION_CLASSES': (
188+
'rest_framework_simplejwt.authentication.JWTAuthentication',
189+
# Other authentication classes as needed
190+
),
191+
# Other settings
192+
}
193+
194+
195+
AUTH_USER_MODEL = 'api.User'
196+

backend/backend/urls.py

Lines changed: 2 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,7 @@
1-
"""
2-
URL configuration for backend project.
3-
4-
The `urlpatterns` list routes URLs to views. For more information please see:
5-
https://docs.djangoproject.com/en/5.0/topics/http/urls/
6-
Examples:
7-
Function views
8-
1. Add an import: from my_app import views
9-
2. Add a URL to urlpatterns: path('', views.home, name='home')
10-
Class-based views
11-
1. Add an import: from other_app.views import Home
12-
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
13-
Including another URLconf
14-
1. Import the include() function: from django.urls import include, path
15-
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
16-
"""
171
from django.contrib import admin
18-
from django.urls import path
2+
from django.urls import path, include
193

204
urlpatterns = [
215
path('admin/', admin.site.urls),
6+
path('api/', include('api.urls')), # Adjusted to use single quotes consistently
227
]

backend/db.sqlite3

0 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)