Access Permissions
Learn how to control or implement the access restriction functionality on our Vue application.
We'll cover the following...
This section doesn’t exactly address app security, but if our application has different roles for users, then we might want to prevent a user from accessing certain pages or features on the client-side.
Objectives
In this section, we’ll cover:
-
How to restrict access to the comments section when a user isn’t logged in.
-
How to restrict access to the edit comment button to a user who is an author, moderator, or admin.
-
How to restrict access to moderators and admins-only pages.
-
How to restrict access to the admins-only page.
First, let’s create a few necessary files for demonstration. We can create a new Vue 3 project from scratch if we want to follow along with the example below or have a look at the Companion App.
Directory structure
These are the files we’ll need to create or modify in this example:
Implementation
There will be two main ways of restricting access to pages and features. These are the <Permission />
component and checkPermission
function. Let’s think about how exactly they should work and what arguments they should accept. For this example, we’ll have a moderator and an admin role. However, there are also other situations when a user’s access could be restricted. For instance, if a user isn’t logged in, then they should not be able to visit and see certain pages or content. Another example would be allowing users to edit their own content, but not content posted by other users. From here on, we’ll refer to any content record that could be created and owned by a user, such as a blog post or a comment, as an entity.
Permission checks must be able to handle these rules:
- Is the user authenticated?
- Is the user an owner of an entity?
- Does the user have a specific role or roles?
Below we can see how the <Permission />
component and the checkPermission
function are used after they’re implemented.
The Permission
component
<Permission :roles="['logged-in', 'owner', 'moderator', 'admin']" type="one-of" :entityOwnerId="entityOwnerId" debug><p>This content is displayed if a user has access permissions.</p><template #no-access><p>This content is displayed if a user doesn't have access permissions.</p></template></Permission>
The Permission
component accepts four props. These are an array of required roles, a type
of permission check—whether we want to match just one role or all of them, an entityOwnerId
to check if a user is an owner of an ...