Esempio n. 1
0
 def _get_tokens(user: User, session_id: Union[str,
                                               UUID]) -> TokenCollection:
     token_payload = {"user_id": user.id, "session_id": str(session_id)}
     access_token, access_token_expired_at = encode_jwt(token_payload)
     refresh_token, refresh_token_expired_at = encode_jwt(
         token_payload,
         token_type=TOKEN_TYPE_REFRESH,
     )
     return TokenCollection(
         refresh_token=refresh_token,
         refresh_token_expired_at=refresh_token_expired_at,
         access_token=access_token,
         access_token_expired_at=access_token_expired_at,
     )
Esempio n. 2
0
 async def test_get_rendered_page__ok(self, unauth_client, user):
     token = encode_jwt({"user_id": user.id})
     response = await unauth_client.get(self.path, params={"t": token})
     assert response.status == 200
     content = await response.text()
     assert token in content
     assert user.email in content
Esempio n. 3
0
 def test_user_does_not_exist__fail(self, client, user):
     user_id = 0
     token, _ = encode_jwt({"user_id": user_id},
                           token_type=TOKEN_TYPE_RESET_PASSWORD)
     response_data = self._assert_fail_response(client, token)
     self.assert_auth_invalid(
         response_data, f"Couldn't found active user with id={user_id}.")
Esempio n. 4
0
 def test__token_invalid_type__fail(self, client, user):
     token, _ = encode_jwt({"user_id": user.id},
                           token_type=TOKEN_TYPE_REFRESH)
     response_data = self._assert_fail_response(client, token)
     self.assert_auth_invalid(
         response_data,
         "Token type 'reset_password' expected, got 'refresh' instead.")
Esempio n. 5
0
 def test_user_inactive__fail(self, client, user, dbs):
     await_(user.update(dbs, is_active=False))
     await_(dbs.commit())
     token, _ = encode_jwt({"user_id": user.id},
                           token_type=TOKEN_TYPE_RESET_PASSWORD)
     response_data = self._assert_fail_response(client, token)
     self.assert_auth_invalid(
         response_data, f"Couldn't found active user with id={user.id}.")
Esempio n. 6
0
 async def test_get_rendered_page__token_expired__fail(
         self, unauth_client, user):
     token = encode_jwt({"user_id": user.id}, expiration_seconds=-10)
     response = await unauth_client.get(self.path, params={"t": token})
     assert response.status == 200
     content = await response.text()
     assert token not in content
     assert "Provided token is missed or incorrect" in content
Esempio n. 7
0
 def _generate_token(user: User):
     payload = {
         "user_id": user.id,
         "email": user.email,
         "jti": f"token-{uuid.uuid4()}",  # JWT ID
         "slt": get_salt(),
     }
     return encode_jwt(payload, expiration_seconds=settings.RESET_PASSWORD_LINK_EXP)
    def test_check_auth__token_t_mismatch__fail(self, client, user,
                                                user_session, token_type, dbs):
        await_(user_session.update(dbs, is_active=False))
        await_(dbs.commit())
        token, _ = encode_jwt({"user_id": user.id}, token_type=token_type)
        request = self._prepare_request(dbs, user, user_session)
        with pytest.raises(AuthenticationFailedError) as err:
            await_(
                BaseAuthJWTBackend(request).authenticate_user(
                    token, token_type="access"))

        assert err.value.details == f"Token type 'access' expected, got '{token_type}' instead."
Esempio n. 9
0
 def _generate_token(user: User) -> str:
     payload = {
         "user_id": user.id,
         "email": user.email,
         "jti": f"token-{uuid.uuid4()}",  # JWT ID
         "slt": get_salt(),
     }
     token, _ = encode_jwt(
         payload,
         token_type=TOKEN_TYPE_RESET_PASSWORD,
         expires_in=settings.RESET_PASSWORD_LINK_EXPIRES_IN,
     )
     return token
 def _prepare_request(db_session: AsyncSession, user: User,
                      user_session: UserSession):
     jwt, _ = encode_jwt({
         "user_id": user.id,
         "session_id": user_session.public_id
     })
     scope = {
         "type": "http",
         "headers": [(b"authorization", f"Bearer {jwt}".encode("latin-1"))]
     }
     request = Request(scope)
     request.db_session = db_session
     return request
