Exemple #1
0
 async def __aexit__(self, *args):
     set_authenticated_user(None)
     # make sure to close out connection
     await self.abort()
Exemple #2
0
 async def __aenter__(self):
     task_vars.request.set(self.request)
     task_vars.db.set(self.db)
     set_authenticated_user(self.user)
     return self
Exemple #3
0
def logout():
    set_authenticated_user(None)
Exemple #4
0
    async def real_resolve(self, request: IRequest) -> Optional[MatchInfo]:
        """Main function to resolve a request."""
        if request.method not in app_settings["http_methods"]:
            raise HTTPMethodNotAllowed(
                method=request.method,
                allowed_methods=[
                    k for k in app_settings["http_methods"].keys()
                ])
        method = app_settings["http_methods"][request.method]

        try:
            resource, tail = await self.traverse(request)
        except ConflictError:
            # can also happen from connection errors so we bubble this...
            raise
        except Exception as _exc:
            logger.error("Unhandled exception occurred", exc_info=True)
            request.resource = request.tail = None
            request.exc = _exc
            data = {
                "success": False,
                "exception_message": str(_exc),
                "exception_type": getattr(type(_exc), "__name__",
                                          str(type(_exc))),  # noqa
            }
            if app_settings.get("debug"):
                data["traceback"] = traceback.format_exc()
            raise HTTPBadRequest(content={"reason": data})

        request.record("traversed")

        request.resource = resource
        request.tail = tail

        if tail and len(tail) > 0:
            # convert match lookups
            view_name = routes.path_to_view_name(tail)
        elif not tail:
            view_name = ""

        request.record("beforeauthentication")
        authenticated = await authenticate_request(request)
        # Add anonymous participation
        if authenticated is None:
            authenticated = AnonymousUser()
            set_authenticated_user(authenticated)
        request.record("authentication")

        policy = get_security_policy(authenticated)

        for language in get_acceptable_languages(request):
            translator = query_adapter((resource, request),
                                       ILanguage,
                                       name=language)
            if translator is not None:
                resource = translator.translate()
                break

        # container registry lookup
        try:
            view = query_multi_adapter((resource, request),
                                       method,
                                       name=view_name)
        except AttributeError:
            view = None

        if view is None and method == IOPTIONS:
            view = DefaultOPTIONS(resource, request)

        # Check security on context to AccessContent unless
        # is view allows explicit or its OPTIONS
        permission = get_utility(IPermission, name="guillotina.AccessContent")
        if not policy.check_permission(permission.id, resource):
            # Check if its a CORS call:
            if IOPTIONS != method:
                # Check if the view has permissions explicit
                if view is None or not view.__allow_access__:
                    logger.info(
                        "No access content {content} with {auth}".format(
                            content=resource, auth=authenticated.id),
                        request=request,
                    )
                    raise HTTPUnauthorized(
                        content={
                            "reason":
                            "You are not authorized to access content",
                            "content": str(resource),
                            "auth": authenticated.id,
                        })

        if not view and len(tail) > 0:
            # we should have a view in this case because we are matching routes
            await notify(TraversalViewMissEvent(request, tail))
            raise HTTPNotFound(
                content={"reason": "object and/or route not found"})

        request.found_view = view
        request.view_name = view_name
        request.record("viewfound")

        ViewClass = view.__class__
        view_permission = get_view_permission(ViewClass)
        if view_permission is None:
            # use default view permission
            view_permission = app_settings["default_permission"]
        if not policy.check_permission(view_permission, view):
            if IOPTIONS != method:
                raise HTTPUnauthorized(
                    content={
                        "reason": "You are not authorized to view",
                        "content": str(resource),
                        "auth": authenticated.id,
                    })

        try:
            view.__route__.matches(request, tail or [])
        except (KeyError, IndexError):
            await notify(TraversalRouteMissEvent(request, tail))
            return None
        except AttributeError:
            pass

        await notify(ObjectLoadedEvent(resource))

        if hasattr(view, "prepare"):
            view = (await view.prepare()) or view

        request.record("authorization")

        return MatchInfo(resource, request, view)
Exemple #5
0
def login(*, user=RootUser("foobar")):
    set_authenticated_user(user)