-
Notifications
You must be signed in to change notification settings - Fork 4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
User Model #1
Open
lodha1503
wants to merge
3
commits into
devlup-labs:main
Choose a base branch
from
lodha1503:venv-setup
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
User Model #1
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,8 @@ | ||
bracket-env | ||
*.pyc | ||
*.py~ | ||
.idea/ | ||
*/.DS_Store | ||
*.sqlite3 | ||
local_settings.py | ||
sftp-config.json | ||
db.sqlite3 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,9 @@ | ||
.env | ||
__pycache__ | ||
__pycache__ | ||
*.log | ||
*.pot | ||
*.pyc | ||
__pycache__ | ||
db.sqlite3 | ||
media | ||
myworld/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
*.log | ||
*.pot | ||
*.pyc | ||
__pycache__ | ||
db.sqlite3 | ||
media | ||
|
||
|
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
from django.contrib import admin | ||
from .models import User | ||
|
||
admin.site.register(User) | ||
# Register your models here. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
from django.apps import AppConfig | ||
|
||
|
||
class AccountsConfig(AppConfig): | ||
default_auto_field = 'django.db.models.BigAutoField' | ||
name = 'Accounts' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
# Generated by Django 4.2 on 2023-04-06 16:50 | ||
|
||
import django.core.validators | ||
from django.db import migrations, models | ||
import django.utils.timezone | ||
|
||
|
||
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')), | ||
('email', models.CharField(max_length=80, unique=True)), | ||
('username', models.CharField(max_length=45)), | ||
('bio', models.CharField(blank=True, max_length=200, null=True)), | ||
('age', models.IntegerField(db_index=True, null=True, validators=[django.core.validators.MinValueValidator(18), django.core.validators.MaxValueValidator(130)])), | ||
('sex', models.CharField(choices=[('F', 'Female'), ('M', 'Male')], db_index=True, max_length=1, null=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, | ||
}, | ||
), | ||
] |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
from django.db import models | ||
|
||
|
||
from django.contrib.auth.base_user import BaseUserManager | ||
from django.contrib.auth.models import AbstractUser | ||
from django.db import models | ||
from django.core.validators import MinValueValidator, MaxValueValidator | ||
|
||
# Create your models here. | ||
SEX_CHOICES = ( | ||
('F', 'Female',), | ||
('M', 'Male',), | ||
('','Prefer Not To Say') | ||
) | ||
|
||
class CustomUserManager(BaseUserManager): | ||
def create_user(self, email, password, **extra_fields): | ||
email = self.normalize_email(email) | ||
user = self.model(email=email, **extra_fields) | ||
user.set_password(password) | ||
user.save() | ||
return user | ||
|
||
def create_superuser(self, email, password, **extra_fields): | ||
extra_fields.setdefault("is_staff", True) | ||
extra_fields.setdefault("is_superuser", True) | ||
|
||
if extra_fields.get("is_staff") is not True: | ||
raise ValueError("Superuser has to have is_staff being True") | ||
|
||
if extra_fields.get("is_superuser") is not True: | ||
raise ValueError("Superuser has to have is_superuser being True") | ||
|
||
return self.create_user(email=email, password=password, **extra_fields) | ||
|
||
|
||
|
||
|
||
|
||
class User(AbstractUser): | ||
|
||
email = models.CharField(max_length=80, unique=True) | ||
username = models.CharField(max_length=45) | ||
bio=models.CharField(max_length=1024,null=True,blank=True) | ||
age = models.IntegerField(validators=[MinValueValidator(18),MaxValueValidator(130)],db_index=True, null=True) | ||
sex = models.CharField(max_length=1, choices=SEX_CHOICES, db_index=True ,null=True) | ||
|
||
|
||
def __str__(self): | ||
return self.username | ||
|
||
|
||
|
||
objects = CustomUserManager() | ||
USERNAME_FIELD = "email" | ||
|
||
|
||
REQUIRED_FIELDS = ["username",'age','sex',] | ||
|
||
def __str__(self): | ||
return self.username |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
from rest_framework import serializers | ||
from .models import User, SEX_CHOICES | ||
from rest_framework.validators import UniqueValidator | ||
from django.contrib.auth import password_validation | ||
|
||
class UserListSerializer(serializers.ModelSerializer): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. UserSerializer should be made, the purpose of this serializer is unclear |
||
email = serializers.EmailField(validators=[UniqueValidator(queryset=User.objects.all())]) | ||
username = serializers.CharField(validators=[UniqueValidator(queryset=User.objects.all())]) | ||
class Meta: | ||
model = User | ||
fields = ('first_name','last_name','email','password','username','sex','age','bio') | ||
extra_kwargs={ | ||
'password':{'write_only':True} | ||
} | ||
|
||
#Intermediate function between serializer and views.Helps in hashing of password | ||
def create(self,validated_data): | ||
password=validated_data.pop('password','None') | ||
instance=self.Meta.model(**validated_data) | ||
if password is not None: | ||
instance.set_password(password) | ||
instance.save() | ||
return instance | ||
|
||
def validate_password(self, value): | ||
password_validation.validate_password(value) | ||
return value | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
from django.test import TestCase | ||
|
||
# Create your tests here. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
from django.contrib import admin | ||
from django.urls import path | ||
from . import views | ||
|
||
|
||
urlpatterns = [ | ||
path('signup/', views.SignUp), | ||
path("login/", views.Login), | ||
path("profile/", views.UserApi), | ||
path('logout/', views.LogOut), | ||
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,142 @@ | ||
from django.db import IntegrityError | ||
from django.forms import ValidationError | ||
from rest_framework.decorators import api_view, permission_classes | ||
from rest_framework.permissions import IsAuthenticated | ||
from rest_framework.response import Response | ||
from .serializers import UserListSerializer | ||
from .models import User | ||
from django.contrib.auth import authenticate, login | ||
from rest_framework.authtoken.models import Token | ||
from rest_framework.permissions import AllowAny | ||
from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST | ||
import io | ||
from rest_framework.parsers import JSONParser | ||
import jwt,datetime | ||
|
||
|
||
|
||
# Requires Deserialization ------ JSON Data — Parse data →Python native data — De-serialization →Complex Data | ||
@api_view(['POST']) | ||
@permission_classes((AllowAny,)) | ||
def SignUp(request): # Create a new user | ||
|
||
try: | ||
data = {} | ||
json_data=request.body | ||
stream= io.BytesIO(json_data) | ||
pythondata= JSONParser().parse(stream) # It parses the incoming request JSON content into python content type dict. It is used if "Content-Type" is set to "application/json". | ||
serializer = UserListSerializer(data=pythondata) # Converts python data to complex data type :- De-serialization | ||
if serializer.is_valid(): | ||
if(User.objects.filter(username=serializer.validated_data['username']).exists() ): | ||
data['status'] = 'failed' | ||
data['message'] = 'Username already exists' | ||
return Response(data, status=HTTP_400_BAD_REQUEST, headers={'Access-Control-Allow-Origin': '*'}) | ||
elif(User.objects.filter(email=serializer.validated_data['email']).exists() ): | ||
data['status'] = 'failed' | ||
data['message'] = 'Email already exists' | ||
return Response(data, status=HTTP_400_BAD_REQUEST, headers={'Access-Control-Allow-Origin': '*'}) | ||
elif(User.objects.filter(email=serializer.validated_data['email']).exists() and User.objects.filter(email=serializer.validated_data['email']).exists() ): | ||
data['status'] = 'failed' | ||
data['message'] = 'Both Username and Email already exists' | ||
return Response(data, status=HTTP_400_BAD_REQUEST, headers={'Access-Control-Allow-Origin': '*'}) | ||
|
||
account = serializer.save() | ||
account.save() | ||
token = Token.objects.get_or_create(user=account)[0].key | ||
data["message"] = "User registered successfully" | ||
data["email"] = account.email | ||
data["username"] = account.username | ||
data["sex"]=account.sex | ||
data["age"]=account.age | ||
data["bio"]=account.bio | ||
data["token"] = token | ||
# Save the user and return the above info as response | ||
return Response(data, status=HTTP_200_OK, headers={'Access-Control-Allow-Origin': '*'}) | ||
else: | ||
data = serializer.errors | ||
return Response(data, status=HTTP_400_BAD_REQUEST, headers={'Access-Control-Allow-Origin': '*'}) | ||
except IntegrityError as e: | ||
account=User.objects.get(username='') | ||
account.delete() | ||
raise ValidationError({"400": f'{str(e)}'}) | ||
|
||
|
||
@api_view(["GET"]) | ||
@permission_classes((AllowAny,)) | ||
def Login(request): | ||
|
||
email = request.headers.get('Email') | ||
password = request.headers.get('Password') | ||
try: | ||
Account = User.objects.get(email=email) # get the account with the given email | ||
except BaseException as e: | ||
return Response({"message": "No Such Email Registered!! "}, status=HTTP_400_BAD_REQUEST, headers={'Access-Control-Allow-Origin': '*'}) | ||
|
||
if not Account.check_password(password): # We cannot directly compare passwords so we have to use django inbuilt method | ||
return Response({"message": "Incorrect Login Credentials"}, status=HTTP_400_BAD_REQUEST, headers={'Access-Control-Allow-Origin': '*'}) | ||
|
||
# If the credentials are correct, return the token | ||
if Account: | ||
|
||
payload={ | ||
'email': Account.email, | ||
'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60), | ||
'iat': datetime.datetime.utcnow() # Date on which token is created | ||
} | ||
|
||
token= jwt.encode(payload,'secret',algorithm='HS256') | ||
|
||
# Now we have to send token as cookies | ||
response=Response() | ||
response.set_cookie(key='jwt',value=token,httponly=True) # Use of httponly=True is that we want frontend to use only cookies not token , token is only for backend | ||
|
||
response.data = {"jwt": token} | ||
|
||
# response.content_type='application/json' | ||
# response.status=HTTP_200_OK, headers={'Access-Control-Allow-Origin': '*'} | ||
|
||
return response | ||
|
||
else: | ||
return Response({"message": "Incorrect Login credentials"}, status=HTTP_400_BAD_REQUEST, headers={'Access-Control-Allow-Origin': '*'}) | ||
|
||
|
||
|
||
@api_view(["GET"]) | ||
# @permission_classes([IsAuthenticated]) | ||
def UserApi(request): | ||
token=request.COOKIES.get("jwt") | ||
|
||
if not token: | ||
return Response({"message": "Token Invalid"}, status=HTTP_400_BAD_REQUEST, headers={'Access-Control-Allow-Origin': '*'}) | ||
|
||
try: | ||
payload=jwt.decode(token,'secret',algorithms=['HS256']) | ||
except: | ||
return Response({"message": "User Not Authenticated"}, status=HTTP_400_BAD_REQUEST, headers={'Access-Control-Allow-Origin': '*'}) | ||
|
||
Account=User.objects.filter(email=[payload['email']]).first() | ||
serializer=UserListSerializer(Account) | ||
return Response(serializer.data) | ||
|
||
|
||
|
||
|
||
|
||
|
||
@api_view(["POST"]) | ||
# @permission_classes([IsAuthenticated]) | ||
def LogOut(request): | ||
response=Response() | ||
response.delete_cookie("jwt") | ||
response.data={ | ||
"message":"Logged Out" | ||
} | ||
return response | ||
|
||
|
||
|
||
|
||
|
||
|
||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add 'Prefer not to Say'