Esempio n. 11
0
 def test_refresh_token__token_not_refresh__fail(self, client, user,
                                                 token_type):
     refresh_token, _ = encode_jwt({"user_id": user.id},
                                   token_type=token_type)
     response = client.post(self.url, json={"refresh_token": refresh_token})
     response_data = self.assert_fail_response(
         response,
         status_code=401,
         response_status=ResponseStatus.AUTH_FAILED)
     assert response_data == {
         "error":
         "Authentication credentials are invalid.",
         "details":
         f"Token type 'refresh' expected, got '{token_type}' instead.",
     }
Esempio n. 12
0
 async def test_token_invalid__fail(self, unauth_client, user):
     token = encode_jwt({"user_id": user.id}) + "fake-post"
     new_password = "******"
     response = await unauth_client.post(self.path,
                                         data={
                                             "token": token,
                                             "password_1": new_password,
                                             "password_2": new_password
                                         })
     assert response.status == 401
     response_data = await response.json()
     assert response_data == {
         "details":
         "Invalid token header. Token could not be decoded as JWT.",
         "message": "Authentication credentials are invalid",
     }
Esempio n. 13
0
    async def test_change_password_success__ok(self, unauth_client, user,
                                               web_app):
        token = encode_jwt({"user_id": user.id})
        new_password = "******"
        response = await unauth_client.post(self.path,
                                            data={
                                                "token": token,
                                                "password_1": new_password,
                                                "password_2": new_password
                                            })
        assert response.status == 200
        response_data = await response.json()
        assert response_data["redirect_url"] == str(
            web_app.router["index"].url_for())

        user = await User.async_get(web_app.objects, id=user.id)
        assert user.verify_password(new_password)
Esempio n. 14
0
 async def test_user_does_not_exist__fail(self, unauth_client, user,
                                          db_objects):
     user_id = "fake-user-id"
     token = encode_jwt({"user_id": user_id})
     new_password = "******"
     response = await unauth_client.post(self.path,
                                         data={
                                             "token": token,
                                             "password_1": new_password,
                                             "password_2": new_password
                                         })
     assert response.status == 401
     response_data = await response.json()
     assert response_data == {
         "message": "Authentication credentials are invalid",
         "details":
         f"Active user #{user_id} not found or token is invalid.",
     }
Esempio n. 15
0
    def test_change_password__ok(self, client, user, user_session, dbs):
        token, _ = encode_jwt(
            {
                "user_id": user.id,
                "session_id": user_session.public_id
            },
            token_type=TOKEN_TYPE_RESET_PASSWORD,
        )
        request_data = {
            "token": token,
            "password_1": self.new_password,
            "password_2": self.new_password,
        }
        client.logout()
        response = client.post(self.url, json=request_data)
        response_data = self.assert_ok_response(response)
        assert_tokens(response_data, user)

        await_(dbs.refresh(user))
        assert user.verify_password(self.new_password)
Esempio n. 16
0
 def _prepare_token(db_session: AsyncSession,
                    user: User,
                    is_active=True,
                    refresh=True) -> UserSession:
     token_type = TOKEN_TYPE_REFRESH if refresh else TOKEN_TYPE_ACCESS
     session_id = str(uuid.uuid4())
     refresh_token, _ = encode_jwt(
         {
             "user_id": user.id,
             "session_id": session_id
         },
         token_type=token_type)
     user_session = await_(
         UserSession.async_create(
             db_session,
             db_commit=True,
             user_id=user.id,
             is_active=is_active,
             public_id=session_id,
             refresh_token=refresh_token,
             expired_at=datetime.utcnow(),
         ))
     return user_session
Esempio n. 17
0
 def test__token_expired__fail(self, client, user):
     token, _ = encode_jwt({"user_id": user.id}, expires_in=-10)
     response_data = self._assert_fail_response(
         client, token, ResponseStatus.SIGNATURE_EXPIRED)
     self.assert_auth_invalid(response_data,
                              "JWT signature has been expired for token")
Esempio n. 18
0
 def login(self, user: User):
     user_session = create_user_session(self.db_session, user)
     jwt, _ = encode_jwt({"user_id": user.id, "session_id": user_session.public_id})
     self.headers["Authorization"] = f"Bearer {jwt}"
     return user_session