here’s an example on the forum:
You could create your own wrapper for this:
from functools import wraps
def admin(func):
@wraps(func)
def wrapper(*args, **kwargs):
admin_role = app_tables.roles.get(name='admin')
user = anvil.users.get_user()
if user is not None and admin_role in user['roles']:
return func(*args, **kwargs)
else:
raise anvil.users.AuthenticationFailed('not an admin')
return wrapper
@anvil.server.callable
@admin
def get_data_for_admin():
user = anvil.users.g…
Notice the use of the @wraps
decorator to ensure that the wrapped function keeps it’s name when it is wrapped.
This saves you having to declare the name explicitly
def custom_wrapper(fn):
@wraps(fn)
def wrapper(*args, **kws):
... #custom logic
return fn(*args, **kws)
return wrapper
And worth remembering the require_user
argument which is often sufficient for authentication
Hi @Tony.Nguyen ,
You can also further customise the @anvil.server.callable decorator. require_user can take a boolean value, or a function. That function will receive the currently logged-in user (the return value of anvil.users.get_user()). For example, if your Users table has a boolean column called ‘admin’, you could restrict your server functions to admin users like this:
Using a lambda function:
@anvil.server.callable(require_user = lambda u: u['admin'])
or a regular function:
def vali…
3 Likes