acupedia-api/app/features/auth/service.py

411 lines
12 KiB
Python

from __future__ import annotations
import logging
from collections.abc import Callable
from datetime import datetime, timedelta
from uuid import UUID
from sqlalchemy.ext.asyncio import AsyncSession
from starlette.concurrency import run_in_threadpool
from .errors import (
CurrentPasswordIncorrectError,
InvalidCredentialsError,
InvalidOrExpiredOtpError,
UnauthorizedError,
UserAlreadyExistsError,
UserInactiveError,
UserNotFoundError,
)
from .repository import AuthRepository
from .schema import (
AuthTokenResponse,
AuthTokenUserResponse,
ChangePasswordRequest,
ChangePasswordResponse,
ForgotPasswordRequest,
ForgotPasswordResponse,
ProfileUpdateRequest,
ProfileUpdateResponse,
ResetPasswordRequest,
ResetPasswordResponse,
UserIdentityResponse,
UserLoginRequest,
UserRegisterRequest,
)
from .security import (
create_access_token,
decode_access_token,
generate_otp_code,
hash_password,
normalize_email,
normalize_phone_number,
validate_password_strength,
verify_password,
)
logger = logging.getLogger(__name__)
PRACTITIONER_ROLE = "practitioner"
PASSWORD_RESET_OTP_TTL_MINUTES = 15
PasswordResetEmailSender = Callable[[str, str], bool]
class AuthService:
"""
Authentication/identity service.
Deliberately contains no commerce/content access aggregation.
`/auth/me` is identity + roles only.
"""
def __init__(
self,
*,
session: AsyncSession,
repository: AuthRepository,
password_reset_email_sender: PasswordResetEmailSender,
) -> None:
self.session = session
self.repository = repository
self.password_reset_email_sender = password_reset_email_sender
async def register(
self,
request: UserRegisterRequest,
) -> AuthTokenResponse:
email = normalize_email(request.email)
validate_password_strength(request.password)
phone = normalize_phone_number(request.phone_number)
if await self.repository.get_user_by_email(email) is not None:
raise UserAlreadyExistsError(
"An account with this email address already exists. Please log in."
)
if phone and await self.repository.get_user_by_phone(phone) is not None:
raise UserAlreadyExistsError(
"An account with this phone number already exists. Please log in."
)
country = request.country.strip() if request.country else "India"
full_name = (
request.full_name.strip()
if request.full_name
else email.split("@", 1)[0].title()
)
user = await self.repository.create_user(
email=email,
phone_number=phone or None,
display_name=full_name,
country=country,
password_hash=hash_password(request.password),
)
role = await self.repository.get_role_by_name(PRACTITIONER_ROLE)
if role is not None:
await self.repository.assign_role(
user_id=user.id,
role_id=role.id,
)
# Preserve current registration response semantics.
roles = [PRACTITIONER_ROLE]
token = create_access_token({
"sub": str(user.id),
"email": user.email,
"roles": roles,
})
return AuthTokenResponse(
access_token=token,
token_type="bearer",
user=AuthTokenUserResponse(
id=user.id,
email=user.email,
display_name=user.display_name,
phone_number=phone,
country=user.country,
roles=roles,
),
)
async def login(
self,
request: UserLoginRequest,
) -> AuthTokenResponse:
if request.phone_number:
phone = normalize_phone_number(request.phone_number)
user = await self.repository.get_user_by_phone(phone)
if user is None:
raise UserNotFoundError(
"No account found with this phone number. Please sign up first."
)
else:
assert request.email is not None
email = normalize_email(request.email)
user = await self.repository.get_user_by_email(email)
if user is None:
raise UserNotFoundError(
"No account found with this email address. Please sign up first."
)
if not user.is_active:
raise UserInactiveError("Account is deactivated.")
if not verify_password(request.password, user.password_hash):
raise InvalidCredentialsError(
"Incorrect password. Please try again."
)
roles = await self.repository.get_user_roles(user.id)
if not roles:
roles = [PRACTITIONER_ROLE]
token = create_access_token({
"sub": str(user.id),
"email": user.email,
"roles": roles,
})
return AuthTokenResponse(
access_token=token,
token_type="bearer",
user=self._token_user(user=user, roles=roles),
)
async def get_identity(
self,
*,
access_token: str,
) -> UserIdentityResponse:
user_id = self.require_user_id(access_token)
user = await self.repository.get_user_by_id(user_id)
if user is None:
raise UserNotFoundError("User not found.")
roles = await self.repository.get_user_roles(user.id)
if not roles:
roles = [PRACTITIONER_ROLE]
return UserIdentityResponse(
id=user.id,
email=user.email,
display_name=user.display_name,
phone_number=user.phone_number,
country=user.country,
roles=roles,
is_active=user.is_active,
created_at=user.created_at,
)
async def update_profile(
self,
*,
access_token: str,
request: ProfileUpdateRequest,
) -> ProfileUpdateResponse:
user_id = self.require_user_id(access_token)
# Preserve existing behavior: email is accepted but not mutated.
full_name = request.full_name.strip() if request.full_name else None
phone = (
normalize_phone_number(request.phone_number)
if request.phone_number
else None
)
country = request.country.strip() if request.country else None
user = await self.repository.update_profile(
user_id=user_id,
display_name=full_name,
phone_number=phone,
country=country,
)
if user is None:
raise UserNotFoundError("User not found.")
roles = await self.repository.get_user_roles(user.id)
if not roles:
roles = [PRACTITIONER_ROLE]
return ProfileUpdateResponse(
status="success",
message="Profile updated successfully.",
user=self._token_user(user=user, roles=roles),
)
async def change_password(
self,
*,
access_token: str,
request: ChangePasswordRequest,
) -> ChangePasswordResponse:
user_id = self.require_user_id(access_token)
user = await self.repository.get_user_by_id(user_id)
if user is None:
raise UserNotFoundError("User not found.")
if not verify_password(
request.old_password,
user.password_hash,
):
raise CurrentPasswordIncorrectError(
"Current password is incorrect. Please enter your valid current password."
)
validate_password_strength(request.new_password)
await self.repository.update_password_hash(
user_id=user.id,
password_hash=hash_password(request.new_password),
)
return ChangePasswordResponse(
status="success",
message="Password updated successfully in database.",
)
async def forgot_password(
self,
request: ForgotPasswordRequest,
) -> tuple[ForgotPasswordResponse, str | None]:
email = normalize_email(request.email)
user = await self.repository.get_user_by_email(email)
if user is None:
return (
ForgotPasswordResponse(
status="success",
message=(
"If an account exists with this email, "
"a 6-digit verification code has been sent."
),
),
None,
)
await self.repository.invalidate_unused_password_reset_otps(email)
otp_code = generate_otp_code()
expires_at = datetime.utcnow() + timedelta(
minutes=PASSWORD_RESET_OTP_TTL_MINUTES
)
await self.repository.create_password_reset_otp(
email=email,
otp_code=otp_code,
expires_at=expires_at,
)
return (
ForgotPasswordResponse(
status="success",
message=(
"A 6-digit verification code has been sent to your email. "
"Valid for 15 minutes."
),
),
otp_code,
)
async def send_password_reset_email(
self,
*,
email: str,
otp_code: str,
) -> None:
try:
sent = await run_in_threadpool(
self.password_reset_email_sender,
email,
otp_code,
)
except Exception:
logger.warning(
"Failed to send password reset email to %s",
email,
exc_info=True,
)
return
if not sent:
logger.warning(
"Password reset email sender returned false for %s",
email,
)
async def reset_password(
self,
request: ResetPasswordRequest,
) -> ResetPasswordResponse:
email = normalize_email(request.email)
otp_code = request.otp_code.strip()
if not otp_code:
raise InvalidOrExpiredOtpError(
"Invalid or expired verification code. Please request a new code."
)
validate_password_strength(request.new_password)
otp = await self.repository.get_valid_password_reset_otp(
email=email,
otp_code=otp_code,
)
if otp is None:
raise InvalidOrExpiredOtpError(
"Invalid or expired verification code. Please request a new code."
)
updated = await self.repository.update_password_hash_by_email(
email=email,
password_hash=hash_password(request.new_password),
)
if updated == 0:
raise UserNotFoundError("User not found.")
await self.repository.mark_password_reset_otp_used(otp.id)
return ResetPasswordResponse(
status="success",
message=(
"Password reset successfully. "
"You can now log in with your new password."
),
)
@staticmethod
def require_user_id(
access_token: str,
) -> UUID:
if not access_token:
raise UnauthorizedError("Unauthorized.")
claims = decode_access_token(access_token)
try:
return UUID(str(claims["sub"]))
except (KeyError, TypeError, ValueError) as exc:
raise UnauthorizedError("Unauthorized.") from exc
@staticmethod
def _token_user(
*,
user,
roles: list[str],
) -> AuthTokenUserResponse:
return AuthTokenUserResponse(
id=user.id,
email=user.email,
display_name=user.display_name,
phone_number=user.phone_number,
country=user.country,
roles=roles,
)