forked from wuhan2020/rest-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Role.ts
69 lines (52 loc) · 1.68 KB
/
Role.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import {
JsonController,
Authorized,
Post,
Ctx,
Body,
ForbiddenError,
Get
} from 'routing-controllers';
import { Query, Role, User, ACL } from 'leanengine';
import { LCContext } from '../utility';
import { UserRole } from '../model';
@JsonController('/role')
export class RoleController {
static getAdmin() {
return new Query(Role).equalTo('name', UserRole.Admin).first();
}
static async create(name: string, user: User) {
const acl = new ACL();
acl.setPublicReadAccess(true),
acl.setPublicWriteAccess(false),
acl.setWriteAccess(user, true);
const admin = await this.getAdmin();
if (admin) acl.setRoleWriteAccess(admin, true);
const role = new Role(name, acl);
role.getUsers().add(user);
return role.save();
}
static async isAdmin(user: User) {
const list = await user.getRoles();
return !!list.find(role => role.getName() === UserRole.Admin);
}
@Post()
@Authorized()
async create(
@Ctx() { currentUser }: LCContext,
@Body() { name }: { name: string }
) {
if (!(await RoleController.isAdmin(currentUser)))
throw new ForbiddenError();
const role = await RoleController.create(name, currentUser);
return role.toJSON();
}
@Get()
@Authorized()
async getAll(@Ctx() { currentUser }: LCContext) {
if (!(await RoleController.isAdmin(currentUser)))
throw new ForbiddenError();
const list = await new Query(Role).find();
return list.map(item => item.toJSON());
}
}