ajb426 / IS601_HW10

MIT License
0 stars 0 forks source link

Update Profile - validate nickname and email address are not taken #10

Closed ajb426 closed 3 months ago

ajb426 commented 3 months ago

To ensure that username remains unique, additional validation is needed on nickname to make sure a duplicate entry is not created when updating the profile

ajb426 commented 3 months ago

During update requests we check if the email address or nickname are already in the users table, in user_service.py

 @classmethod
    async def create(cls, session: AsyncSession, user_data: Dict[str, str], email_service: EmailService) -> Optional[User]:
        try:
            validated_data = UserCreate(**user_data).model_dump()
            existing_user_by_email = await cls.get_by_email(session, validated_data['email'])
            if existing_user_by_email:
                logger.error("User with given email already exists.")
                raise HTTPException(status_code=422, detail="User with given email already exists.")

            existing_user_by_nickname = await cls.get_by_nickname(session, validated_data['nickname'])
            if existing_user_by_nickname:
                logger.error("User with given nickname already exists.")
                raise HTTPException(status_code=422, detail="User with given nickname already exists.")
...

@classmethod
    async def update(cls, session: AsyncSession, user_id: UUID, update_data: Dict[str, str]) -> Optional[User]:
        try:
            validated_data = UserUpdate(**update_data).dict(exclude_unset=True)

            if 'email' in validated_data:
                existing_user = await cls.get_by_email(session, validated_data['email'])
                if existing_user and existing_user.id != user_id:
                    logger.error("User with given email already exists.")
                    raise HTTPException(status_code=422, detail="User with given email already exists.")

            if 'nickname' in validated_data:
                validate_nickname(validated_data['nickname'])
                existing_user = await cls.get_by_nickname(session, validated_data['nickname'])
                if existing_user and existing_user.id != user_id:
                    logger.error("User with given nickname already exists.")
                    raise HTTPException(status_code=422, detail="User with given nickname already exists.")