master
2022-03-23 3b8d6dc7ac1f52a411671ceb5cabfb995ea3cfe2
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
70
71
72
73
import { Inject, Provide } from '@midwayjs/decorator';
import { BaseService, ICoolCache } from '@cool-midway/core';
import { BaseSysMenuService } from './menu';
import { BaseSysRoleService } from './role';
import { BaseSysDepartmentService } from './department';
import { Context } from 'egg';
 
/**
 * 权限
 */
@Provide()
export class BaseSysPermsService extends BaseService {
  @Inject('cool:cache')
  coolCache: ICoolCache;
 
  @Inject()
  baseSysMenuService: BaseSysMenuService;
 
  @Inject()
  baseSysRoleService: BaseSysRoleService;
 
  @Inject()
  baseSysDepartmentService: BaseSysDepartmentService;
 
  @Inject()
  ctx: Context;
 
  /**
   * 刷新权限
   * @param userId 用户ID
   */
  async refreshPerms(userId) {
    const roleIds = await this.baseSysRoleService.getByUser(userId);
    const perms = await this.baseSysMenuService.getPerms(roleIds);
    await this.coolCache.set(`admin:perms:${userId}`, JSON.stringify(perms));
    // 更新部门权限
    const departments = await this.baseSysDepartmentService.getByRoleIds(
      roleIds,
      this.ctx.admin.username === 'admin'
    );
    await this.coolCache.set(
      `admin:department:${userId}`,
      JSON.stringify(departments)
    );
  }
 
  /**
   * 获得权限菜单
   * @param roleIds
   */
  async permmenu(roleIds: number[]) {
    const perms = await this.baseSysMenuService.getPerms(roleIds);
    const menus = await this.baseSysMenuService.getMenus(
      roleIds,
      this.ctx.admin.username === 'admin'
    );
    return { perms, menus };
  }
 
  /**
   * 根据用户ID获得部门权限
   * @param userId
   * @return 部门ID数组
   */
  async departmentIds(userId: number) {
    const department = await this.coolCache.get(`admin:department:${userId}`);
    if (department) {
      return JSON.parse(department);
    } else {
      return [];
    }
  }
}