Permissions

Learn how to write a simple permissions system with Makerkit

Most of the permissions are written in a single file at src/lib/organizations/permissions.ts.

Here, you can find some of the examples used in the boilerplate so that you can start writing your own.

Why are permissions written in a single file? Because it's easy to write inline logic and lose track of it. Therefore, we will write all the logic within the same file and encapsulated as simple functions.

Let's take a look at a simple permission function in the boilerplate:

/**
 *
 * @param currentUserRole The current logged-in user
 * @param targetUser The role of the target of the action
 * @description Checks if a user can perform actions (such as update a role) of another user
 * @name canUpdateUser
 */
export function canUpdateUser(
  currentUserRole: MembershipRole,
  targetUser: MembershipRole
) {
  return currentUserRole > targetUser;
}

The function takes two parameters: the current user's role, and the target user's role, and checks if the current user can update the role (or anything) of the target user.

Now, we can use the function above with the IfHasPermissions component to display or hide some parts of the application. This component automatically injects the current user's role, such as below:

<IfHasPermissions
  condition={(currentUserRole) =>
    canInviteUser(currentUserRole, targetUserRole)
  }
>
  <InviteUserComponent />
</IfHasPermissions>

If the condition is truthy, then the InviteUserComponent component will be displayed.

Otherwise, you can use these functions throughout the application, both on the client and on the server.

Let's assume we want to allow only paying users to perform a certain action:

export function isPayingUser(
  subscription: Maybe<OrganizationSubscription>
) {
  return (
    subscription?.status === OrganizationSubscriptionStatus.Paid
  );
}

function isAdmin(
  role: MembershipRole
) {
  return role === MembershipRole.Admin;
}

Now, combine this function with other conditions:

export function canCreateNewThing(
  subscription: Maybe<OrganizationSubscription>,
  userRole: MembershipRole,
) {
  return isPayingUser(subscription) && isAdmin(userRole);
}

Stay informed with our latest resources for building a SaaS

Subscribe to our newsletter to receive updatesor