core.request
============

.. py:module:: core.request


Attributes
----------

.. autoapisummary::

   core.request._BaseRequest
   core.request._T
   core.request._F


Classes
-------

.. autoapisummary::

   core.request.Message
   core.request.ReturnToMixin
   core.request.CoreRequest


Functions
---------

.. autoapisummary::

   core.request.is_logged_in


Module Contents
---------------

.. py:data:: _BaseRequest

.. py:data:: _T

.. py:data:: _F

.. py:class:: Message

   Bases: :py:obj:`NamedTuple`


   .. py:attribute:: text
      :type:  str


   .. py:attribute:: type
      :type:  onegov.core.types.MessageType


.. py:class:: ReturnToMixin(environ, app, **kw)

   Bases: :py:obj:`_BaseRequest`


   Provides a safe and convenient way of using return-to links.

   Return-to links are links with an added 'return-to' query parameter
   which points to the url a specific view (usually with a form) should
   return to, once all is said and done.

   There's no magic involved. If a view should honor the return-to
   paramter, it should use request.redirect instead of morepath.redirect.

   If no return-to parameter was specified, rqeuest.redirect is a
   transparent proxy to morepath.redirect.

   To create a link::

       url = request.return_to(original_url, redirect)

   To honor the paramter in a view, if present::

       return request.redirect(default_url)

   *Do not use the return-to parameter directly*. Redirect parameters
   are notorious for being used in phising attacks. By using ``return_to``
   and ``redirect`` you are kept safe from these attacks as the redirect
   url is signed and verified.

   For the same reason you should not allow the user-data for return-to
   links. Those are meant for internally generated links!



   .. py:property:: identity_secret
      :type: str

      :abstractmethod:



   .. py:property:: redirect_signer
      :type: itsdangerous.URLSafeSerializer



   .. py:method:: sign_url_for_redirect(url: str) -> str


   .. py:method:: return_to(url: str, redirect: str) -> str


   .. py:method:: return_here(url: str) -> str


   .. py:method:: redirect(url: str) -> webob.Response


.. py:function:: is_logged_in(identity: morepath.authentication.Identity | morepath.authentication.NoIdentity) -> TypeGuard[morepath.authentication.Identity]

