def test_update(orm_user_repository): orm_user_repository.update( user=User( id=UserId(value="heumsi"), name=UserName(value="heumsi jeon"), description="Hi, I'm heumsi jeon!", password="******", image_url="", ) ) actual = orm_user_repository.find_by_user_id(user_id=UserId(value="heumsi")) expected = User( id=UserId(value="heumsi"), name=UserName(value="heumsi jeon"), description="Hi, I'm heumsi jeon!", password="******", image_url="", ) assert actual == expected with pytest.raises(ResourceNotFoundError): orm_user_repository.update( user=User( id=UserId(value="not exist user"), name=UserName(value="heumsi jeon"), description="Hi, I'm heumsi jeon!", password="******", image_url="", ) )
def setup(database): with database.session() as session: session.query(UserOrm).delete() session.add_all( [ UserOrm.from_user( User( id=UserId(value="heumsi"), name=UserName(value="heumsi"), description="hi, I am heumsi", password="******", image_url="", ) ), UserOrm.from_user( User( id=UserId(value="joon"), name=UserName(value="joon"), description="hello, I am joon", password="******", image_url="", ) ), ] ) session.commit()
async def _(): user = User( id=1, email="*****@*****.**", name="Name", is_staff=False, is_active=True, date_joined=datetime.utcnow(), ) repository = FakeUsersRepository(users=[user]) with patch( "users.auth.entities.get_jwt_metadata", return_value={ "exp": datetime(1980, 1, 1), "iat": datetime(1980, 1, 1) }, ): jwt_token = user.generate_token() request = MagicMock() request.headers = {"Authorization": f"Bearer {jwt_token}"} with raises(AuthenticationError): await JWTAuthBackend(repository).authenticate(request)
async def _(): user = User( id=10, email="*****@*****.**", date_joined=datetime.now(timezone.utc), password="******", is_active=True, jwt_auth_id=1, ) with time_machine.travel("2021-10-10 15:00:00Z", tick=False): token = jwt.encode( { "jti": user.get_reset_password_jwt_id(), "user_id": 10, "exp": datetime.now(timezone.utc) + timedelta(minutes=30), "iat": datetime.now(timezone.utc), "iss": "users", "aud": "users/not-reset-password", }, str(SECRET_KEY), ) with raises(ResetPasswordTokenInvalidError): await reset_password( ResetPasswordInput(token=token, new_password="******"), repository=FakeUsersRepository([user]), )
async def _(): user = User( id=10, email="*****@*****.**", date_joined=datetime.now(timezone.utc), is_active=False, ) with raises(UserIsNotActiveError): await reset_password( ResetPasswordInput(token=user.create_reset_password_token(), new_password="******"), repository=FakeUsersRepository([user]), )
async def social_login(input: SocialLoginInput, *, users_repository: AbstractUsersRepository) -> User: logger.info( "Request social login with social_id=%s and google provider", input.social_account.social_id, ) user = await users_repository.get_by_email(input.email) if not user: logger.info("Social login not found, creating a new user") user = await users_repository.create_user( User( email=input.email, password=UNUSABLE_PASSWORD, date_joined=datetime.now(timezone.utc), fullname=input.social_account.fullname, name=input.social_account.first_name, )) user = dataclasses.replace(user, password=None) await users_repository.commit() logger.info("Created user %s for social login", user.id) else: logger.info("Found user %s for social login", user.id) return user
async def _(): user = User( id=1, username="******", password="******", email="*****@*****.**", fullname="Marco Acierno", name="Marco", gender="", date_birth=None, open_to_newsletter=False, open_to_recruiting=False, country="", date_joined=datetime(2020, 1, 1), is_staff=False, is_superuser=False, is_active=True, ) repository = FakeUsersRepository(users=[user]) with raises(UserIsNotAdminError): await login( LoginInputModel(email="*****@*****.**", password="******"), reject_non_admins=True, users_repository=repository, )
async def _(): repository = FakeUsersRepository( users=[ User( id=10, email="*****@*****.**", date_joined=datetime.now(), password="******", fullname="Hello World", name="Hello", ) ] ) user = await social_login( SocialLoginInput( email="*****@*****.**", social_account=SocialAccount( social_id="1", fullname="Test Account", first_name="Test", last_name="Account", ), ), users_repository=repository, ) assert user assert user.has_usable_password() assert user.check_password("my_password") assert user.id == 10 assert user.fullname == "Hello World" assert user.name == "Hello" assert user.email == "*****@*****.**"
async def _(): user = User( id=1, username="******", password="******", email="*****@*****.**", fullname="Marco Acierno", name="Marco", gender="", date_birth=None, open_to_newsletter=False, open_to_recruiting=False, country="", date_joined=datetime(2020, 1, 1), is_staff=False, is_superuser=False, is_active=True, ) repository = FakeUsersRepository(users=[user]) with time_machine.travel("2020-10-10 10:10:00Z", tick=False): logged_user = await login( LoginInputModel(email="*****@*****.**", password="******"), users_repository=repository, ) assert logged_user.id == user.id assert logged_user.last_login == datetime( 2020, 10, 10, 10, 10, 00, tzinfo=timezone.utc )
async def _(): user = User( id=10, email="*****@*****.**", date_joined=datetime.now(timezone.utc), password="******", is_active=False, jwt_auth_id=1, name="Old name", fullname="Old fullname", gender="f", open_to_recruiting=True, open_to_newsletter=True, date_birth=date(1900, 1, 1), country="US", ) with raises(UserIsNotActiveError): await update_profile( user.id, UpdateProfileInput( name="New name", full_name="Full name", gender="m", open_to_recruiting=False, open_to_newsletter=False, date_birth=date(2020, 10, 1), country="IT", ), users_repository=FakeUsersRepository([user]), )
async def _(): user = User( id=1, username="******", password="******", email="*****@*****.**", fullname="Marco Acierno", name="Marco", gender="", date_birth=None, open_to_newsletter=False, open_to_recruiting=False, country="", date_joined=datetime(2020, 1, 1), is_staff=False, is_superuser=False, is_active=True, ) repository = FakeUsersRepository(users=[user]) logged_user = await login( LoginInputModel(email="*****@*****.**", password="******"), users_repository=repository, ) assert logged_user.id == user.id
def to_user(self) -> User: return User( id=UserId(value=self.id), name=UserName(value=self.name), description=self.description, password=self.password, image_url=self.image_url, )
def user(exemplary_user_id: int, exemplary_user_email: str) -> User: return User(id=exemplary_user_id, email=exemplary_user_email, name="John Doe", user_type=1, is_staff=False, is_active=True, is_confirmed=True)
async def _(): user = User( id=10, email="*****@*****.**", date_joined=datetime.now(timezone.utc), password="******", is_active=True, jwt_auth_id=1, ) token = user.create_reset_password_token() user.jwt_auth_id = 2 with raises(ResetPasswordTokenInvalidError): await reset_password( ResetPasswordInput(token=token, new_password="******"), repository=FakeUsersRepository([user]), )
async def _(): repository = FakeUsersRepository( users=[User(email="*****@*****.**", date_joined=datetime.utcnow())]) with raises(EmailAlreadyUsedError): await register( RegisterInputModel(email="*****@*****.**", password="******"), users_repository=repository, )
async def _(): user = User( id=1, email="*****@*****.**", name="Name", is_staff=False, is_active=False, date_joined=datetime.utcnow(), ) repository = FakeUsersRepository(users=[user]) jwt_token = user.generate_token() request = MagicMock() request.headers = {"Authorization": f"Bearer {jwt_token}"} with raises(AuthenticationError): await JWTAuthBackend(repository).authenticate(request)
def test_find_all(orm_user_repository): actual = orm_user_repository.find_all() expected = [ User( id=UserId(value="heumsi"), name=UserName(value="heumsi"), description="hi, I am heumsi", password="******", image_url="", ), User( id=UserId(value="joon"), name=UserName(value="joon"), description="hello, I am joon", password="******", image_url="", ), ] assert actual == expected
async def _(): user = User( id=10, email="*****@*****.**", date_joined=datetime.now(timezone.utc), password="******", is_active=True, jwt_auth_id=1, ) with time_machine.travel("2020-10-10 10:10:10Z", tick=False): token = user.create_reset_password_token() with time_machine.travel( "2020-10-10 15:10:10Z", tick=False), raises(ResetPasswordTokenExpiredError): await reset_password( ResetPasswordInput(token=token, new_password="******"), repository=FakeUsersRepository([user]), )
def test_add(orm_user_repository): orm_user_repository.add(user=User(id=UserId(value="siheum"), name=UserName(value="siheum"), password="******")) actual = orm_user_repository.find_by_user_id(user_id=UserId(value="siheum")) expected = User( id=UserId(value="siheum"), name=UserName(value="siheum"), description="", password="******", image_url="", ) assert actual == expected with pytest.raises(ResourceAlreadyExistError): orm_user_repository.add( user=User( id=UserId(value="siheum"), name=UserName(value="siheum"), password="******", ) )
async def _(): user = User( id=50, email="*****@*****.**", date_joined=datetime.now(timezone.utc), jwt_auth_id=1, ) with time_machine.travel("2020-10-10 10:10:10Z", tick=False): token = user.create_reset_password_token() decoded_token = jwt.decode( token, str(SECRET_KEY), audience="users/reset-password", issuer="users", algorithms=["HS256"], ) assert decoded_token["user_id"] == 50 assert decoded_token["jti"] == "reset-password:50:1"
async def _(): user = User( id=10, email="*****@*****.**", date_joined=datetime.now(timezone.utc), password="******", is_active=True, jwt_auth_id=1, ) await reset_password( ResetPasswordInput(token=user.create_reset_password_token(), new_password="******"), repository=FakeUsersRepository([user]), ) assert user.new_password == "testnewpassword" # we did column + 1 so the value updated in the DB and not python assert user.jwt_auth_id.left.name == "jwt_auth_id" assert user.jwt_auth_id.right.value == 1
async def _(): user = User( id=1, email="*****@*****.**", name="Name", is_staff=False, date_joined=datetime.utcnow(), ) repository = FakeUsersRepository(users=[user]) jwt_token = user.generate_token() request = MagicMock() request.headers = {"Authorization": f"Bearer {jwt_token}"} credentials, logged_user = await JWTAuthBackend(repository).authenticate( request) assert credentials.scopes == [Credential.AUTHENTICATED] assert logged_user.id == user.id
def test_login_success(user_repository_mock, user_id, user_name, password): user_repository_mock.find_by_user_id.return_value = User( id=UserId(value=user_id), name=UserName(value=user_name), password="******", ) user_application_service = UserApplicationService( user_repository=user_repository_mock) input_dto = LoginInputDto(user_id=user_id, password=password) actual = user_application_service.login(input_dto) expected = LoginOutputDto() assert actual == expected
def test_find_user_success(user_repository_mock, user_id, user_name, password): user_repository_mock.find_by_user_id.return_value = User( id=UserId(value=user_id), name=UserName(value=user_name), password=password) user_application_service = UserApplicationService( user_repository=user_repository_mock) input_dto = FindUserInputDto(user_id=user_id) actual = user_application_service.find_user(input_dto) expected = FindUserOutputDto(user_id=user_id, user_name=user_name, description="", image_url="") assert actual == expected
def test_login_fail_with_wrong_password(user_repository_mock, user_id, user_name, password): wrong_password = "******" user_repository_mock.find_by_user_id.return_value = User( id=UserId(value=user_id), name=UserName(value=user_name), password="******", ) user_application_service = UserApplicationService( user_repository=user_repository_mock) input_dto = LoginInputDto(user_id=user_id, password=wrong_password) actual = user_application_service.login(input_dto) expected = FailedOutputDto.build_unauthorized_error( message=f"잘못된 비밀번호 입니다.") assert actual == expected
async def _(): user = User( id=1, email="*****@*****.**", name="Name", is_staff=False, date_joined=datetime.utcnow(), ) repository = FakeUsersRepository(users=[user]) request = MagicMock() request.headers = {"Authorization": f"token abc"} result = await JWTAuthBackend(repository).authenticate(request) assert not result
def update_user( self, input_dto: UpdateUserInputDto ) -> Union[UpdateUserOutputDto, FailedOutputDto]: try: user = User( id=UserId(value=input_dto.user_id), name=UserName(value=input_dto.user_name), description=input_dto.description, password=input_dto.password, ) self._user_repository.update(user) return UpdateUserOutputDto() except ResourceNotFoundError as e: return FailedOutputDto.build_resource_not_found_error( message=str(e)) except Exception as e: return FailedOutputDto.build_system_error(message=str(e))
async def _(db=db, second_session=second_session, cleanup_db=cleanup_db): db = cast(AsyncSession, db) second_session = cast(AsyncSession, second_session) repository = UsersRepository(db) await repository.create_user( User( email="*****@*****.**", password="******", date_joined=datetime.datetime(2020, 1, 1, 1, tzinfo=datetime.timezone.utc), username="******", fullname="Nanan Nana", gender="male", date_birth=datetime.date(2000, 5, 1), open_to_newsletter=False, open_to_recruiting=True, country="IT", is_active=True, is_staff=False, is_superuser=False, )) await repository.commit() query = select(User).where(User.email == "*****@*****.**") db_user: User = (await second_session.execute(query)).scalar() assert db_user assert db_user.date_joined == datetime.datetime( 2020, 1, 1, 1, tzinfo=datetime.timezone.utc) assert db_user.username == "username" assert db_user.fullname == "Nanan Nana" assert db_user.gender == "male" assert db_user.date_birth == datetime.date(2000, 5, 1) assert db_user.open_to_newsletter is False assert db_user.open_to_recruiting is True assert db_user.country == "IT" assert db_user.is_active is True assert db_user.is_staff is False assert db_user.is_superuser is False
async def request_reset_password(user: User): if not user.is_active: logger.info( "Trying to request reset password of not active user_id=%s", user.id) raise UserIsNotActiveError() token = user.create_reset_password_token() send_email( template=EmailTemplate.RESET_PASSWORD, to=user.email, subject="Reset your password", variables={ "firstname": user.name, # "resetpasswordlink": f"{ASSOCIATION_FRONTEND_URL}/reset-password/{token}", "resetpasswordlink": f"https://pycon.it/en/reset-password/{token}", }, ) logger.info("Sent reset password token of user_id=%s", user.id)
def create_user( self, input_dto: CreateUserInputDto ) -> Union[CreateUserOutputDto, FailedOutputDto]: try: user = User( id=UserId(value=input_dto.user_id), name=UserName(value=input_dto.user_name), password=self._get_password_hash(input_dto.password), ) self._user_repository.add(user) return CreateUserOutputDto( user_id=str(user.id), user_name=str(user.name), description=user.description, image_url=user.image_url, ) except ResourceAlreadyExistError as e: return FailedOutputDto.build_resource_conflict_error( message=str(e)) except Exception as e: return FailedOutputDto.build_system_error(message=str(e))