diff --git a/fastapi_auth_jwt/dependencies.py b/fastapi_auth_jwt/dependencies.py index 21490da1..dce7cf04 100644 --- a/fastapi_auth_jwt/dependencies.py +++ b/fastapi_auth_jwt/dependencies.py @@ -204,8 +204,9 @@ def __call__( except Unauthorized as e: raise HTTPException(status_code=HTTP_401_UNAUTHORIZED) from e if not partner_id: - _logger.info("Could not determine partner from JWT payload.") - raise HTTPException(status_code=HTTP_401_UNAUTHORIZED) + if not self.allow_unauthenticated or validator.partner_id_required: + _logger.info("Could not determine partner from JWT payload.") + raise HTTPException(status_code=HTTP_401_UNAUTHORIZED) return env["res.partner"].with_user(uid).browse(partner_id) diff --git a/fastapi_auth_jwt_demo/tests/test_fastapi_auth_jwt_demo.py b/fastapi_auth_jwt_demo/tests/test_fastapi_auth_jwt_demo.py index 9d29e693..8d4f2bfa 100644 --- a/fastapi_auth_jwt_demo/tests/test_fastapi_auth_jwt_demo.py +++ b/fastapi_auth_jwt_demo/tests/test_fastapi_auth_jwt_demo.py @@ -52,6 +52,14 @@ def test_whoami(self): self.assertEqual(whoami.get("email"), partner.email) self.assertEqual(whoami.get("uid"), self.env.ref("base.user_demo").id) + def test_whoami_no_partner(self): + """A end-to-end test with positive authentication but no partner retrieved.""" + token = self._get_token() + resp = self.url_open( + "/fastapi_auth_jwt_demo/whoami", headers={"Authorization": token} + ) + self.assertEqual(resp.status_code, 401) + def test_whoami_cookie(self): """A end-to-end test with positive authentication and cookie.""" partner = self.env["res.users"].search([("email", "!=", False)])[0] @@ -105,6 +113,28 @@ def test_public(self): self.assertEqual(whoami.get("email"), partner.email) self.assertEqual(whoami.get("uid"), self.env.ref("base.user_demo").id) + def test_public_no_partner(self): + """A end-to-end test for anonymous/public access without partner.""" + token = self._get_token() + resp = self.url_open( + "/fastapi_auth_jwt_demo/whoami-public-or-jwt", + headers={"Authorization": token}, + ) + resp.raise_for_status() + whoami = resp.json() + self.assertFalse(whoami.get("name")) + self.assertFalse(whoami.get("email")) + self.assertEqual(whoami.get("uid"), self.env.ref("base.user_demo").id) + # now with partner required on validator + self.env["auth.jwt.validator"].search( + [("name", "=", "demo")] + ).partner_id_required = True + resp = self.url_open( + "/fastapi_auth_jwt_demo/whoami-public-or-jwt", + headers={"Authorization": token}, + ) + self.assertEqual(resp.status_code, 401) + def test_public_cookie_mode(self): """A end-to-end test for anonymous/public access with cookie.""" resp = self.url_open("/fastapi_auth_jwt_demo/cookie/whoami-public-or-jwt")