Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
venv
db.sqlite3
Binary file modified Main/__pycache__/__init__.cpython-312.pyc
Binary file not shown.
Binary file modified Main/__pycache__/settings.cpython-312.pyc
Binary file not shown.
Binary file added Main/__pycache__/urls.cpython-312.pyc
Binary file not shown.
Binary file added Main/__pycache__/wsgi.cpython-312.pyc
Binary file not shown.
45 changes: 44 additions & 1 deletion Main/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,17 @@
# Application definition

INSTALLED_APPS = [
'jazzmin',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'api',
'rest_framework'
'rest_framework',
'rest_framework_simplejwt.token_blacklist',
'corsheaders',

]

Expand All @@ -50,6 +53,7 @@
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',
]

ROOT_URLCONF = 'Main.urls'
Expand Down Expand Up @@ -103,6 +107,7 @@
]



# Internationalization
# https://docs.djangoproject.com/en/5.0/topics/i18n/

Expand All @@ -124,3 +129,41 @@
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
)
}
from datetime import timedelta
SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(minutes=5),
'REFRESH_TOKEN_LIFETIME': timedelta(days=50),
'ROTATE_REFRESH_TOKENS': True,
'BLACKLIST_AFTER_ROTATION': True,
'UPDATE_LAST_LOGIN': False,
'ALGORITHM': 'HS256',
'VERIFYING_KEY': None,
'AUDIENCE': None,
'ISSUER': None,
'JWK_URL': None,
'LEEWAY': 0,
'AUTH_HEADER_TYPES': ('Bearer',),
'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION',
'USER_ID_FIELD': 'id',
'USER_ID_CLAIM': 'user_id',
'USER_AUTHENTICATION_RULE':
'rest_framework_simplejwt.authentication.default_user_authentication_rule',
'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',),
'TOKEN_TYPE_CLAIM': 'token_type',
'TOKEN_USER_CLASS': 'rest_framework_simplejwt.models.TokenUser',
'JTI_CLAIM': 'jti',
'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp',
'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5),
'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1),

}

CORS_ALLOW_ALL_ORIGINS = True

AUTH_USER_MODEL='api.User'
3 changes: 2 additions & 1 deletion Main/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.urls import path,include

urlpatterns = [
path('api/',include('api.urls')),
path('admin/', admin.site.urls),
]
Binary file added api/__pycache__/__init__.cpython-312.pyc
Binary file not shown.
Binary file added api/__pycache__/admin.cpython-312.pyc
Binary file not shown.
Binary file added api/__pycache__/apps.cpython-312.pyc
Binary file not shown.
Binary file added api/__pycache__/models.cpython-312.pyc
Binary file not shown.
Binary file added api/__pycache__/serlizers.cpython-312.pyc
Binary file not shown.
Binary file added api/__pycache__/urls.cpython-312.pyc
Binary file not shown.
Binary file added api/__pycache__/views.cpython-312.pyc
Binary file not shown.
11 changes: 10 additions & 1 deletion api/admin.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
from django.contrib import admin
from .models import User, Profile

# Register your models here.
class UserAdmin(admin.ModelAdmin):
list_display=['username','email']

class ProfileAdmin(admin.ModelAdmin):
list_editable=['verified']
list_display=['user','full_name','bio','image','verified']

admin.site.register(User,UserAdmin)
admin.site.register(Profile,ProfileAdmin)
56 changes: 56 additions & 0 deletions api/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# Generated by Django 5.0.7 on 2024-07-16 17:29

import django.contrib.auth.models
import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]

operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('username', models.CharField(max_length=100)),
('email', models.EmailField(max_length=254, unique=True)),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.permission', verbose_name='user permissions')),
],
options={
'verbose_name': 'user',
'verbose_name_plural': 'users',
'abstract': False,
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
migrations.CreateModel(
name='Profile',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('full_name', models.CharField(max_length=200)),
('bio', models.CharField(max_length=300)),
('image', models.ImageField(default='default.jpg', upload_to='user_images')),
('verified', models.BooleanField(default=False)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
Binary file not shown.
Binary file added api/migrations/__pycache__/__init__.cpython-312.pyc
Binary file not shown.
33 changes: 32 additions & 1 deletion api/models.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,34 @@
from django.db import models

from django.contrib.auth.models import AbstractUser
from django.db.models.signals import post_save
# Create your models here.
class User(AbstractUser):
username=models.CharField(max_length=100)
email=models.EmailField(unique=True)


USERNAME_FIELD='email'
REQUIRED_FIELDS=['username']

def __str__(self):
return self.username

class Profile(models.Model):
user=models.OneToOneField(User, on_delete=models.CASCADE)
full_name=models.CharField(max_length=200)
bio=models.CharField(max_length=300)
image=models.ImageField(default="default.jpg",upload_to="user_images")
verified=models.BooleanField(default=False)

def __str__(self):
return self.full_name

def create_user_profile(sender,instance,created, **kwargs):
if created:
Profile.objects.create(user=instance)

def save_user_profile(sender,instance,**kwargs):
instance.profile.save()

post_save.connect(create_user_profile,sender=User)
post_save.connect(save_user_profile,sender=User)
48 changes: 48 additions & 0 deletions api/serlizers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from rest_framework_simplejwt.tokens import Token
from .models import User, Profile
from django.contrib.auth.password_validation import validate_password
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework import serializers

class UserSerilizers(serializers.ModelSerializer):
class Meta:
model=User
fields=['id','username','email']

class TokenObtainPairSerializer(TokenObtainPairSerializer):
@classmethod
def get_token(cls, user):
token= super().get_token(user)

token['Full_name']=user.profile.full_name
token['username']=user.username
token['email']=user.email
token['bio']=user.profile.bio
token['image']=str(user.profile.image)
token['verified']=user.profile.verified

return token
class RegisterSerlizer(serializers.ModelSerializer):
password=serializers.CharField(write_only=True, required=True, validators=[validate_password])
password2=serializers.CharField(write_only=True, required=True)

class Meta:
model=User
fields=['email','username','password','password2']


def validate(self, attrs):
if attrs['password']!=attrs['password2']:
raise serializers.ValidationError({"password":"password fields does not match"})
return attrs

def create(self,attrs):
user=User.objects.create(
username=attrs['username'],
email=attrs['email'],

)
user.set_password(attrs['password'])
user.save()
return user

10 changes: 10 additions & 0 deletions api/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from rest_framework_simplejwt.views import TokenRefreshView
from django.urls import path

from .views import MyTokenobtainpPairView, Registrationview,dashbord
urlpatterns = [
path('token/',MyTokenobtainpPairView.as_view()),
path('token/refresh',TokenRefreshView.as_view()),
path("register/",Registrationview.as_view()),
path("dashbord/", dashbord)
]
38 changes: 37 additions & 1 deletion api/views.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,39 @@
from django.shortcuts import render

# Create your views here.
from .models import User,Profile
from .serlizers import UserSerilizers,TokenObtainPairSerializer,RegisterSerlizer

from rest_framework.decorators import api_view, permission_classes
from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework import generics,status
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response

class MyTokenobtainpPairView(TokenObtainPairView):
serializer_class=TokenObtainPairSerializer

class Registrationview(generics.CreateAPIView):
queryset=User.objects.all()
permission_classes=(AllowAny,)
serializer_class=RegisterSerlizer


@api_view(['GET','POST'])
@permission_classes([IsAuthenticated])
def dashbord(request):
if request.method=="GET":
response=f"Hey{request.user}, You are seeing the GET response"
return Response(response, status=status.HTTP_200_OK)

elif request.method=="POST":
text=request.POST.get("text")
response=f"Hey {request.user}, your text is {text}"
return Response(response,status=status.HTTP_200_OK)

return Response({}, status=status.HTTP_400_BAD_REQUEST)






Binary file modified requirements.txt
Binary file not shown.