The Users service handles user management. You can display a login and signup form by running:
There are lower-level functions to implement specific parts of user management workflow. For example,
anvil.users.signup_with_email(username, password) executes the user signup (this runs in the browser - the password is hashed before it leaves the user’s machine).
User records are stored in Data Tables, in a table named Users.
To control user access to UI elements, you can selectively hide them based on a user role. Create a column in the Users table named
role, then get the logged-in user by running:
This returns a Row from the Users table. Here’s an example of selectively displaying a component depending on the user’s role:
user = anvil.users.get_user() if user is not None and user['role'] == 'admin': self.admin_panel.visible = True else: self.admin_panel.visible = False
In this example,
self.admin_panel is a container, and all the components within it are hidden when it is hidden.
Here’s an example of allowing access to a particular screen for only users with particular roles:
user = anvil.users.get_user() if user is not None and user['role'] in ('admin', 'trusted'): # Show the stats dashboard for trusted users. open_form(StatsDashboard()) else: # Display the permission denied error self.label_permission_denied.visible = True
Of course, you can control access based on any data about the user. You could give access to an invidual user by checking
user[‘email'] == firstname.lastname@example.org, or even prevent access for users older than 30 days by checking
user[‘signed_up’] > datetime.now() - datetime.timedelta(days=30).
Selectively displaying menu elements based on user roles is the same as selectively displaying sections of screens. Just run a method that iterates over the components you want to show, and set their
visible property based on the user role. For example:
# These are links that perform actions only admins can do. admin_options = [ self.link_generate_reports, self.link_flush_cache, self.link_email_customers, ] user = anvil.users.get_user() if user is not None and user['role'] == 'admin': # This user is an admin; show them the admin options for option in admin_options: option.visible = True else: # Not an admin; don't show the admin options. for option in admin_options: option.visible = False