def ensureTokenScopes(token, scope): """ Call this to validate a token scope for endpoints that require tokens other than a user authentication token. Raises an AccessException if the required scopes are not allowed by the given token. :param token: The token object used in the request. :type token: dict :param scope: The required scope or set of scopes. :type scope: `str or list of str` """ tokenModel = Token() if tokenModel.hasScope(token, TokenScope.USER_AUTH): return if not tokenModel.hasScope(token, scope): setCurrentUser(None) if isinstance(scope, six.string_types): scope = (scope,) raise AccessException( 'Invalid token scope.\n' 'Required: %s.\n' 'Allowed: %s' % ( ' '.join(scope), '' if token is None else ' '.join(tokenModel.getAllowedScopes(token))))
def _authorizeInitUpload(event): """ Called when initializing an upload, prior to the default handler. Checks if the user is passing an authorized upload token, and if so, sets the current request-thread user to be whoever created the token. """ token = getCurrentToken() params = event.info['params'] tokenModel = Token() parentType = params.get('parentType') parentId = params.get('parentId', '') requiredScopes = {TOKEN_SCOPE_AUTHORIZED_UPLOAD, 'authorized_upload_folder_%s' % parentId} if parentType == 'folder' and tokenModel.hasScope(token=token, scope=requiredScopes): user = User().load(token['userId'], force=True) setCurrentUser(user)
def _storeUploadId(event): """ Called after an upload is first initialized successfully. Sets the authorized upload ID in the token, ensuring it can be used for only this upload. """ returnVal = event.info['returnVal'] token = getCurrentToken() tokenModel = Token() isAuthorizedUpload = tokenModel.hasScope(token, TOKEN_SCOPE_AUTHORIZED_UPLOAD) if isAuthorizedUpload and returnVal.get('_modelType', 'upload') == 'upload': params = event.info['params'] token['scope'].remove(TOKEN_SCOPE_AUTHORIZED_UPLOAD) token['authorizedUploadId'] = returnVal['_id'] token['authorizedUploadDescription'] = params.get('authorizedUploadDescription', '') token['authorizedUploadEmail'] = params.get('authorizedUploadEmail') tokenModel.save(token)