Authorization
With SugoiJS Authorization check is that simple.

Overview

1
/**
2
* requiredRole: TStringOrNumber|TStringOrNumber[] - The required role(s)
3
* permissions: TStringOrNumber|TStringOrNumber[] - The required premission(s)
4
* failedCode: number - The response code in case the policy will fail
5
**/
6
Authorized(requiredRole: TStringOrNumber|TStringOrNumber[] = null, permissions: TStringOrNumber|TStringOrNumber[] = null, failedCode: number = 401)
Copied!
The Authorized decorator use for validate if the user is authorized and in the right role & have the right permissions(optional).
In case null will pass the value won't be checked.

Initialize

The Authorized policy will use the AuthProvider which pass while the server init: init(boostrapModule: any, rootPath?: string, moduleMetaKey?: string, authProvider?: AuthProvider)
The AuthProvider will init for each request, the AuthProvider holding the request headers & cookies.

Example

authorization.class.ts
app.ts
dashboard.controller.ts
1
export class Authorization extends AuthProvider<User> {
2
3
4
/**
5
* Verify if user is authorized
6
*
7
* Implemented dummy check for x-sug-demo header to be equal to "Wyn1RRR9PQJPaqYM"
8
*
9
* @returns {Promise<boolean>}
10
*/
11
isAuthenticated(): Promise<boolean> {
12
return Promise.resolve(this.headers["x-sug-demo"] === "Wyn1RRR9PQJPaqYM");
13
}
14
15
getUser(req?: e.Request, res?: e.Response, next?: e.NextFunction): Promise<any> {
16
return this.details
17
? Promise.resolve(this.details)
18
: UserService.getUser(UserService.getIdFromCookie(this.cookie))
19
.then((user:User)=>{
20
this.details = user;
21
return user;
22
})
23
}
24
25
isInRole(...roles: Array<string | number>): Promise<boolean> {
26
return this.getUser().then(user=>roles.includes(user.role));
27
28
}
29
30
/**
31
* Check if on of user has some of the permissions.
32
**/
33
isAllowedTo(...permissions: Array<string | number>): Promise<boolean> {
34
return this.getUser().then(user=>permissions.some(permission=>user.permissions.includes(permission)));
35
}
36
37
isResourceOwner(resourceId: any): Promise<boolean> {
38
return this.getUser().then(user=>Resources.checkIfOwner(resourceId,user.id));
39
}
40
41
}
Copied!
1
init(boostrapModule,"/",null, Authorization).build().listen(3000)
Copied!
1
@Controller('/dashboard')
2
export class DashboardController {
3
constructor() {
4
}
5
6
@HttpPost("/:id")
7
@Authorized(["User","Admin"],"User.READ")
8
@Authorized(null,"User.READ_BY_ID") // This case promise the user have both "User.READ" AND "User.READ_BY_ID" permissions
9
getUser(@RequestParam("id") id:number, @RequestBody() body:{role:{text:string}}) {
10
return User.findOne({id,role:body.role.text})
11
}
12
13
}
Copied!

1
Copied!
Last modified 2yr ago
Copy link