-1
@app.route('/<string:charity_id>/glc')
# @roles_accepted('admin',charity_id[:3])
def GLC(charity_id):
    ...
    ...
    return render_template('one.html',charity_id=charity_id)

Is there a way of allowing a role, as defined by first 3 characters of the charity_id i.e. charity_id[:3]. At present, if the comment line is uncommented, charity_id is not defined and therefore doesn't work.

I am trying to allow someone with role 'admin' or 'charity_id[:3]' onto the page. Each user is assigned a role in flask security protocol. I am trying to test whether the persons allowed onto the page based on the page id i.e. string:charity_id

Many thanks

tedioustortoise
  • 259
  • 3
  • 20

1 Answers1

0

I don’t know what it is for, but as you can see @roles_accepted decorator works only with roles and runs endpoint only when perm.can().

You can create a custom decorator (just an example):

def custom_roles(roles: list, path_param: str):
    def wrapper(fn):
        @roles_accepted(*roles)  # just roles like in docs
        @wraps(fn)
        def decorated_view(*args, **kwargs):
            # try to open /100-test/glc
            sub_charity_id = kwargs.get(path_param)[:3]  # 100
            # call route using roles_accepted decorator and path param
            fn2 = roles_accepted(*[sub_charity_id])(fn)
            return fn2(*args, **kwargs)
        return decorated_view
    return wrapper


@app.route('/<string:charity_id>/glc')
@custom_roles(roles=['admin'], path_param='charity_id')
def glc(charity_id):
    return 'test'

Or call roles_accepted inside route:

def do_something(charity_id: str):
    return charity_id


@app.route('/<string:charity_id>/glc')
@roles_accepted('admin', 'editor')
def glc(charity_id):
    fn = roles_accepted(*[charity_id[:3]])(do_something)
    return fn(charity_id)

Hope this helps.

Danila Ganchar
  • 10,266
  • 13
  • 49
  • 75