core.request

Attributes

_BaseRequest

_T

_F

Classes

Message

ReturnToMixin

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

CoreRequest

Extends the default Morepath request with virtual host support and

Functions

is_logged_in(→ TypeGuard[Identity])

Module Contents

core.request._BaseRequest[source]
core.request._T[source]
core.request._F[source]
class core.request.Message[source]

Bases: NamedTuple

text: str[source]
type: onegov.core.types.MessageType[source]
class core.request.ReturnToMixin(environ, app, **kw)[source]

Bases: _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!

property identity_secret: str[source]
Abstractmethod:

property redirect_signer: itsdangerous.URLSafeSerializer[source]
sign_url_for_redirect(url: str) str[source]
return_to(url: str, redirect: str) str[source]
return_here(url: str) str[source]
redirect(url: str) webob.Response[source]
core.request.is_logged_in(identity: Identity | NoIdentity) TypeGuard[Identity][source]
class core.request.CoreRequest(*args, **kwargs)[source]

Bases: more.webassets.core.IncludeRequest, more.content_security.ContentSecurityRequest, 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

app: onegov.core.Framework[source]

morepath.App instance currently handling request.

property identity_secret: str[source]
property session: sqlalchemy.orm.Session[source]

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.

property x_vhm_host: str[source]

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.

property x_vhm_root: str[source]

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
property path_url: str[source]

Returns the path_url, taking the virtual hosting in account.

property application_url: str[source]

Extends the default application_url with virtual host suport.

transform(url: str) str[source]

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

link(obj: None, name: str, default: _T, app: Framework | Sentinel = ..., query_params: SupportsItems[str, str] | None = ..., fragment: str | None = ...) _T
link(obj: object, name: str = ..., default: Any = ..., app: Framework | Sentinel = ..., query_params: SupportsItems[str, str] | None = ..., fragment: str | None = ...) str

Extends the default link generating function of Morepath.

Extends the default class link generating function of Morepath.

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.

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.

property browser_session: onegov.core.browser_session.BrowserSession[source]

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.

get_form(form_class: type[_F], i18n_support: bool = True, csrf_support: bool = True, data: dict[str, Any] | None = None, model: object = None, formdata: MultiDict[str, str | _FieldStorageWithFile] | None = None) _F[source]

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.

translate(text: Markup | TranslationMarkup) markupsafe.Markup[source]
translate(text: str) str

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

property translator: Callable[[str], str][source]

Returns the translate function for basic string translations.

property default_locale: str | None[source]

Returns the default locale.

property locale: str | None[source]

Returns the current locale of this request.

property html_lang: str[source]

The language code for the html tag.

get_translate(for_chameleon: Literal[False] = False) GNUTranslations | None[source]
get_translate(for_chameleon: Literal[True]) _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).

message(text: str, type: onegov.core.types.MessageType) None[source]

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:

success() warning() info() alert()

The messages are stored with the session and to display them, the template using the messages should call consume_messages().

consume_messages() Iterator[Message][source]

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.

success(text: str) None[source]

Adds a success message.

warning(text: str) None[source]

Adds a warning message.

info(text: str) None[source]

Adds an info message.

alert(text: str) None[source]

Adds an alert message.

property is_logged_in: bool[source]

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

property agent: Any[source]

Returns the user agent, parsed by ua-parser.

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

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

has_access_to_url(url: str) bool[source]

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.

exclude_invisible(models: Iterable[_T]) list[_T][source]

Excludes models invisble to the current user from the list.

is_visible(model: object) bool[source]

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).

is_public(model: object) bool[source]

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

is_personal(model: object) bool[source]

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

is_private(model: object) bool[source]

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

is_secret(model: object) bool[source]

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

property current_role: str | None[source]

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

has_role(*roles: str) bool[source]

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

property csrf_salt: str[source]
new_csrf_token(salt: str | bytes | None = None) bytes[source]

Returns a new CSRF token. A CSRF token can be verified using 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.

assert_valid_csrf_token(signed_value: str | bytes | None = None, salt: str | bytes | None = None) None[source]

Validates the given CSRF token and returns if it was created by 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’).

new_url_safe_token(data: object, salt: str | bytes | None = None) str[source]

Returns a new URL safe token. A token can be deserialized using load_url_safe_token().

load_url_safe_token(data: str | bytes | None, salt: str | bytes | None = None, max_age: int = 3600) Any | None[source]

Deserialize a token created by new_url_safe_token().

If the token is invalid, None is returned.

property template_loader: core.templates.TemplateLoader[source]

Returns the chameleon template loader.