Skip to content

Roles and Permissions System

Aurelien9Code edited this page Dec 6, 2024 · 1 revision

In our application, roles and permissions manage access control, enabling different users to perform specific actions based on their assigned rights. Roles are linked to users, and each role has specific permissions.

Here is a very very simple wiki, so that everyone does not get lazy be reading my PR implementing it.

To add a permission, you can simply add a line to PermissionType - an enum representing different types of permissions. Each permission corresponds to a specific string action (e.g., VIEW_EVENTS, EDIT_EVENTS, etc.). For example ADD_EVENTS("Add Events")

Permissions is a class that encapsulates a set of permissions granted to a user. It offers methods for adding, deleting, and checking permissions. Check it when you want to manage permissions. To create a Permissions object, please use PermissionsBuilder.

How Roles and Permissions Work

When a user is assigned a role (e.g., "Admin" or "Member"), they are granted a set of permissions. These permissions can be checked to see if a user is allowed to perform certain actions.

-> The hasPermission() method in the Permissions class is used to check if a user has the right to perform an action. Example:

val permissions = Permissions(mutableSetOf(PermissionType.ADD_EVENTS)) val hasAddEventPermission = permissions.hasPermission(PermissionType.ADD_EVENTS)

BE AWARE: A user with FULL_RIGHTS automatically has all the permissions, regardless of whether they are explicitly listed.

How to Implement Role and Permission Checks in a Composable

When implementing a Composable, it’s common to check the user’s permissions to determine if certain UI elements should be visible or certain actions should be allowed.

-> Retrieve the User's Permissions First, retrieve the current user's permissions. This could be fetched from the association object or user data.

val userPermissions = association.members .find { it.userId == user?.uid } ?.permissions

-> Check Permissions - Use the hasPermission method to check whether the user has the necessary permissions for a specific action.

val hasAddEventsPermission = userPermissions?.hasPermission(PermissionType.ADD_EVENTS) == true

-> Handle UI

if (hasAddEventsPermission) { Button(onClick = { navigateToAddEvent() }) { Text("Add Event") } }

Of course checking the permissions in the UI is not enough, but I will to a refactor to simply create a cloud functions to also check it server-side for each of your implementations : )