def _options(self, context: IResource, request: IRequest) -> dict: empty = {} # tiny performance tweak cstruct = deepcopy(options_resource_response_data_dict) if request.has_permission('edit_some', context): edits = self.content.get_sheets_edit(context, request) put_sheets = [(s.meta.isheet.__identifier__, empty) for s in edits] if put_sheets: put_sheets_dict = dict(put_sheets) self._add_metadata_edit_permission_info(put_sheets_dict) self._add_workflow_edit_permission_info(put_sheets_dict, edits) cstruct['PUT']['request_body']['data'] = put_sheets_dict else: del cstruct['PUT'] else: del cstruct['PUT'] if request.has_permission('view', context): views = self.content.get_sheets_read(context, request) get_sheets = [(s.meta.isheet.__identifier__, empty) for s in views] if get_sheets: cstruct['GET']['response_body']['data'] = dict(get_sheets) else: del cstruct['GET'] else: del cstruct['GET'] if not request.has_permission('delete', context): del cstruct['DELETE'] is_users = IUsersService.providedBy(context) \ and request.has_permission('create_user', context) # TODO move the is_user specific part the UsersRestView if request.has_permission('create', self.context) or is_users: addables = self.content.get_resources_meta_addable(context, request) if addables: for resource_meta in addables: iresource = resource_meta.iresource resource_typ = iresource.__identifier__ creates = self.content.get_sheets_create(context, request, iresource) sheet_typs = [s.meta.isheet.__identifier__ for s in creates] sheets_dict = dict.fromkeys(sheet_typs, empty) post_data = {'content_type': resource_typ, 'data': sheets_dict} cstruct['POST']['request_body'].append(post_data) else: del cstruct['POST'] else: del cstruct['POST'] return cstruct
def test_subclass_mutate_before_providedBy(self): from pyramid.interfaces import IRequest from pyramid.request import Request from pyramid.util import InstancePropertyHelper class RequestSub(Request): pass req = RequestSub({}) helper = InstancePropertyHelper() helper.apply_properties(req, {'b': 'b'}) self.assertTrue(IRequest.providedBy(req)) self.assertTrue(IRequest.implementedBy(RequestSub))
def allows(self, principals, permission=None): """ ``principals`` may either be 1) a sequence of principal indentifiers, 2) a single principal identifier, or 3) a Pyramid request, which indicates that all the effective principals implied by the request are used. ``permission`` may be ``None`` if this index is configured with only a single permission. Otherwise a permission name must be passed or an error will be raised. """ permissions = self.discriminator.permissions if permission is None: if len(permissions) > 1: raise ValueError('Must pass a permission') else: permission = list(permissions)[0] else: if permissions is not None and not permission in permissions: raise ValueError( 'This index does not support the %s ' 'permission' % (permission,) ) if IRequest.providedBy(principals): principals = effective_principals(principals) elif not is_nonstr_iter(principals): principals = (principals,) principals = [ get_principal_repr(p) for p in principals ] values = [(principal, permission) for principal in principals] return hypatia.query.Any(self, values)
def _authorize(*args, **kwargs): login_required = HTTPUnauthorized() login_required.headers['WWW-Authenticate'] = \ 'Basic realm="Manage bridge"' if IRequest.providedBy(args[0]): request = args[0] else: request = args[0].request authorization = request.headers.get('Authorization', None) if not authorization: raise login_required _basic, authorization = authorization.split(' ', 1) username, password = authorization.decode('base64').split(':', 1) settings = getUtility(ISettings) admin_user = settings.get('bridge.admin.username', object()) admin_pass = settings.get('bridge.admin.password', object()) if username != admin_user or password != admin_pass: raise login_required return fun(*args, **kwargs)
def apply_async_web_process(self, args, kwargs): """Schedule a task from web process. Do not trigger the task until transaction commit. Check that we pass Request to the task as the first argument always. This is an extra complex sanity check. """ # Intercept request argumetn going to the function args_ = kwargs.get("args", []) kwargs_ = kwargs.get("kwargs", {}) request, args_, kwargs_ = _pop_request_argument(args_, kwargs_) kwargs["args"] = args_ kwargs["kwargs"] = kwargs_ if not IRequest.providedBy(request): raise BadAsyncLifeCycleException("You must explicitly pass request as the first argument to asynchronous tasks as these tasks are bound to happen when the database transaction tied to the request lifecycle completes.") # If for whatever reason we were unable to get a request we'll just # skip this and call the original method to send this immediately. if not hasattr(request, "tm"): return super().apply_async(*args, **kwargs) # This will break things that expect to get an AsyncResult because # we're no longer going to be returning an async result from this when # called from within a request, response cycle. Ideally we shouldn't be # waiting for responses in a request/response cycle anyways though. request.tm.get().addAfterCommitHook( self._after_commit_hook, args=args, kws=kwargs, )
def serialize(self, appstruct: Request): if appstruct is colander.null: return colander.null if not IRequest.providedBy(appstruct): msg = '{:s} does not implement IRequest interface'.format( str(appstruct)) raise Invalid(self, msg) content_type = getattr(appstruct, "content_type", "application/octet-stream") if content_type != "application/json": msg = "{:s} is not a json request.".format((str(appstruct))) raise Invalid(self, msg) try: json_body = appstruct.json_body or {} except (JSONDecodeError, AttributeError): json_body = {} appstruct = { "body": json_body, "queryset": appstruct.GET, } return super(RequestSchema, self).serialize(appstruct)
def get_registration_service(request: Request) -> IRegistrationService: """Get the registration service. :param request: Pyramid request. :return: Implementation of IRegistrationService. """ assert IRequest.providedBy(request) return request.registry.queryAdapter(request, IRegistrationService)
def get_domain(request): if IRequest.providedBy(request): referrer = get_referrer(request) else: referrer = request if not referrer: return '' return urlsplit(referrer).netloc.split(':')[0]
def get_oauth_login_service(request: Request) -> IOAuthLoginService: """Get the oauth login service. :param request: Pyramid request. :return: Implementation of IOAuthLoginService. """ assert IRequest.providedBy(request) return request.registry.queryAdapter(request, IOAuthLoginService)
def get_credential_activity_service(request: Request) -> ICredentialService: """Get the credential activity service. :param request: Pyramid request. :return: Implementation of ICredentialService. """ assert IRequest.providedBy(request) return request.registry.queryAdapter(request, ICredentialService)
def _validate_list_schema(schema: SequenceSchema, cstruct: list, request: IRequest, location='body'): if location != 'body': # for now we only support location == body return child_cstructs = schema.cstruct_children(cstruct) try: request.validated = schema.deserialize(child_cstructs) except Invalid as err: _add_colander_invalid_error(err, request, location)
def __init__(self, request: Request, obj: object): """ :param obj: The underlying object we wish to wrap for traversing. Usually SQLALchemy model instance. """ # Some safety checks we get arguments correctly.n assert IRequest.providedBy(request) self.request = request self.obj = obj
def _get_api_auth_data(headers: [tuple], request: IRequest, user: IResource)\ -> dict: token_headers = dict([(x, y) for x, y in headers if x == UserTokenHeader]) token = token_headers[UserTokenHeader] user_url = request.resource_url(user) # TODO: use colander schema to create cstruct return {'status': 'success', 'user_path': user_url, 'user_token': token, }
def guess_request(view, *args, **kwargs): """Extract request from view arguments. Pyramid may place request as the first or second argumetn depending if view gets a context argument.""" request = kwargs.get("request") if request: return request first_arg = args[0] if IRequest.providedBy(first_arg): return first_arg if len(args) >= 2: second_arg = args[1] if IRequest.providedBy(second_arg): return second_arg raise AssertionError("Could not determine request argument for view: {} args: {} kwargs: {}".format(view, args, kwargs))
def allows(self, principals, permission='view'): """ ``principals`` may either be 1) a sequence of principal indentifiers, 2) a single principal identifier, or 3) a Pyramid request, which indicates that all the effective principals implied by the request are used.""" if IRequest.providedBy(principals): principals = effective_principals(principals) elif not is_nonstr_iter(principals): principals = (principals, ) values = [(principal, permission) for principal in principals] return hypatia.query.Any(self, values)
def _extract_json_body(request: IRequest) -> object: json_body = {} if request.body == '': request.body = '{}' try: json_body = request.json_body except (ValueError, TypeError) as err: error = error_entry('body', None, 'Invalid JSON request body'.format(err)) request.errors.append(error) return json_body
def query_layout(context, request, name=''): """ query named layout for context """ assert IRequest.providedBy(request), u"must pass in a request object" for context in lineage(context): layout = request.registry.queryMultiAdapter( (context, request), ILayout, name) if layout is not None: return layout return None
def effective_principals(self, request: IRequest) -> list: """Return userid, roles and groups for the authenticated user. THE RESULT IS CACHED for the current request in the request attribute called: __cached_principals__ . """ cached_principals = getattr(request, '__cached_principals__', None) if cached_principals: return cached_principals principals = super().effective_principals(request) request.__cached_principals__ = principals return principals
def __init__(self, user, revoked_tos, request): # Static typing old style... :( assert IUser.providedBy(user) if ITOS.providedBy(revoked_tos): revoked_tos = [revoked_tos] else: for tos in revoked_tos: assert ITOS.providedBy(tos) assert IRequest.providedBy(request) self.user = user self.revoked_tos = revoked_tos self.request = request
def get_choices_by_interface(interface: IInterface, context: IResource, request: IRequest, ) -> []: """Get choices for resource paths by interface.""" catalogs = find_service(context, 'catalogs') query = search_query._replace(interfaces=interface) resources = catalogs.search(query).elements choices = [(request.resource_url(r, route_name=API_ROUTE_NAME), resource_path(r)) for r in resources] return choices
def allows(self, principals, permission): """ ``principals`` may either be 1) a sequence of principal indentifiers, 2) a single principal identifier, or 3) a Pyramid request, which indicates that all the effective principals implied by the request are used. ``permission`` must be a permission name. """ if IRequest.providedBy(principals): principals = effective_principals(principals) elif not is_nonstr_iter(principals): principals = (principals, ) return AllowsComparator(self, (principals, permission))
def effective_principals(self, request: IRequest) -> list: """Return userid, roles and groups for the authenticated user. THE RESULT IS CACHED for the current request in the request attribute called: __cached_principals__ . """ cached_principals = getattr(request, '__cached_principals__', None) if cached_principals: return cached_principals else: principals = super().effective_principals(request) request.__cached_principals__ = principals return principals
def allows(self, principals, permission): """ ``principals`` may either be 1) a sequence of principal indentifiers, 2) a single principal identifier, or 3) a Pyramid request, which indicates that all the effective principals implied by the request are used. ``permission`` must be a permission name. """ if IRequest.providedBy(principals): principals = effective_principals(principals) elif not is_nonstr_iter(principals): principals = (principals,) return AllowsComparator(self, (principals, permission))
def test_subclass_with_implementer(self): from pyramid.interfaces import IRequest from pyramid.request import Request from pyramid.util import InstancePropertyHelper from zope.interface import implementer @implementer(IRequest) class RequestSub(Request): pass self.assertTrue(hasattr(Request, '__provides__')) self.assertTrue(hasattr(Request, '__implemented__')) self.assertTrue(hasattr(Request, '__providedBy__')) self.assertTrue(hasattr(RequestSub, '__provides__')) self.assertTrue(hasattr(RequestSub, '__providedBy__')) self.assertTrue(hasattr(RequestSub, '__implemented__')) req = RequestSub({}) helper = InstancePropertyHelper() helper.apply_properties(req, {'b': 'b'}) self.assertTrue(IRequest.providedBy(req)) self.assertTrue(IRequest.implementedBy(RequestSub))
def test_subclass(self): from pyramid.interfaces import IRequest from pyramid.request import Request class RequestSub(Request): pass self.assertTrue(hasattr(Request, '__provides__')) self.assertTrue(hasattr(Request, '__implemented__')) self.assertTrue(hasattr(Request, '__providedBy__')) self.assertFalse(hasattr(RequestSub, '__provides__')) self.assertTrue(hasattr(RequestSub, '__providedBy__')) self.assertTrue(hasattr(RequestSub, '__implemented__')) self.assertTrue(IRequest.implementedBy(RequestSub)) # The call to implementedBy will add __provides__ to the class self.assertTrue(hasattr(RequestSub, '__provides__'))
def query_layout(context, request, name=''): """ query named layout for context """ assert IRequest.providedBy(request), "must pass in a request object" try: iface = request.request_iface except AttributeError: iface = IRequest adapters = request.registry.adapters for context in lineage(context): layout_factory = adapters.lookup( (providedBy(context), iface), ILayout, name=name) if layout_factory is not None: return layout_factory, context return None, None
def embed_code_config_adapter(context: IResource, request: IRequest) -> {}: """Return mapping to render `adhocracy_core:templates/embed_code.html`.""" settings = request.registry.settings frontend_url = settings.get('adhocracy.frontend_url', 'http://localhost:6551') sdk_url = os.path.join(frontend_url, 'AdhocracySDK.js') path = request.resource_url(context) locale = settings.get('pyramid.default_locale_name', 'en') return {'sdk_url': sdk_url, 'frontend_url': frontend_url, 'path': path, 'widget': '', 'autoresize': 'false', 'locale': locale, 'autourl': 'false', 'nocenter': 'true', 'style': 'height: 650px', }
def query_layout(context, request, name=''): """ query named layout for context """ assert IRequest.providedBy(request), "must pass in a request object" try: iface = request.request_iface except AttributeError: iface = IRequest adapters = request.registry.adapters for context in lineage(context): layout_factory = adapters.lookup((providedBy(context), iface), ILayout, name=name) if layout_factory is not None: return layout_factory, context return None, None
def embed_code_config_adapter(context: IResource, request: IRequest) -> {}: """Return mapping to render `adhocracy_core:templates/embed_code.html`.""" settings = request.registry['config'] frontend_url = settings.adhocracy.frontend_url sdk_url = os.path.join(frontend_url, 'AdhocracySDK.js') path = request.resource_url(context, route_name=API_ROUTE_NAME) # TODO use frontend.locale instead locale = settings.configurator.pyramid.default_locale_name return { 'sdk_url': sdk_url, 'frontend_url': frontend_url, 'path': path, 'widget': '', 'autoresize': 'false', 'locale': locale, 'autourl': 'false', 'initial_url': '', 'nocenter': 'true', 'noheader': 'false', 'style': 'height: 650px', }
def embed_code_config_adapter(context: IResource, request: IRequest) -> {}: """Return mapping to render `adhocracy_core:templates/embed_code.html`.""" settings = request.registry['config'] frontend_url = settings.adhocracy.frontend_url sdk_url = os.path.join(frontend_url, 'AdhocracySDK.js') path = request.resource_url(context, route_name=API_ROUTE_NAME) # TODO use frontend.locale instead locale = settings.configurator.pyramid.default_locale_name return {'sdk_url': sdk_url, 'frontend_url': frontend_url, 'path': path, 'widget': '', 'autoresize': 'false', 'locale': locale, 'autourl': 'false', 'initial_url': '', 'nocenter': 'true', 'noheader': 'false', 'style': 'height: 650px', }
def __init__(self, request): if isinstance(request, self.__class__): # for some rare cases this makes sense request = request.request # make sure yafowil is testable inside pyramid environment pyramid_req = IRequest is not None and IRequest.providedBy(request) if not isinstance(request, BaseRequest) \ and not pyramid_req \ and request is not UNSET \ and request.__class__ is not dict: raise ValueError( 'Expecting object based on webob.request.BaseRequest') self.request = request if pyramid_req: self.mixed = request.params elif request is UNSET: self.mixed = dict() elif request.__class__ is dict: self.mixed = dict() else: self.mixed = request.params.mixed()
def _validate_request_data(context: IResource, request: IRequest, schema: colander.Schema): """Validate request data. :param context: passed to validator functions :param request: passed to validator functions :param schema: Schema to validate. Data to validate is extracted from the request.body. For schema nodes with attribute `location` == `querystring` the data is extracted from the query string. The validated data (dict or list) is stored in the `request.validated` attribute. :raises HTTPBadRequest: HTTP 400 for bad request data. """ body = {} if request.content_type == 'multipart/form-data': body = unflatten_multipart_request(request) if request.content_type == 'application/json': body = _extract_json_body(request) qs = _extract_querystring(request) _validate_body_or_querystring(body, qs, schema, context, request) if request.errors: request.validated = {} raise HTTPBadRequest()
def test_instance_provides(self): from pyramid.interfaces import IRequest inst = self._makeOne({}) self.assertTrue(IRequest.providedBy(inst))
def test_class_implements(self): from pyramid.interfaces import IRequest klass = self._getTargetClass() self.assertTrue(IRequest.implementedBy(klass))
def copy_header_if_exists(self, header: str, request: IRequest): """Copy header if exists.""" value = self.request.headers.get(header, None) if value is not None: request.headers[header] = value
def get_oauth_login_service(request: IRequest) -> IOAuthLoginService: assert IRequest.providedBy(request) return request.registry.queryAdapter(request, IOAuthLoginService)
def get_credential_activity_service(request: IRequest) -> ICredentialActivityService: assert IRequest.providedBy(request) return request.registry.queryAdapter(request, ICredentialActivityService)
def get_registration_service(request: IRequest) -> IRegistrationService: assert IRequest.providedBy(request) return request.registry.queryAdapter(request, IRegistrationService)
def get_credential_activity_service( request: IRequest) -> ICredentialActivityService: assert IRequest.providedBy(request) return request.registry.queryAdapter(request, ICredentialActivityService)