Role authorization
Authorization refers to the process that determines what a user is able to do. For example, an administrative user is allowed to create, edit, and delete posts. A non-administrative user is only authorized to read the posts.
Basic RBAC implementation
- Step 1: Install a simple permission verification package provided by
Zerone
yarn add @zeronejs/role-easy
1
- Step 2: let's create a Role enum representing roles in the system
TIP
It is common/role/enums.ts
export enum Role {
User = 'user',
Admin = 'admin',
}
1
2
3
4
2
3
4
- Step 3: Import RolesModule into the root module
import { RolesModule } from '@zeronejs/role-easy';
@Module({
imports: [
RolesModule,
// ... Other modules
]
})
export class AppModule {}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
- Step 4: Add the Roles decorator to the interface that requires permission validation
import { Roles } from '@zeronejs/role-easy';
import { Role } from './common/role/enums';
...
@Get()
@Roles(Role.Admin)
getHello(): string {
return this.appService.getHello();
}
...
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
TIP
In this example, we assumed that request.user
contains the user instance and allowed roles (under the roles
property).
To make sure this example works, your User
class must look as follows:
class User {
// ...other properties
roles: Role[];
}
1
2
3
4
2
3
4