permission.service.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import { Config, Inject, InjectClient, Provide } from '@midwayjs/core';
  2. import { RequestBase } from '../interface/proxy.interface';
  3. import { ProxyService } from './proxy.service';
  4. import { HttpServiceFactory, HttpService } from '@midwayjs/axios';
  5. import { get } from 'lodash';
  6. @Provide()
  7. export class PermissionService {
  8. @Config('axios.clients')
  9. axiosClients: object;
  10. @Config('authUri')
  11. authUriObject: any;
  12. authBase = '/cxyy/api';
  13. @Inject()
  14. proxyService: ProxyService;
  15. @InjectClient(HttpServiceFactory, 'default')
  16. serviceAxios: HttpService;
  17. /**
  18. * 检查用户权限
  19. * 1.获取请求 完整的uri和method
  20. * 2.然后带着token去请求到 服务的 tokenController中,把路由信息和权限码都拿来
  21. * 3.查询权限码中的api设置是不是当前
  22. */
  23. async index() {
  24. const rb: RequestBase = this.proxyService.getRequstBase();
  25. const clientConfig = this.axiosClients[this.authBase];
  26. const baseURL = clientConfig.baseURL;
  27. const getRouteCodeUrl = `${baseURL}${this.authUriObject.getRouteCode}`;
  28. const getRouteConfig = {
  29. url: getRouteCodeUrl,
  30. method: 'Post',
  31. data: { uri: rb.path, method: rb.method },
  32. headers: { token: get(rb, 'header.token') },
  33. };
  34. const rcResult: string = await this.toRequest(getRouteConfig);
  35. const userApiCodesUrl = `${baseURL}${this.authUriObject.getUserApiCode}`;
  36. const getUserApiCodeConfig = {
  37. url: userApiCodesUrl,
  38. method: 'Post',
  39. headers: { token: get(rb, 'header.token') },
  40. };
  41. const uacResult: Array<string> = await this.toRequest(getUserApiCodeConfig);
  42. if (uacResult.includes(rcResult)) return true;
  43. throw new Error('no auth');
  44. }
  45. async toRequest(config: any) {
  46. const result = await this.serviceAxios.request(config);
  47. if (result.status !== 200) throw new Error('proxy service request error');
  48. return get(result, 'data.data');
  49. }
  50. }