Skip to content

Commit

Permalink
fix verify otp code after create user
Browse files Browse the repository at this point in the history
  • Loading branch information
flavien-hugs committed Sep 15, 2024
1 parent 4072cf7 commit 9bddfd6
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 14 deletions.
2 changes: 1 addition & 1 deletion src/models/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@


class User(CreateUser, DatetimeTimestamp, Document):
is_active: Optional[StrictBool] = True
is_active: Optional[StrictBool] = False
is_primary: Optional[StrictBool] = False

class Settings:
Expand Down
23 changes: 13 additions & 10 deletions src/services/auth.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from datetime import datetime, timedelta, timezone, UTC
from datetime import datetime, timedelta, timezone
from typing import Optional

from beanie import PydanticObjectId
Expand All @@ -12,7 +12,7 @@
from src.config import email_settings, settings, sms_config
from src.middleware.auth import CustomAccessBearer
from src.models import User
from src.schemas import ChangePassword, LoginUser, PhonenumberModel, UserBaseSchema, VerifyOTP, RequestChangePassword
from src.schemas import ChangePassword, LoginUser, PhonenumberModel, RequestChangePassword, UserBaseSchema, VerifyOTP
from src.shared import blacklist_token, mail_service, otp_service, sms_service
from src.shared.error_codes import AuthErrorCode, UserErrorCode
from src.shared.utils import password_hash, verify_password
Expand Down Expand Up @@ -272,7 +272,7 @@ async def send_otp(user: User, background: BackgroundTasks):

new_attributes = user.attributes.copy() if user.attributes else {}
new_attributes["otp_secret"] = otp_secret
new_attributes["otp_created_at"] = datetime.now(tz=UTC)
new_attributes["otp_created_at"] = datetime.now(timezone.utc).timestamp()

template = template_env.get_template(name="sms_send_otp.txt")
message = template.render(otp_code=otp_code, service_name=sms_config.SMS_SENDER)
Expand Down Expand Up @@ -316,13 +316,15 @@ async def verify_otp(payload: VerifyOTP):
status_code=status.HTTP_400_BAD_REQUEST,
)

otp_created_at = user.attributes.get("otp_created_at")
if otp_created_at and datetime.now(tz=UTC) - otp_created_at > timedelta(minutes=5):
raise CustomHTTException(
code_error=AuthErrorCode.AUTH_OTP_EXPIRED,
message_error="OTP has expired. Please request a new one.",
status_code=status.HTTP_400_BAD_REQUEST,
)
if otp_created_at := user.attributes.get("otp_created_at"):
current_timestamp = datetime.now(timezone.utc).timestamp()
time_elapsed = current_timestamp - otp_created_at
if time_elapsed > timedelta(minutes=5).total_seconds():
raise CustomHTTException(
code_error=AuthErrorCode.AUTH_OTP_EXPIRED,
message_error="OTP has expired. Please request a new one.",
status_code=status.HTTP_400_BAD_REQUEST,
)

if not otp_service.generate_otp_instance(user.attributes["otp_secret"]).verify(payload.otp_code):
raise CustomHTTException(
Expand All @@ -331,6 +333,7 @@ async def verify_otp(payload: VerifyOTP):
status_code=status.HTTP_400_BAD_REQUEST,
)

await user.set({"is_active": True})
role = await get_one_role(role_id=PydanticObjectId(user.role))
user_data = user.model_dump(by_alias=True, exclude={"password", "attributes", "is_primary"})

Expand Down
4 changes: 2 additions & 2 deletions src/services/users.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ async def create_first_user(user_data: CreateUser) -> User:
)
await check_if_email_exist(email=user_data.email.lower())
user_dict = user_data.model_copy(update={"role": role.id, "password": password_hash(user_data.password)})
new_user = await User(**user_dict.model_dump()).create()
new_user = await User(is_active=True, **user_dict.model_dump()).create()
return new_user


Expand All @@ -71,7 +71,7 @@ async def create_admin_user():
return
else:
password = os.getenv("DEFAULT_ADMIN_PASSWORD")
user = User(**paylaod, role=role.id, is_primary=True)
user = User(is_active=True, role=role.id, is_primary=True, **paylaod)
user.password = password_hash(password)
await user.create()
logger.info("--> Create first user successfully !")
Expand Down
2 changes: 1 addition & 1 deletion src/templates/sms_send_otp.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
Bonjour, utilsez ce code OTP: {{ otp_code }} pour valider votre compte {{ service_name }}.
Bonjour, utilsez ce code OTP: {{ otp_code }} pour vous connecter à votre compte {{ service_name }}.

0 comments on commit 9bddfd6

Please sign in to comment.