def _(fn): if inspect.isfunction(fn) or inspect.ismethod(fn): @functools.wrap(fn) async def _(request: Request): pair = await backend.authenticate(request) if pair is None: pair = AuthCredentials(), UnauthenticatedUser() request.scope["auth"], request.scope["user"] = pair return _ else: return AuthenticationMiddleware(fn, backend)
def test_no_cookie(self): """ Make sure it works when there is no cookie with the correct name. """ app = AuthenticationMiddleware( EchoEndpoint, SessionsAuthBackend(allow_unauthenticated=True), ) client = TestClient(app) # Test it with no cookie set response = client.get("/") self.assertEqual(response.status_code, 200) self.assertEqual( response.json(), {"is_unauthenticated_user": True, "is_authenticated": False}, )
def test_wrong_cookie_value(self): """ Make sure it works when there is a cookie with the correct name, but an incorrect value. """ app = AuthenticationMiddleware( EchoEndpoint, SessionsAuthBackend(allow_unauthenticated=True), ) client = TestClient(app) # Test it with a cookie set, but containing an incorrect token. response = client.get("/", cookies={"id": "abc123"}) self.assertEqual(response.status_code, 200) self.assertEqual( response.json(), {"is_unauthenticated_user": True, "is_authenticated": False}, )
async def init_caffeine(self): jwt_helper = JwtHelper(str(self.settings.JWT_SECRET)) e = casbin.Enforcer(self.settings.CASBIN_MODEL, self.settings.CASBIN_POLICY) enforcer = Enforcer(e) security_container = SecurityContainer( jwt_helper, enforcer, self.settings.JWT_COOKIE_KEY, self.settings.JWT_COOKIE_REFRESH_KEY, self.settings.JWT_COOKIE_EXPIRE, ) recaptcha = Recaptcha(self.settings.RECAPTCHA_SECRET) self.shutdown_events.put(recaptcha.shutdown) templater = Templater(self.settings.TEMPLATE_PATH) # PubSub pubsub_store = PubSubStore(self.db) pubsub = PostgresPubSub(pubsub_store) # User user_store = PostgreSQLUserStore(self.db) user_service = UserService(self.settings, user_store, pubsub, templater) user_handler = UserHandler(self.settings, user_service, security_container, recaptcha) # App health_service = HealthService(self.db) app_handler = AppHandler(health_service) auth_middleware = AuthenticationMiddleware( self.app, backend=JwtAuthBackend(user_service, security_container.jwt_helper, security_container.jwt_cookie_key), ) router = StarletteRouter(self.app) user_routers = UserRouter(user_handler, auth_middleware, router) app_routers = AppRouter(app_handler, router) router.mount("/v1", app_routers.init()) router.mount("/v1", user_routers.init()) router.export()
def app(user_service, recaptcha=True): starlette = Starlette() r = Mock(Recaptcha("")) r.check.return_value = recaptcha ExceptionHandlers(starlette) settings = Settings() settings.JWT_TOKEN_EXPIRE = 10 settings.JWT_TOKEN_REFRESH_EXPIRE = 50 user_handler = UserHandler(settings, user_service, security_container, r) router = StarletteRouter(starlette) auth_middleware = AuthenticationMiddleware( starlette, backend=JwtAuthBackend(user_service, security_container.jwt_helper, security_container.jwt_cookie_key), ) user_routers = UserRouter(user_handler, auth_middleware, router) router.mount("/v1", user_routers.init()) router.export() return starlette
return PlainTextResponse("top secret") ROUTER = Router(routes=[ Route("/", HomeEndpoint, name="home"), Route( "/login/", session_login(), name="login", ), Route("/logout/", session_logout(), name="login"), Mount( "/secret/", AuthenticationMiddleware( ProtectedEndpoint, SessionsAuthBackend( admin_only=True, superuser_only=True, active_only=True), ), ), ]) APP = ExceptionMiddleware(ROUTER) ############################################################################### class SessionTestCase(TestCase): credentials = {"username": "******", "password": "******"} wrong_credentials = {"username": "******", "password": "******"} def setUp(self): SessionsBase.create_table().run_sync()