def setUpClass(cls): super(FullExampleTestCase, cls).setUpClass() sys.path.append(os.path.abspath(os.path.join( os.path.dirname(__file__), '..', '..', 'example'))) exampleModule = importlib.import_module('main') # noinspection PyUnresolvedReferences cls._VALID_CLIENT = exampleModule.getTestClient() # noinspection PyUnresolvedReferences cls._SERVER = MockSite(exampleModule.setupTestServerResource()) TokenResource.getTokenStorageSingleton().store( cls._VALID_TOKEN, cls._VALID_CLIENT, cls._VALID_SCOPE)
def isAuthorized(request, scope, allowInsecureRequestDebug=False): """ Returns True if the token in the request grants access to the given scope. The token is validated via the authTokenStorage singleton given to the TokenResource instance. If the token is invalid, does not grant access to the scope or was not send via a secure protocol, False is returned, an error is written to the request and the request is closed. You can not write to the request if this function returned False! :param request: The request. :param scope: The scope or list of scopes the token must grant access to. :param allowInsecureRequestDebug: Allow requests to originate from insecure connections. Only use for local testing! :return: True, if the request is authorized, False otherwise. """ error = None scope = scope if type(scope) == list else [scope] if not (allowInsecureRequestDebug or request.isSecure()): error = InsecureConnectionError() else: try: requestToken = _getToken(request) except ValueError: error = MultipleTokensError(scope) else: if requestToken is None: error = MissingTokenError(scope) else: try: requestToken = requestToken.decode('utf-8') except UnicodeDecodeError: pass else: tokenStorage = TokenResource.getTokenStorageSingleton() if tokenStorage.contains(requestToken): if tokenStorage.hasAccess(requestToken, scope): return True else: error = InsufficientScopeRequestError(scope) if error is None: error = InvalidTokenRequestError(scope) request.write(error.generate(request)) request.finish() return False