import { Config, Inject, InjectClient, Provide } from '@midwayjs/core'; import { RequestBase } from '../interface/proxy.interface'; import { ProxyService } from './proxy.service'; import { HttpServiceFactory, HttpService } from '@midwayjs/axios'; import { get } from 'lodash'; @Provide() export class PermissionService { @Config('axios.clients') axiosClients: object; @Config('authUri') authUriObject: any; authBase = '/cxyy/api'; @Inject() proxyService: ProxyService; @InjectClient(HttpServiceFactory, 'default') serviceAxios: HttpService; /** * 检查用户权限 * 1.获取请求 完整的uri和method * 2.然后带着token去请求到 服务的 tokenController中,把路由信息和权限码都拿来 * 3.查询权限码中的api设置是不是当前 */ async index() { const rb: RequestBase = this.proxyService.getRequstBase(); const clientConfig = this.axiosClients[this.authBase]; const baseURL = clientConfig.baseURL; const getRouteCodeUrl = `${baseURL}${this.authUriObject.getRouteCode}`; const getRouteConfig = { url: getRouteCodeUrl, method: 'Post', data: { uri: rb.path, method: rb.method }, headers: { token: get(rb, 'header.token') }, }; const rcResult: string = await this.toRequest(getRouteConfig); const userApiCodesUrl = `${baseURL}${this.authUriObject.getUserApiCode}`; const getUserApiCodeConfig = { url: userApiCodesUrl, method: 'Post', headers: { token: get(rb, 'header.token') }, }; const uacResult: Array = await this.toRequest(getUserApiCodeConfig); if (uacResult.includes(rcResult)) return true; throw new Error('no auth'); } async toRequest(config: any) { const result = await this.serviceAxios.request(config); if (result.status !== 200) throw new Error('proxy service request error'); return get(result, 'data.data'); } }