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

502 lines
15 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 app.db.models import AppUser
from .errors import (
CurrentPasswordIncorrectError,
InvalidCredentialsError,
InvalidOrExpiredOtpError,
SamePasswordError,
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 (
build_phone_lookup_variants,
create_access_token,
decode_access_token,
extract_phone_digits,
generate_otp_code,
hash_password,
matches_login_phone,
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,
),
)
@staticmethod
def _verify_active_user_credentials(user: AppUser, password: str) -> AppUser:
if not user.is_active:
raise UserInactiveError("Account is deactivated.")
if not verify_password(password, user.password_hash):
raise InvalidCredentialsError("Incorrect password. Please try again.")
return user
async def _authenticate_phone_login(
self,
phone_number: str,
password: str,
) -> AppUser:
exact_values, suffix_digits = build_phone_lookup_variants(phone_number)
if not exact_values:
raise UserNotFoundError(
"No account found with this phone number. Please sign up first."
)
raw_candidates = await self.repository.find_users_by_phone_candidates(
exact_values=exact_values,
suffix_digits=suffix_digits,
)
matched = [
candidate
for candidate in raw_candidates
if matches_login_phone(candidate.phone_number, phone_number)
]
if not matched:
raise UserNotFoundError(
"No account found with this phone number. Please sign up first."
)
login_digits = extract_phone_digits(phone_number)
exact_matched = [
candidate
for candidate in matched
if extract_phone_digits(candidate.phone_number) == login_digits
]
candidates = exact_matched or matched
if len(candidates) == 1:
return self._verify_active_user_credentials(candidates[0], password)
active_candidates = [candidate for candidate in candidates if candidate.is_active]
if not active_candidates:
raise UserInactiveError("Account is deactivated.")
verified_users = [
candidate
for candidate in active_candidates
if verify_password(password, candidate.password_hash)
]
if not verified_users:
raise InvalidCredentialsError("Incorrect password. Please try again.")
if len(verified_users) > 1:
raise InvalidCredentialsError(
"Multiple accounts share this phone number. Please log in with your email address."
)
return verified_users[0]
async def login(
self,
request: UserLoginRequest,
) -> AuthTokenResponse:
if request.phone_number:
user = await self._authenticate_phone_login(
request.phone_number,
request.password,
)
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."
)
user = self._verify_active_user_credentials(user, request.password)
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
if phone:
existing_user = await self.repository.get_user_by_phone(phone)
if existing_user is not None and str(existing_user.id) != str(user_id):
raise UserAlreadyExistsError(
"An account with this phone number already exists."
)
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.")
# Keep default user billing profile in sync with updated contact info
from app.db.models import UserBillingProfile
from sqlalchemy import update
bp_values: dict[str, object] = {}
if full_name:
bp_values["billing_name"] = full_name
if phone:
bp_values["billing_phone"] = phone
if country:
bp_values["country"] = country
if bp_values:
await self.session.execute(
update(UserBillingProfile)
.where(UserBillingProfile.user_id == user.id, UserBillingProfile.is_default.is_(True))
.values(**bp_values)
)
await self.session.flush()
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."
)
if (
request.old_password == request.new_password
or verify_password(request.new_password, user.password_hash)
):
raise SamePasswordError(
"New password cannot be the same as 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,
)