Skip to content

decorators

drunc.authoriser.decorators

Functions:

authentified_and_authorised(action, system)

Decorator to check if the user is authentified and authorised to execute a command.

Parameters:

Name Type Description Default
action ActionType

The action type to check.

required
system SystemType

The system type to check.

required

Returns:

Type Description
Callable[[C], C]

A decorator that checks if the user is authentified and authorised.

Raises:

Type Description
Unauthorised

If the user is not authorised to execute the command.

Source code in drunc/authoriser/decorators.py
def authentified_and_authorised(
    action: ActionType, system: SystemType
) -> Callable[[C], C]:
    """
    Decorator to check if the user is authentified and authorised to execute a command.

    Args:
        action: The action type to check.
        system: The system type to check.

    Returns:
        A decorator that checks if the user is authentified and authorised.

    Raises:
        Unauthorised: If the user is not authorised to execute the command.
    """

    def decor(cmd: C) -> C:
        def check_token(
            obj: _ContextProtocol,
            request: _RequestProtocol,
            context: grpc.ServicerContext,
        ) -> Response:
            log = get_logger("utils.authentified_and_authorised_decorator")
            log.debug("Entering")
            if not obj.authoriser.is_authorised(
                request.token, action, system, cmd.__name__
            ):
                return Response(
                    name=obj.name,
                    token=request.token,
                    data=pack_to_any(
                        PlainText(
                            text=f"User {request.token.user_name} is not authorised to execute {cmd.__name__} on {obj.name} (action type is {action}, system is {system})"
                        )
                    ),
                    flag=ResponseFlag.NOT_EXECUTED_NOT_AUTHORISED,
                    children=[],
                )

                # raise Unauthorised(
                #     user = request.token.user_name,
                #     action = action,
                #     command = cmd.__name__,
                #     drunc_system = obj.name,
                # )
            log.debug("Executing wrapped function")
            ret = cmd(obj, request, context)
            log.debug("Exiting")
            return ret

        return cast(C, functools.update_wrapper(check_token, cmd))

    return decor