async def register(repo: UserRepo, credentials: Credentials) -> UserRegistry: email = credentials.email.lower() user = await repo.fetch_by_email(email) if user: raise EmailNotUniqueError(email) password_hash = hash_service.hash_(credentials.password) user = await repo.persist(email, password_hash) return UserRegistry(**user.dict())
async def _populate_user(db: Database) -> None: values = [ { "email": "*****@*****.**", "password_hash": hash_service.hash_("dev@1234"), }, { "email": "*****@*****.**", "password_hash": hash_service.hash_("dev2@1234"), }, { "email": "*****@*****.**", "password_hash": hash_service.hash_("dev3@1234"), }, { "email": "*****@*****.**", "password_hash": hash_service.hash_("dev4@1234"), }, ] await _populate_table(db, User, values)
def test_success(self, test_client, credentials): insert_user({ "email": credentials.email, "password_hash": hash_service.hash_(credentials.password), }) with test_client as client: response = client.post(oauth2_token_url, data=build_form_data(credentials)) body = response.json() assert body["access_token"] assert body["expire"] assert body["token_type"] == "bearer" assert response.status_code == 200
async def test_invalid_credentials(self, user_repo, credentials, user): # Setup email = credentials.email password_hash = hash_service.hash_("other password") user_repo.fetch_by_email.return_value = User( **{ **user.dict(), "email": email, "password_hash": password_hash }) # Test result = await user_service.get_by_credentials(user_repo, credentials) # Assertions user_repo.fetch_by_email.assert_called_once_with(email) assert not result
def logged_user(test_client, credentials): id_ = 1 email = credentials.email password_hash = hash_service.hash_(credentials.password) insert_user({ "id": id_, "email": credentials.email, "password_hash": password_hash }) with test_client as client: response = client.post(oauth2_token_url, data=build_form_data(credentials)) body = response.json() return LoggedUser( User(id=id_, email=email, password_hash=password_hash), body["access_token"], )
def test_different_secrets_must_be_different(self, secret, other): assert hash_service.hash_(secret) != hash_service.hash_(other)
def test_hash_same_secret_must_be_different(self, secret): assert hash_service.hash_(secret) != hash_service.hash_(secret)
def test_hash_must_be_verifiable(self, secret): hash_ = hash_service.hash_(secret) assert hash_service.verify(secret, hash_)
def test_hash_secret(self, secret): hash_ = hash_service.hash_(secret) assert secret != hash_
def test_invalid_hash(self, secret, other): other_hash = hash_service.hash_(other) assert not hash_service.verify(secret, other_hash)
def test_valid_hash(self, secret): result = hash_service.hash_(secret) assert hash_service.verify(secret, result)