Aller au contenu

Views

ThirdPartyAuthForm(*args, label_suffix='', initial, **kwargs)

Bases: Form

Form to complete to authenticate on the sith from a third-party app.

For the form to be valid, the user approve the EULA (french: CGU) and give its username from the third-party app.

Source code in api/forms.py
def __init__(self, *args, label_suffix: str = "", initial, **kwargs):
    super().__init__(*args, label_suffix=label_suffix, initial=initial, **kwargs)
    self.fields["is_username_valid"].label = _(
        "I confirm that %(username)s is my username on %(app)s"
    ) % {"username": initial.get("username"), "app": initial.get("third_party_app")}

ApiClient

Bases: Model

has_perm(perm)

Return True if the client has the specified permission.

Source code in api/models.py
def has_perm(self, perm: str):
    """Return True if the client has the specified permission."""
    return perm in self.all_permissions

has_perms(perm_list)

Return True if the client has each of the specified permissions.

Source code in api/models.py
def has_perms(self, perm_list: Iterable[str]) -> bool:
    """Return True if the client has each of the specified permissions."""
    if not isinstance(perm_list, Iterable) or isinstance(perm_list, str):
        raise ValueError("perm_list must be an iterable of permissions.")
    return all(self.has_perm(perm) for perm in perm_list)

reset_hmac(*, commit=True)

Reset and return the HMAC key for this client.

Parameters:

Name Type Description Default
commit bool

if True (the default), persist the new hmac in db.

True
Source code in api/models.py
def reset_hmac(self, *, commit: bool = True) -> str:
    """Reset and return the HMAC key for this client.

    Args:
        commit: if True (the default), persist the new hmac in db.
    """
    self.hmac_key = get_hmac_key()
    if commit:
        self.save()
    return self.hmac_key

ThirdPartyAuthParamsSchema

Bases: Schema

ThirdPartyAuthView

Bases: AccessMixin, FormView

parse_params()

Parse and check the authentication parameters.

If parsing fails, messages will be created using the django message infrastructure.

Returns:

Type Description
ThirdPartyAuthParamsSchema | None

The parses parameters, or None if the parsing failed.

Source code in api/views.py
def parse_params(self) -> ThirdPartyAuthParamsSchema | None:
    """Parse and check the authentication parameters.

    If parsing fails, messages will be created using the django message
    infrastructure.

    Returns:
        The parses parameters, or None if the parsing failed.
    """
    # This is here rather than in ThirdPartyAuthForm because
    # the given parameters and their signature are checked during both
    # POST (for obvious reasons) and GET (in order not to make
    # the user fill a form just to get an error he won't understand)
    params = self.request.GET if self.request.method == "GET" else self.request.POST
    params = {key: unquote(val) for key, val in params.dict().items()}
    try:
        params = ThirdPartyAuthParamsSchema(**params)
    except pydantic.ValidationError:
        messages.error(
            self.request, _("The data provided for authentication is incorrect")
        )
        return None
    client: ApiClient | None = get_object_or_none(ApiClient, id=params.client_id)
    if not client:
        messages.error(
            self.request, _("The data provided for authentication is incorrect")
        )
        return None
    if not hmac.compare_digest(
        hmac_hexdigest(client.hmac_key, params.model_dump(exclude={"signature"})),
        params.signature,
    ):
        messages.error(
            self.request,
            _(
                "The signature is incorrect. "
                "We cannot ensure the provenance of the request."
            ),
        )
        return None
    return params

ThirdPartyAuthResultView

Bases: LoginRequiredMixin, TemplateView

View that the user will see if its authentication on sith was successful.

This can show either a success or a failure message : - success : everything is good, the user is successfully authenticated and can close the page - failure : the authentication has been processed on the sith side, but the request to the callback url received an error. In such a case, there is nothing much we can do but to advice the user to contact the developers of the third-party app.