Skip to content

Commit e96adb2

Browse files
committed
refactor
1 parent 9012091 commit e96adb2

File tree

8 files changed

+63
-55
lines changed

8 files changed

+63
-55
lines changed

API/Apps/Auth/api/views.py

+16-45
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,11 @@
1-
import os
21
import threading
3-
4-
from django.http import HttpResponseRedirect
5-
from pytz import timezone
6-
7-
from Apps.Auth.serializers import RegisterSerializer, ChangePasswordSerializer, RegisterWith42Serializer
2+
from Apps.Auth.serializers import RegisterSerializer, ChangePasswordSerializer
83
from rest_framework.exceptions import AuthenticationFailed
94
from rest_framework.decorators import api_view, permission_classes
105
from rest_framework.permissions import *
6+
from ..auth_tools import Authenticator, TokenGenerator
117
from ..utils import *
12-
from rest_framework_simplejwt.tokens import RefreshToken
13-
from .permissions import IsEmailVerified
14-
from ...Profile.api.Serializers import UserSerializer
15-
from ...Profile.api.api_42 import api_42
8+
from ...Profile.api.api_42 import connect_api_42
169

1710

1811
@api_view(['POST'])
@@ -40,39 +33,18 @@ def send_email_for_verification(request):
4033
@api_view(['POST'])
4134
@permission_classes([AllowAny])
4235
def email_verification_and_login(request):
43-
try:
44-
username = request.data['username']
45-
verification_code = request.data['verification_code']
46-
db_verification_code = VerificationCode.objects.get(code=verification_code, username=username)
47-
user = User.objects.get(username=username)
48-
except VerificationCode.DoesNotExist:
49-
return Response(data={'message': 'Invalid verification code!'}, status=400)
50-
except User.DoesNotExist:
51-
return Response(data={'message': 'User not found!'}, status=400)
52-
if verification_code != db_verification_code.code:
53-
return Response(data={'message': 'Incorrect verification code!'}, status=400)
54-
55-
expiration_time = timedelta(minutes=15)
56-
if (datetime.now().astimezone(timezone('UTC')) - db_verification_code.expired_date) > expiration_time:
57-
db_verification_code.delete()
58-
return Response(data={'message': 'Verification code expired!'}, status=400)
59-
db_verification_code.delete()
60-
61-
profile = user.profile
62-
profile.is_verified = True
63-
profile.save()
64-
65-
tokens = RefreshToken.for_user(user)
66-
67-
response = Response()
68-
response.data = {
69-
'tokens': {'access': str(tokens.access_token), 'refresh': str(tokens)},
70-
'user_id': user.pk,
71-
'username': user.username
72-
}
73-
74-
response.status_code = 200
75-
return response
36+
username = request.data.get('username')
37+
verification_code = request.data.get('verification_code')
38+
39+
if not username or not verification_code:
40+
return Response(data={'message': 'Username and verification code are required!'}, status=400)
41+
42+
user, error_response = Authenticator.authenticate_user(username, verification_code)
43+
if error_response:
44+
return error_response
45+
46+
response_data = TokenGenerator.generate_tokens(user)
47+
return Response(data=response_data, status=200)
7648

7749

7850
@api_view(['POST'])
@@ -105,5 +77,4 @@ def direct_42_login_page(request):
10577

10678
@api_view(['POST'])
10779
def login_with_42(request, code):
108-
response = api_42(code)
109-
return response
80+
return connect_api_42(code)

API/Apps/Auth/auth_tools.py

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
from datetime import timedelta, datetime
2+
from django.utils import timezone
3+
from rest_framework.response import Response
4+
from .models import VerificationCode
5+
from rest_framework_simplejwt.tokens import RefreshToken
6+
7+
8+
class Authenticator:
9+
@staticmethod
10+
def authenticate_user(username, verification_code):
11+
try:
12+
db_verification_code = VerificationCode.objects.get(code=verification_code, username=username)
13+
except VerificationCode.DoesNotExist:
14+
return None, Response(data={'message': 'Invalid verification code!'}, status=400)
15+
16+
if verification_code != db_verification_code.code:
17+
return None, Response(data={'message': 'Incorrect verification code!'}, status=400)
18+
19+
if (datetime.now().astimezone(timezone('UTC')) - db_verification_code.expired_date) > timedelta(minutes=15):
20+
db_verification_code.delete()
21+
return None, Response(data={'message': 'Verification code expired!'}, status=400)
22+
23+
db_verification_code.delete()
24+
25+
user = db_verification_code.user
26+
user.profile.is_verified = True
27+
user.profile.save()
28+
29+
return user, None
30+
31+
32+
class TokenGenerator:
33+
@staticmethod
34+
def generate_tokens(user):
35+
tokens = RefreshToken.for_user(user)
36+
return {
37+
'tokens': {'access': str(tokens.access_token), 'refresh': str(tokens)},
38+
'user_id': user.pk,
39+
'username': user.username
40+
}

API/Apps/Auth/models.py

-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
from time import timezone
2-
32
from django.db import models
43

54

API/Apps/Auth/serializers.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import uuid
2+
13
from rest_framework import serializers
24
from django.contrib.auth.models import User
35
from rest_framework.validators import UniqueValidator
@@ -88,14 +90,14 @@ class RegisterWith42Serializer(serializers.Serializer):
8890

8991
class Meta:
9092
model = User
91-
fields = ('username', 'email',)
93+
fields = ('username', 'email')
9294

9395
def create(self, validated_data):
94-
print(validated_data)
9596
user = User.objects.create(
9697
username=validated_data['username'],
9798
email=validated_data['email'],
9899
)
100+
user.set_password(str(uuid.uuid1()))
99101

100102
profile = Profile.objects.create(
101103
user=user,

API/Apps/Chat/api/views.py

-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
# chat/views.py
2-
from django.contrib.auth.models import User
32
from django.db.models import Q
43
from rest_framework.decorators import api_view, permission_classes
54
from rest_framework.pagination import PageNumberPagination

API/Apps/Chat/consumers.py

-3
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,7 @@
22

33
from asgiref.sync import async_to_sync
44
from channels.generic.websocket import WebsocketConsumer
5-
from django.contrib.auth.models import User
6-
from rest_framework_simplejwt.backends import TokenBackend
75
from Apps.Chat.models import Message
8-
from urllib.parse import parse_qsl
96

107
from Apps.Profile.models import Profile
118

API/Apps/Profile/api/api_42.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from Apps.Profile.api.Serializers import UserSerializer
1010

1111

12-
def api_42(code):
12+
def connect_api_42(code):
1313
response = requests.post(f"{os.getenv("42_API_URL")}/oauth/token", data={
1414
'grant_type': 'authorization_code',
1515
'code': code,

API/static/styles/verification.css

+2-2
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,10 @@ input::-webkit-outer-spin-button {
4646
border-radius: 20px!important;
4747
background: linear-gradient(rgba(0, 0, 0, 0), rgba(0, 0, 0, 0.1));
4848
transition-duration: 0.5s;
49-
color: white!important;
49+
color: white;
5050
}
5151

5252
button:hover {
5353
background-color: white;
54-
color: black;
54+
color: black !important;
5555
}

0 commit comments

Comments
 (0)