.. py:class:: CoreRequest(*args, **kwargs)

   Bases: :py:obj:`more.webassets.core.IncludeRequest`, :py:obj:`more.content_security.ContentSecurityRequest`, :py:obj:`ReturnToMixin`


   Extends the default Morepath request with virtual host support and
   other useful methods.

   Virtual hosting might be supported by Morepath directly in the future:
   https://github.com/morepath/morepath/issues/185



   .. py:attribute:: app
      :type:  onegov.core.Framework

      :class:`morepath.App` instance currently handling request.
              



   .. py:property:: identity_secret
      :type: str



   .. py:property:: session
      :type: sqlalchemy.orm.Session



   .. py:method:: link_prefix(app: onegov.core.Framework | None = None) -> str

      Override the `link_prefix` with the application base path provided
      by onegov.server, because the default link_prefix contains the
      hostname, which is not useful in our case - we'll add the hostname
      ourselves later.




   .. py:property:: x_vhm_host
      :type: str


      Return the X_VHM_HOST variable or an empty string.

      X_VHM_HOST acts like a prefix to all links generated by Morepath.
      If this variable is not empty, it will be added in front of all
      generated urls.



   .. py:property:: x_vhm_root
      :type: str


      Return the X_VHM_ROOT variable or an empty string.

      X_VHM_ROOT is a bit more tricky than X_VHM_HOST. It tells Morepath
      where the root of the application is situated. This means that the
      value of X_VHM_ROOT must be an existing path inside of Morepath.

      We can understand this best with an example. Let's say you have a
      Morepath application that serves a blog under /blog. You now want to
      serve the blog under a separate domain, say blog.example.org.

      If we just served Morepath under blog.example.org, we'd get urls like
      this one::

          blog.example.org/blog/posts/2014-11-17-16:00

      In effect, this subdomain would be no different from example.org
      (without the blog subdomain). However, we want the root of the host to
      point to /blog.

      To do this we set X_VHM_ROOT to /blog. Morepath will then automatically
      return urls like this::

          blog.example.org/posts/2014-11-17-16:00




   .. py:property:: path_url
      :type: str


      Returns the path_url, taking the virtual hosting in account. 



   .. py:property:: application_url
      :type: str


      Extends the default application_url with virtual host suport. 



   .. py:method:: transform(url: str) -> str

      Applies X_VHM_HOST and X_VHM_ROOT to the given url (which is
      expected to not contain a host yet!). 



   .. py:method:: link(obj: None, name: str = ..., default: None = ..., app: onegov.core.Framework | dectate.Sentinel = ..., query_params: _typeshed.SupportsItems[str, str] | None = ..., fragment: str | None = ...) -> None
                  link(obj: None, name: str, default: _T, app: onegov.core.Framework | dectate.Sentinel = ..., query_params: _typeshed.SupportsItems[str, str] | None = ..., fragment: str | None = ...) -> _T
                  link(obj: object, name: str = ..., default: Any = ..., app: onegov.core.Framework | dectate.Sentinel = ..., query_params: _typeshed.SupportsItems[str, str] | None = ..., fragment: str | None = ...) -> str

      Extends the default link generating function of Morepath. 



   .. py:method:: class_link(model: type[Any], variables: dict[str, Any] | None = None, name: str = '', app: onegov.core.Framework | dectate.Sentinel = SAME_APP) -> str

      Extends the default class link generating function of Morepath. 



   .. py:method:: filestorage_link(path: str) -> str | None

      Takes the given filestorage path and returns an url if the path
      exists. The url might point to the local server or it might point to
      somehwere else on the web.




   .. py:property:: theme_link
      :type: str


      Returns the link to the current theme. Computed once per request.

      The theme is automatically compiled and stored if it doesn't exist yet,
      or if it is outdated.




   .. py:method:: get_session_nonce() -> str

      Returns a nonce that can be passed as a POST parameter
      to restore a session in a context where the session cookie
      is unavailable, due to `SameSite=Lax`.



   .. py:property:: browser_session
      :type: onegov.core.browser_session.BrowserSession


      Returns a browser_session bound to the request. Works via cookies,
      so requests without cookies won't be able to use the browser_session.

      The browser session is bound to the application (by id), so no session
      data is shared between the applications.

      If no data is written to the browser_session, no session_id cookie
      is created.

      The session_id is rotated when users log in but not when they log out,
      that way we can still identify them and send messages when they log
      out.




   .. py:method:: get_form(form_class: type[_F], i18n_support: bool = True, csrf_support: bool = True, data: dict[str, Any] | None = None, model: object = None, formdata: webob.multidict.MultiDict[str, str | webob.request._FieldStorageWithFile] | None = None) -> _F

      Returns an instance of the given form class, set up with the
      correct translator and with CSRF protection enabled (the latter
      doesn't work yet).

      Form classes passed to this function (or defined through the
      ``App.form`` directive) may define a ``on_request`` method, which
      is called after the request has been bound to the form and before
      the view function is called.




   .. py:method:: translate(text: markupsafe.Markup | onegov.core.i18n.translation_string.TranslationMarkup) -> markupsafe.Markup
                  translate(text: str) -> str

      Translates the given text, if it's a translatable text. Also
      translates mappings. 



   .. py:property:: translator
      :type: collections.abc.Callable[[str], str]


      Returns the translate function for basic string translations. 



   .. py:property:: default_locale
      :type: str | None


      Returns the default locale. 



   .. py:property:: locale
      :type: str | None


      Returns the current locale of this request. 



   .. py:property:: html_lang
      :type: str


      The language code for the html tag. 



   .. py:method:: get_translate(for_chameleon: Literal[False] = False) -> gettext.GNUTranslations | None
                  get_translate(for_chameleon: Literal[True]) -> translationstring._ChameleonTranslate | None

      Returns the translate method to the given request, or None
      if no such method is availabe.

      :for_chameleon:
          True if the translate instance is used for chameleon (which is
          special).




   .. py:method:: message(text: str, type: onegov.core.types.MessageType) -> None

      Adds a message with the given type to the messages list. This
      messages list may then be displayed by an application building on
      onegov.core.

      For example::

          http://foundation.zurb.com/docs/components/alert_boxes.html

      Four default types are defined on the request for easier use:

      :meth:`success`
      :meth:`warning`
      :meth:`info`
      :meth:`alert`

      The messages are stored with the session and to display them, the
      template using the messages should call :meth:`consume_messages`.




   .. py:method:: consume_messages() -> collections.abc.Iterator[Message]

      Returns the messages, removing them from the session in the
      process. Call only if you can be reasonably sure that the user
      will see the messages.




   .. py:method:: success(text: str) -> None

      Adds a success message. 



   .. py:method:: warning(text: str) -> None

      Adds a warning message. 



   .. py:method:: info(text: str) -> None

      Adds an info message. 



   .. py:method:: alert(text: str) -> None

      Adds an alert message. 



   .. py:property:: is_logged_in
      :type: bool


      Returns True if the current request is logged in at all. 



   .. py:property:: agent
      :type: ua_parser.DefaultedResult


      Returns the user agent, parsed by ua-parser. 



   .. py:method:: has_permission(model: object, permission: type[onegov.core.security.permissions.Intent] | None, user: UserLike | None = None) -> bool

      Returns True if the current or given user has the given permission
      on the given model.




   .. py:method:: has_access_to_url(url: str) -> bool

      Returns true if the current user has access to the given url.

      The domain part of the url is completely ignored. This method should
      only be used if you have no other choice. Loading the object by
      url first is slower than if you can get the object otherwise.

      The initial use-case for this function is the to parameter in the
      login view. If the to-url is accessible anyway, we skip the login
      view.

      If we can't find a view for the url, a KeyError is thrown.




   .. py:method:: exclude_invisible(models: collections.abc.Iterable[_T]) -> list[_T]

      Excludes models invisble to the current user from the list. 



   .. py:method:: is_visible(model: object) -> bool

      Returns True if the given model is visible to the current user.

      In addition to the `is_public` check, this checks if the model is
      secret and should therefore not be visible (though it can still be
      reached via URL).




   .. py:method:: is_public(model: object) -> bool

      Returns True if the current user has the Public permission for
      the given model.




   .. py:method:: is_personal(model: object) -> bool

      Returns True if the current user has the Personal permission for
      the given model.




   .. py:method:: is_private(model: object) -> bool

      Returns True if the current user has the Private permission for
      the given model.




   .. py:method:: is_secret(model: object) -> bool

      Returns True if the current user has the Secret permission for
      the given model.




   .. py:property:: current_role
      :type: str | None


      Returns the user-role of the current request, if logged in.
      Otherwise, None is returned.




   .. py:method:: has_role(*roles: str) -> bool

      Returns true if the current user has any of the given roles. 



   .. py:property:: csrf_salt
      :type: str



   .. py:method:: new_csrf_token(salt: str | bytes | None = None) -> bytes

      Returns a new CSRF token. A CSRF token can be verified
      using :meth:`is_valid_csrf_token`.

      Note that forms do their own CSRF protection. This is meant
      for CSRF protection outside of forms.

      onegov.core uses the Synchronizer Token Pattern for CSRF protection:
      `<https://www.owasp.org/index.php/        Cross-Site_Request_Forgery_%28CSRF%29_Prevention_Cheat_Sheet>`_

      New CSRF tokens are signed usign a secret attached to the session (but
      not sent out to the user). Clients have to return the CSRF token they
      are given. The token has to match the secret, which the client doesn't
      know. So an attacker would have to get access to both the cookie and
      the html source to be able to forge a request.

      Since cookies are marked as HTTP only (no javascript access), this
      even prevents CSRF attack combined with XSS.




   .. py:property:: csrf_token
      :type: str


      Returns a csrf token for use with DELETE links (forms do their
      own thing automatically).




   .. py:method:: csrf_protected_url(url: str) -> str

      Adds a csrf token to the given url. 



   .. py:method:: assert_valid_csrf_token(signed_value: str | bytes | None = None, salt: str | bytes | None = None) -> None

      Validates the given CSRF token and returns if it was
      created by :meth:`new_csrf_token`. If there's a mismatch, a 403 is
      raised.

      If no signed_value is passed, it is taken from
      request.params.get('csrf-token').




   .. py:method:: new_url_safe_token(data: object, salt: str | bytes | None = None) -> str

      Returns a new URL safe token. A token can be deserialized
      using :meth:`load_url_safe_token`.




   .. py:method:: load_url_safe_token(data: str | bytes | None, salt: str | bytes | None = None, max_age: int = 3600) -> Any | None

      Deserialize a token created by :meth:`new_url_safe_token`.

      If the token is invalid, None is returned.




   .. py:property:: template_loader
      :type: core.templates.TemplateLoader


      Returns the chameleon template loader.