64 lines
2.5 KiB
Python
64 lines
2.5 KiB
Python
from src.application.abstractions import IUnitOfWork
|
|
from src.application.contracts import IHashService, ILogger, ICache
|
|
from src.application.domain.exceptions import ApplicationException
|
|
from src.infrastructure.database.decorators import transactional
|
|
|
|
|
|
class ChangeEmailCompleteCommand:
|
|
def __init__(
|
|
self,
|
|
unit_of_work: IUnitOfWork,
|
|
hash_service: IHashService,
|
|
cache: ICache,
|
|
logger: ILogger,
|
|
):
|
|
self._unit_of_work = unit_of_work
|
|
self._hash_service = hash_service
|
|
self._cache = cache
|
|
self._logger = logger
|
|
|
|
@transactional
|
|
async def __call__(self, *, user_id: str, code: str) -> bool:
|
|
code = (code or '').strip()
|
|
|
|
NEW_USER_PREFIX = 'change_email:new_user:'
|
|
NEW_CODE_PREFIX = 'change_email:new_code:'
|
|
|
|
new_user_key = f'{NEW_USER_PREFIX}{user_id}'
|
|
new_code_key = f'{NEW_CODE_PREFIX}{code}'
|
|
|
|
cached_user_id = await self._cache.get(new_code_key)
|
|
if not cached_user_id:
|
|
self._logger.info(f'Change email complete failed: code not found (user_id={user_id})')
|
|
raise ApplicationException(400, 'Invalid or expired code')
|
|
|
|
if cached_user_id != user_id:
|
|
self._logger.info(f'Change email complete failed: code-user mismatch (user_id={user_id})')
|
|
raise ApplicationException(400, 'Invalid or expired code')
|
|
|
|
raw_value = await self._cache.get(new_user_key)
|
|
if not raw_value:
|
|
self._logger.info(f'Change email complete failed: user key missing (user_id={user_id})')
|
|
raise ApplicationException(400, 'Invalid or expired code')
|
|
|
|
separator_idx = raw_value.index(':')
|
|
code_hash = raw_value[:separator_idx]
|
|
new_email = raw_value[separator_idx + 1:]
|
|
|
|
ok = await self._hash_service.verify(hashed_value=code_hash, plain_value=code)
|
|
if not ok:
|
|
self._logger.info(f'Change email complete failed: code hash mismatch (user_id={user_id})')
|
|
raise ApplicationException(400, 'Invalid or expired code')
|
|
|
|
user = await self._unit_of_work.user_repository.set_email(user_id=user_id, email=new_email)
|
|
await self._cache.set_user(user_id, user)
|
|
|
|
try:
|
|
await self._cache.delete(new_code_key)
|
|
await self._cache.delete(new_user_key)
|
|
except Exception as e:
|
|
self._logger.warning(f'Change email complete cleanup failed (user_id={user_id}): {e}')
|
|
|
|
self._logger.info(f'Email changed for user_id={user_id}')
|
|
return True
|