Ejemplo n.º 1
0
    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,
        )
Ejemplo n.º 2
0
    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)
Ejemplo n.º 3
0
    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)
Ejemplo n.º 4
0
    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)
Ejemplo n.º 5
0
    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)
Ejemplo n.º 6
0
    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)
Ejemplo n.º 7
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)
Ejemplo n.º 8
0
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)
Ejemplo n.º 9
0
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)
Ejemplo n.º 10
0
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]
Ejemplo n.º 11
0
    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
Ejemplo n.º 12
0
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))
Ejemplo n.º 13
0
    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
Ejemplo n.º 14
0
 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)
Ejemplo n.º 15
0
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
Ejemplo n.º 16
0
 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
Ejemplo n.º 17
0
    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))
Ejemplo n.º 18
0
    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))
Ejemplo n.º 19
0
    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))
Ejemplo n.º 20
0
    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))
Ejemplo n.º 21
0
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
Ejemplo n.º 22
0
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
Ejemplo n.º 23
0
 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()
Ejemplo n.º 24
0
    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))
Ejemplo n.º 25
0
    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))
Ejemplo n.º 26
0
 def test_instance_provides(self):
     from pyramid.interfaces import IRequest
     inst = self._makeOne({})
     self.assertTrue(IRequest.providedBy(inst))
Ejemplo n.º 27
0
def get_credential_activity_service(request: IRequest) -> ICredentialActivityService:
    assert IRequest.providedBy(request)
    return request.registry.queryAdapter(request, ICredentialActivityService)
Ejemplo n.º 28
0
def get_registration_service(request: IRequest) -> IRegistrationService:
    assert IRequest.providedBy(request)
    return request.registry.queryAdapter(request, IRegistrationService)
Ejemplo n.º 29
0
def get_credential_activity_service(
        request: IRequest) -> ICredentialActivityService:
    assert IRequest.providedBy(request)
    return request.registry.queryAdapter(request, ICredentialActivityService)
Ejemplo n.º 30
0
def get_oauth_login_service(request: IRequest) -> IOAuthLoginService:
    assert IRequest.providedBy(request)
    return request.registry.queryAdapter(request, IOAuthLoginService)
Ejemplo n.º 31
0
def get_oauth_login_service(request: IRequest) -> IOAuthLoginService:
    assert IRequest.providedBy(request)
    return request.registry.queryAdapter(request, IOAuthLoginService)
Ejemplo n.º 32
0
 def test_instance_provides(self):
     from pyramid.interfaces import IRequest
     inst = self._makeOne({})
     self.assertTrue(IRequest.providedBy(inst))
Ejemplo n.º 33
0
def get_registration_service(request: IRequest) -> IRegistrationService:
    assert IRequest.providedBy(request)
    return request.registry.queryAdapter(request, IRegistrationService)