flexmeasures.auth.decorators

Auth decorators for endpoints

Functions

flexmeasures.auth.decorators.account_roles_accepted(*account_roles)

Decorator which specifies that a user’s account must have at least one of the specified roles (or must be an admin). Example:

@app.route(‘/postMeterData’) @account_roles_accepted(‘Prosumer’, ‘MDC’) def post_meter_data():

return ‘Meter data posted’

The current user’s account must have either the Prosumer role or MDC role in order to use the service.

Parameters:

account_roles – The possible roles.

flexmeasures.auth.decorators.account_roles_required(*account_roles)

Decorator which specifies that a user’s account must have all the specified roles. Example:

@app.route('/dashboard')
@account_roles_required('Prosumer', 'App-subscriber')
def dashboard():
    return 'Dashboard'

The current user’s account must have both the Prosumer role and App-subscriber role in order to view the page.

Parameters:

roles – The required roles.

flexmeasures.auth.decorators.permission_required_for_context(permission: str, arg_pos: int | None = None, arg_name: str | None = None, arg_loader: Callable | None = None)

This decorator can be used to make sure that the current user has the necessary permission to access the context. The context needs to be an AuthModelMixin and is found … - by loading it via the arg_loader callable; - otherwise:

  • by the keyword argument arg_name;

  • and/or by a position in the non-keyword arguments (arg_pos).

If nothing is passed, the context lookup defaults to arg_pos=0.

Using both arg_name and arg_pos arguments is useful when Marshmallow de-serializes to a dict and you are using use_args. In this case, the context lookup applies first arg_pos, then arg_name.

The permission needs to be a known permission and is checked with principal descriptions from the context’s access control list (see AuthModelMixin.__acl__).

Usually, you’d place a marshmallow field further up in the decorator chain, e.g.:

@app.route(“/resource/<resource_id>”, methods=[“GET”]) @use_kwargs(

{“the_resource”: ResourceIdField(data_key=”resource_id”)}, location=”path”,

) @permission_required_for_context(“read”, arg_name=”the_resource”) @as_json def view(resource_id: int, the_resource: Resource):

return dict(name=the_resource.name)

Where ResourceIdField._deserialize() turns the id parameter into a Resource context (if possible).

This decorator raises a 403 response if there is no principal for the required permission. It raises a 401 response if the user is not authenticated at all.

flexmeasures.auth.decorators.roles_accepted(*roles)

As in Flask-Security, but also accept admin

flexmeasures.auth.decorators.roles_required(*roles)

As in Flask-Security, but wave through if user is admin