(add, done): add email smtp service and auth service done!
This commit is contained in:
@@ -1,3 +1,26 @@
|
||||
from django.contrib import admin
|
||||
from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
|
||||
# Register your models here.
|
||||
from core.apps.accounts.models import User
|
||||
|
||||
|
||||
@admin.register(User)
|
||||
class UserAdmin(DjangoUserAdmin):
|
||||
fieldsets = (
|
||||
(None, {"fields": ("email", "password")}),
|
||||
(_("Personal info"), {"fields": ("full_name", "passport_id", "pnfl")}),
|
||||
(_("Important dates"), {"fields": ("last_login", "date_joined")}),
|
||||
)
|
||||
add_fieldsets = (
|
||||
(
|
||||
None,
|
||||
{
|
||||
"classes": ("wide",),
|
||||
"fields": ("email", "password1", "password2"),
|
||||
},
|
||||
),
|
||||
)
|
||||
list_display = ("email", "full_name", "is_staff")
|
||||
search_fields = ("full_name", "email")
|
||||
ordering = ("email",)
|
||||
@@ -2,21 +2,21 @@ import redis
|
||||
|
||||
r = redis.StrictRedis.from_url('redis://redis:6379')
|
||||
|
||||
def cache_user_credentials(email, password, passport_id, pnlf, time):
|
||||
def cache_user_credentials(email, password, passport_id, pnfl, time):
|
||||
key = f"user_credentials:{email}"
|
||||
|
||||
r.hmset(key, {
|
||||
r.hset(key, mapping={
|
||||
"email": email,
|
||||
"password": password,
|
||||
"passport_id": passport_id,
|
||||
"pnlf": pnlf,
|
||||
"pnfl": pnfl,
|
||||
})
|
||||
|
||||
r.expire(key, time)
|
||||
|
||||
|
||||
def get_user_credentials(email):
|
||||
key = f"user_credentials:{email}"
|
||||
|
||||
data = r.hgetall(key)
|
||||
if not data:
|
||||
return None
|
||||
@@ -25,6 +25,29 @@ def get_user_credentials(email):
|
||||
"email": data.get(b'email').decode() if data.get(b'email') else None,
|
||||
"password": data.get(b'password').decode() if data.get(b'password') else None,
|
||||
"passport_id": data.get(b'passport_id').decode() if data.get(b'passport_id') else None,
|
||||
"pnlf": data.get(b'pnlf').decode() if data.get(b'pnlf') else None,
|
||||
"pnfl": data.get(b'pnfl').decode() if data.get(b'pnfl') else None,
|
||||
}
|
||||
|
||||
|
||||
def cache_user_confirmation_code(code, email, time):
|
||||
key = f"user_confirmation:{email}_{code}"
|
||||
|
||||
r.hset(key, mapping={
|
||||
'email': email,
|
||||
'code': code
|
||||
})
|
||||
|
||||
r.expire(key, time)
|
||||
|
||||
|
||||
def get_user_confirmation_code(email, code):
|
||||
key = f'user_confirmation:{email}_{code}'
|
||||
|
||||
data = r.hgetall(key)
|
||||
if not data:
|
||||
return None
|
||||
|
||||
return {
|
||||
"email": data.get(b'email').decode() if data.get(b'email') else None,
|
||||
"code": data.get(b'code').decode() if data.get(b'code') else None
|
||||
}
|
||||
|
||||
@@ -3,10 +3,10 @@ from django.db import transaction
|
||||
from rest_framework import serializers
|
||||
|
||||
from core.apps.accounts.models import User
|
||||
from core.apps.accounts.cache import get_user_credentials
|
||||
from core.apps.accounts.cache import get_user_credentials, get_user_confirmation_code
|
||||
|
||||
|
||||
class RegisterSerializer(serializers.ModelSerializer):
|
||||
class RegisterSerializer(serializers.Serializer):
|
||||
passport_id = serializers.CharField()
|
||||
pnfl = serializers.CharField()
|
||||
email = serializers.EmailField()
|
||||
@@ -15,6 +15,38 @@ class RegisterSerializer(serializers.ModelSerializer):
|
||||
def validate_email(self, value):
|
||||
if User.objects.filter(email=value).exists():
|
||||
raise serializers.ValidationError("User with this email already exists")
|
||||
if get_user_credentials(value):
|
||||
user_data = get_user_credentials(email=value)
|
||||
if user_data:
|
||||
raise serializers.ValidationError("User with this email already exists")
|
||||
return value
|
||||
return value
|
||||
|
||||
|
||||
class ConfirmUserSerializer(serializers.Serializer):
|
||||
email = serializers.EmailField()
|
||||
code = serializers.IntegerField()
|
||||
|
||||
def validate(self, data):
|
||||
if User.objects.filter(email=data['email']).exists():
|
||||
raise serializers.ValidationError('User with this email already exists')
|
||||
user_data = get_user_credentials(email=data.get('email'))
|
||||
print(user_data)
|
||||
if not user_data:
|
||||
raise serializers.ValidationError("User with this email not found")
|
||||
confirm_data = get_user_confirmation_code(data['email'], data['code'])
|
||||
if not confirm_data:
|
||||
raise serializers.ValidationError("Invalid confirmation code")
|
||||
data['user_data'] = user_data
|
||||
return data
|
||||
|
||||
def create(self, validated_data):
|
||||
with transaction.atomic():
|
||||
user_data = validated_data.get('user_data')
|
||||
user = User.objects.create(
|
||||
email=user_data.get('email'),
|
||||
passport_id=user_data.get('passport_id'),
|
||||
pnfl=user_data.get('pnfl'),
|
||||
)
|
||||
user.set_password(user_data.get('password'))
|
||||
user.save()
|
||||
return user
|
||||
|
||||
15
core/apps/accounts/tasks.py
Normal file
15
core/apps/accounts/tasks.py
Normal file
@@ -0,0 +1,15 @@
|
||||
from celery import shared_task
|
||||
|
||||
from django.core.mail import send_mail
|
||||
from django.conf import settings
|
||||
|
||||
|
||||
@shared_task
|
||||
def send_confirmation_code_to_email(email, code):
|
||||
send_mail(
|
||||
"Avto Cargo uchun tasdiqlash kod.",
|
||||
f"Bu sizning tasdiqlash kodingiz: {code}",
|
||||
settings.EMAIL_HOST_USER,
|
||||
[email],
|
||||
fail_silently=False,
|
||||
)
|
||||
@@ -2,7 +2,10 @@ from django.urls import path, include
|
||||
|
||||
from rest_framework_simplejwt.views import TokenObtainPairView
|
||||
|
||||
from core.apps.accounts import views
|
||||
|
||||
urlpatterns = [
|
||||
path('login/', TokenObtainPairView.as_view()),
|
||||
path('register/', views.RegisterApiView.as_view()),
|
||||
path('confirm_user/', views.ConfirmUserApiView.as_view()),
|
||||
]
|
||||
@@ -1,9 +1,15 @@
|
||||
import random
|
||||
|
||||
from rest_framework import generics, views
|
||||
from rest_framework.response import Response
|
||||
|
||||
from rest_framework_simplejwt.tokens import RefreshToken
|
||||
|
||||
from core.apps.accounts import serializers
|
||||
from core.apps.accounts import models
|
||||
from core.apps.accounts.cache import cache_user_credentials
|
||||
from core.apps.accounts.cache import cache_user_credentials, cache_user_confirmation_code
|
||||
from core.apps.accounts.tasks import send_confirmation_code_to_email
|
||||
|
||||
|
||||
class RegisterApiView(generics.GenericAPIView):
|
||||
serializer_class = serializers.RegisterSerializer
|
||||
@@ -13,11 +19,36 @@ class RegisterApiView(generics.GenericAPIView):
|
||||
serializer = self.serializer_class(data=request.data)
|
||||
if serializer.is_valid(raise_exception=True):
|
||||
data = serializer.validated_data
|
||||
email = data['email']
|
||||
cache_user_credentials(
|
||||
email=data['email'], password=data['password'],
|
||||
passport_id=data['passport_id'], pnlf=data['pnlf'], time=60*5
|
||||
email=email, password=data['password'],
|
||||
passport_id=data['passport_id'], pnfl=data['pnfl'], time=60*5
|
||||
)
|
||||
code = ''.join([str(random.randint(0, 100)%10) for _ in range(5)])
|
||||
cache_user_confirmation_code(
|
||||
email=email, code=code, time=60*5
|
||||
)
|
||||
send_confirmation_code_to_email.delay(email, code)
|
||||
return Response(
|
||||
{'success': True, 'message': "code sent"},
|
||||
status=200
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class ConfirmUserApiView(generics.GenericAPIView):
|
||||
serializer_class = serializers.ConfirmUserSerializer
|
||||
queryset = models.User.objects.all()
|
||||
|
||||
def post(self, request):
|
||||
serializer = self.serializer_class(data=request.data)
|
||||
if serializer.is_valid(raise_exception=True):
|
||||
user = serializer.save()
|
||||
token = RefreshToken.for_user(user)
|
||||
return Response(
|
||||
{'access': str(token.access_token), 'refresh': str(token)},
|
||||
status=200
|
||||
)
|
||||
return Response(
|
||||
{'success': False, 'error_message': serializer.errors},
|
||||
status=400
|
||||
)
|
||||
Reference in New Issue
Block a user