Skip to content
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
wants to merge 3 commits into
base: main
Choose a base branch
from
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
9 changes: 8 additions & 1 deletion .gitignore
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
9 changes: 8 additions & 1 deletion bracket_backend/.gitignore
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/
8 changes: 8 additions & 0 deletions bracket_backend/Accounts/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
*.log
*.pot
*.pyc
__pycache__
db.sqlite3
media


Empty file.
5 changes: 5 additions & 0 deletions bracket_backend/Accounts/admin.py
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.
6 changes: 6 additions & 0 deletions bracket_backend/Accounts/apps.py
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'
43 changes: 43 additions & 0 deletions bracket_backend/Accounts/migrations/0001_initial.py
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.
61 changes: 61 additions & 0 deletions bracket_backend/Accounts/models.py
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',),
Copy link
Collaborator

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'

('','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
29 changes: 29 additions & 0 deletions bracket_backend/Accounts/serializers.py
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):
Copy link
Collaborator

Choose a reason for hiding this comment

The 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


3 changes: 3 additions & 0 deletions bracket_backend/Accounts/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
11 changes: 11 additions & 0 deletions bracket_backend/Accounts/urls.py
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),
]
142 changes: 142 additions & 0 deletions bracket_backend/Accounts/views.py
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







Loading