def procureASession(self, request): # type: (IRequest) -> Any try: yield (SessionProcurer( self.sessionStore, secureTokenHeader=b"X-Test-Session").procureSession(request)) except NoSuchSession: # Intentionally slightly buggy - if a session can't be procured, # simply leave it out and rely on checkCSRF to ensure the session # component is present before proceeding. pass
def simpleSessionRouter(): # type: () -> Tuple[sessions, errors, str, str, StubTreq] """ Construct a simple router. """ sessions = [] exceptions = [] mss = MemorySessionStore.fromAuthorizers([memoryAuthorizer]) router = Klein() token = "X-Test-Session-Token" cookie = "X-Test-Session-Cookie" sproc = SessionProcurer( mss, secureTokenHeader=b"X-Test-Session-Token", secureCookie=b"X-Test-Session-Cookie", ) @router.route("/") @inlineCallbacks def route(request): # type: (IRequest) -> Deferred try: sessions.append((yield sproc.procureSession(request))) except NoSuchSession as nss: exceptions.append(nss) returnValue(b"ok") requirer = Requirer() @requirer.prerequisite([ISession]) def procure(request): # type: (IRequest) -> Deferred return sproc.procureSession(request) @requirer.require(router.route("/test"), simple=Authorization(ISimpleTest)) def testRoute(simple): # type: (SimpleTest) -> str return "ok: " + str(simple.doTest() + 4) @requirer.require(router.route("/denied"), nope=Authorization(IDenyMe)) def testDenied(nope): # type: (IDenyMe) -> str return "bad" treq = StubTreq(router.resource()) return sessions, exceptions, token, cookie, treq
def route(request: IRequest) -> Deferred: sproc = SessionProcurer(mss, setCookieOnGET=False) with self.assertRaises(NoSuchSession): yield sproc.procureSession(request) returnValue(b"no session")
def procurer(request): return SessionProcurer(sessions).procureSession(request)