@gadmin2n/nest-common 0.0.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +5 -0
  3. package/dist/access-control/access-control.guard.d.ts +11 -0
  4. package/dist/access-control/access-control.guard.js +83 -0
  5. package/dist/access-control/decorators/ac.decorator.d.ts +3 -0
  6. package/dist/access-control/decorators/ac.decorator.js +44 -0
  7. package/dist/access-control/index.d.ts +2 -0
  8. package/dist/access-control/index.js +18 -0
  9. package/dist/auth/index.d.ts +4 -0
  10. package/dist/auth/index.js +20 -0
  11. package/dist/auth/roles.guard.d.ts +13 -0
  12. package/dist/auth/roles.guard.js +55 -0
  13. package/dist/auth/test-user.guard.d.ts +7 -0
  14. package/dist/auth/test-user.guard.js +44 -0
  15. package/dist/auth/user.types.d.ts +10 -0
  16. package/dist/auth/user.types.js +2 -0
  17. package/dist/auth/yf-auth.guard.d.ts +4 -0
  18. package/dist/auth/yf-auth.guard.js +141 -0
  19. package/dist/controller/controller-exclude.d.ts +2 -0
  20. package/dist/controller/controller-exclude.js +12 -0
  21. package/dist/controller/index.d.ts +2 -0
  22. package/dist/controller/index.js +18 -0
  23. package/dist/controller/interceptor.decorators.d.ts +1 -0
  24. package/dist/controller/interceptor.decorators.js +17 -0
  25. package/dist/exception/all-exception.filter.d.ts +4 -0
  26. package/dist/exception/all-exception.filter.js +32 -0
  27. package/dist/exception/index.d.ts +1 -0
  28. package/dist/exception/index.js +17 -0
  29. package/dist/index.d.ts +6 -0
  30. package/dist/index.js +22 -0
  31. package/dist/swagger-pagination/constants.d.ts +4 -0
  32. package/dist/swagger-pagination/constants.js +8 -0
  33. package/dist/swagger-pagination/decorator.d.ts +3 -0
  34. package/dist/swagger-pagination/decorator.js +26 -0
  35. package/dist/swagger-pagination/index.d.ts +6 -0
  36. package/dist/swagger-pagination/index.js +22 -0
  37. package/dist/swagger-pagination/interfaces.d.ts +5 -0
  38. package/dist/swagger-pagination/interfaces.js +2 -0
  39. package/dist/swagger-pagination/page-meta.dto.d.ts +10 -0
  40. package/dist/swagger-pagination/page-meta.dto.js +48 -0
  41. package/dist/swagger-pagination/page-options.dto.d.ts +8 -0
  42. package/dist/swagger-pagination/page-options.dto.js +58 -0
  43. package/dist/swagger-pagination/page.dto.d.ts +6 -0
  44. package/dist/swagger-pagination/page.dto.js +31 -0
  45. package/dist/tsconfig.lib.tsbuildinfo +1 -0
  46. package/dist/utils/helpers.d.ts +10 -0
  47. package/dist/utils/helpers.js +106 -0
  48. package/dist/utils/index.d.ts +1 -0
  49. package/dist/utils/index.js +17 -0
  50. package/package.json +84 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2018-2022 nestjs
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,5 @@
1
+
2
+
3
+ ## Description
4
+
5
+ Helpers for gadmin2 nest app.
@@ -0,0 +1,11 @@
1
+ import { CanActivate, ExecutionContext } from '@nestjs/common';
2
+ import { Reflector } from '@nestjs/core';
3
+ import { RolesBuilder, Role } from 'nest-access-control';
4
+ export declare class ACGuard implements CanActivate {
5
+ private readonly reflector;
6
+ private readonly roleBuilder;
7
+ constructor(reflector: Reflector, roleBuilder: RolesBuilder);
8
+ static getKey(role?: Role): string;
9
+ protected getReq(context: ExecutionContext): Promise<any>;
10
+ canActivate(context: ExecutionContext): Promise<boolean>;
11
+ }
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
12
+ return function (target, key) { decorator(target, key, paramIndex); }
13
+ };
14
+ var ACGuard_1;
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.ACGuard = void 0;
17
+ const common_1 = require("@nestjs/common");
18
+ const core_1 = require("@nestjs/core");
19
+ const nest_access_control_1 = require("nest-access-control");
20
+ let ACGuard = ACGuard_1 = class ACGuard {
21
+ constructor(reflector, roleBuilder) {
22
+ this.reflector = reflector;
23
+ this.roleBuilder = roleBuilder;
24
+ }
25
+ static getKey(role = {}) {
26
+ return `${role.action}:${role.resource}:${role.possession}`;
27
+ }
28
+ async getReq(context) {
29
+ const contextType = context.getType().toString();
30
+ switch (contextType) {
31
+ case 'http':
32
+ return context.switchToHttp().getRequest();
33
+ case 'graphql':
34
+ const { GqlExecutionContext } = require('@nestjs/graphql');
35
+ return GqlExecutionContext.create(context).getContext().req;
36
+ default:
37
+ throw new Error(`Unsupported context type: ${contextType}`);
38
+ }
39
+ }
40
+ async canActivate(context) {
41
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
42
+ const roles = this.reflector.get('roles', context.getHandler());
43
+ if (!roles) {
44
+ return true;
45
+ }
46
+ const req = await this.getReq(context);
47
+ const { user } = req;
48
+ if (!(user === null || user === void 0 ? void 0 : user['configPerms'])) {
49
+ throw new common_1.ForbiddenException();
50
+ }
51
+ if (((_b = (_a = user.configPerms) === null || _a === void 0 ? void 0 : _a.business) === null || _b === void 0 ? void 0 : _b.length) ||
52
+ ((_d = (_c = user.configPerms) === null || _c === void 0 ? void 0 : _c.groups) === null || _d === void 0 ? void 0 : _d.length)) {
53
+ const configBusiness = (_f = (_e = user.configPerms) === null || _e === void 0 ? void 0 : _e.business) === null || _f === void 0 ? void 0 : _f.map((item) => String(item));
54
+ if (!(((_g = user.configPerms) === null || _g === void 0 ? void 0 : _g.roles.includes('SYSTEM_ADMIN')) ||
55
+ (configBusiness === null || configBusiness === void 0 ? void 0 : configBusiness.includes('-1')) ||
56
+ (configBusiness === null || configBusiness === void 0 ? void 0 : configBusiness.includes(String((_h = JSON.parse(req.headers['x-gadmin-business'] || '{}')) === null || _h === void 0 ? void 0 : _h.id))) ||
57
+ ((_k = (_j = user.configPerms) === null || _j === void 0 ? void 0 : _j.groups) === null || _k === void 0 ? void 0 : _k.some((item) => { var _a, _b; return (_b = (_a = user.sessionBusiness) === null || _a === void 0 ? void 0 : _a.groups) === null || _b === void 0 ? void 0 : _b.includes(item); })))) {
58
+ throw new common_1.ForbiddenException();
59
+ }
60
+ }
61
+ req.useRoles = roles;
62
+ user.permissions = {};
63
+ const hasRoles = roles.every((role) => {
64
+ const queryInfo = role;
65
+ queryInfo.role = user['configPerms'].roles;
66
+ const permission = this.roleBuilder.permission(queryInfo);
67
+ if (permission.granted) {
68
+ permission.attributes.push('_count');
69
+ }
70
+ user.permissions[ACGuard_1.getKey(role)] = permission;
71
+ return permission.granted;
72
+ });
73
+ return hasRoles;
74
+ }
75
+ };
76
+ ACGuard = ACGuard_1 = __decorate([
77
+ (0, common_1.Injectable)(),
78
+ __param(0, (0, common_1.Inject)(core_1.Reflector.name)),
79
+ __param(1, (0, nest_access_control_1.InjectRolesBuilder)()),
80
+ __metadata("design:paramtypes", [core_1.Reflector,
81
+ nest_access_control_1.RolesBuilder])
82
+ ], ACGuard);
83
+ exports.ACGuard = ACGuard;
@@ -0,0 +1,3 @@
1
+ export declare const ReqAttr: (...dataOrPipes: (string | import("@nestjs/common").PipeTransform<any, any> | import("@nestjs/common").Type<import("@nestjs/common").PipeTransform<any, any>>)[]) => ParameterDecorator;
2
+ export declare const User: (...dataOrPipes: (string | import("@nestjs/common").PipeTransform<any, any> | import("@nestjs/common").Type<import("@nestjs/common").PipeTransform<any, any>>)[]) => ParameterDecorator;
3
+ export declare const ACAttrFilter: (...dataOrPipes: (number | import("@nestjs/common").PipeTransform<any, any> | import("@nestjs/common").Type<import("@nestjs/common").PipeTransform<any, any>>)[]) => ParameterDecorator;
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ACAttrFilter = exports.User = exports.ReqAttr = void 0;
4
+ const common_1 = require("@nestjs/common");
5
+ const access_control_guard_1 = require("../access-control.guard");
6
+ function userFactory(ctx) {
7
+ const contextType = ctx.getType();
8
+ if (contextType === 'http') {
9
+ return ctx.switchToHttp().getRequest();
10
+ }
11
+ else if (contextType === 'rpc') {
12
+ throw new Error('Rpc context is not implemented yet');
13
+ }
14
+ else if (contextType === 'ws') {
15
+ throw new Error('Websockets context is not implemented yet');
16
+ }
17
+ else if (contextType === 'graphql') {
18
+ const { GqlExecutionContext } = require('@nestjs/graphql');
19
+ const gqlExecutionContext = GqlExecutionContext.create(ctx);
20
+ return gqlExecutionContext.getContext().req;
21
+ }
22
+ throw new Error('Invalid context');
23
+ }
24
+ exports.ReqAttr = (0, common_1.createParamDecorator)((propertyKey, ctx) => {
25
+ const req = userFactory(ctx);
26
+ return propertyKey ? req[propertyKey] : req;
27
+ });
28
+ exports.User = (0, common_1.createParamDecorator)((propertyKey, ctx) => {
29
+ const { user } = userFactory(ctx);
30
+ if (!user)
31
+ return null;
32
+ return propertyKey ? user[propertyKey] : user;
33
+ });
34
+ exports.ACAttrFilter = (0, common_1.createParamDecorator)((index, ctx) => {
35
+ var _a, _b;
36
+ const req = userFactory(ctx);
37
+ const acRoles = req.useRoles;
38
+ const role = index === undefined ? acRoles === null || acRoles === void 0 ? void 0 : acRoles[0] : acRoles === null || acRoles === void 0 ? void 0 : acRoles[index];
39
+ const permission = (_b = (_a = req === null || req === void 0 ? void 0 : req.user) === null || _a === void 0 ? void 0 : _a.permissions) === null || _b === void 0 ? void 0 : _b[access_control_guard_1.ACGuard.getKey(role)];
40
+ if (!role || !permission) {
41
+ return ((data) => data);
42
+ }
43
+ return permission.filter.bind(permission) || ((data) => data);
44
+ });
@@ -0,0 +1,2 @@
1
+ export * from './access-control.guard';
2
+ export * from './decorators/ac.decorator';
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./access-control.guard"), exports);
18
+ __exportStar(require("./decorators/ac.decorator"), exports);
@@ -0,0 +1,4 @@
1
+ export * from './yf-auth.guard';
2
+ export * from './user.types';
3
+ export * from './roles.guard';
4
+ export * from './test-user.guard';
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./yf-auth.guard"), exports);
18
+ __exportStar(require("./user.types"), exports);
19
+ __exportStar(require("./roles.guard"), exports);
20
+ __exportStar(require("./test-user.guard"), exports);
@@ -0,0 +1,13 @@
1
+ import { CanActivate, ExecutionContext } from '@nestjs/common';
2
+ import { UserType } from './user.types';
3
+ declare type RolesGetter = (user: UserType) => Promise<{
4
+ business?: (string | number)[];
5
+ groups?: string[];
6
+ roles: string[];
7
+ }>;
8
+ export declare class RolesGuard implements CanActivate {
9
+ private readonly getter;
10
+ constructor(getter: RolesGetter);
11
+ canActivate(context: ExecutionContext): boolean | Promise<boolean>;
12
+ }
13
+ export {};
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.RolesGuard = void 0;
13
+ const common_1 = require("@nestjs/common");
14
+ let RolesGuard = class RolesGuard {
15
+ constructor(getter) {
16
+ this.getter = getter;
17
+ }
18
+ canActivate(context) {
19
+ let req;
20
+ const contextType = context.getType();
21
+ if (contextType === 'http') {
22
+ req = context.switchToHttp().getRequest();
23
+ }
24
+ else if (contextType === 'rpc') {
25
+ throw new Error('Rpc context is not implemented yet');
26
+ }
27
+ else if (contextType === 'ws') {
28
+ throw new Error('Websockets context is not implemented yet');
29
+ }
30
+ else if (contextType === 'graphql') {
31
+ const { GqlExecutionContext } = require('@nestjs/graphql');
32
+ const gqlExecutionContext = GqlExecutionContext.create(context);
33
+ req = gqlExecutionContext.getContext().req;
34
+ }
35
+ if (!req.user) {
36
+ throw new common_1.UnauthorizedException();
37
+ }
38
+ return this.getter(req.user)
39
+ .then((configPerms) => {
40
+ if (undefined === configPerms || configPerms.roles.length === 0) {
41
+ throw new common_1.ForbiddenException();
42
+ }
43
+ req.user.configPerms = configPerms;
44
+ return true;
45
+ })
46
+ .catch((_) => {
47
+ throw new common_1.UnauthorizedException();
48
+ });
49
+ }
50
+ };
51
+ RolesGuard = __decorate([
52
+ (0, common_1.Injectable)(),
53
+ __metadata("design:paramtypes", [Function])
54
+ ], RolesGuard);
55
+ exports.RolesGuard = RolesGuard;
@@ -0,0 +1,7 @@
1
+ import { CanActivate, ExecutionContext } from '@nestjs/common';
2
+ import { UserType } from './user.types';
3
+ export declare class TestUserGuard implements CanActivate {
4
+ private readonly userinfo;
5
+ constructor(userinfo: UserType);
6
+ canActivate(context: ExecutionContext): boolean | Promise<boolean>;
7
+ }
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ var __metadata = (this && this.__metadata) || function (k, v) {
9
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.TestUserGuard = void 0;
13
+ const common_1 = require("@nestjs/common");
14
+ let TestUserGuard = class TestUserGuard {
15
+ constructor(userinfo) {
16
+ this.userinfo = userinfo;
17
+ }
18
+ canActivate(context) {
19
+ let req;
20
+ const contextType = context.getType();
21
+ if (contextType === 'http') {
22
+ req = context.switchToHttp().getRequest();
23
+ }
24
+ else if (contextType === 'rpc') {
25
+ throw new Error('Rpc context is not implemented yet');
26
+ }
27
+ else if (contextType === 'ws') {
28
+ throw new Error('Websockets context is not implemented yet');
29
+ }
30
+ else if (contextType === 'graphql') {
31
+ throw new Error('Graphql context is not implemented yet');
32
+ }
33
+ if (!this.userinfo) {
34
+ throw new common_1.UnauthorizedException();
35
+ }
36
+ req.user = this.userinfo;
37
+ return true;
38
+ }
39
+ };
40
+ TestUserGuard = __decorate([
41
+ (0, common_1.Injectable)(),
42
+ __metadata("design:paramtypes", [Object])
43
+ ], TestUserGuard);
44
+ exports.TestUserGuard = TestUserGuard;
@@ -0,0 +1,10 @@
1
+ import { Permission } from 'accesscontrol';
2
+ export declare type PermissionsType = Record<string, Permission>;
3
+ export declare type UserType = {
4
+ permissions?: PermissionsType;
5
+ roles?: Array<string>;
6
+ business?: Array<string | number>;
7
+ groups?: Array<string>;
8
+ username: string;
9
+ userid: string;
10
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,4 @@
1
+ import { CanActivate, ExecutionContext } from '@nestjs/common';
2
+ export declare class YFAuthGuard implements CanActivate {
3
+ canActivate(context: ExecutionContext): boolean | Promise<boolean>;
4
+ }
@@ -0,0 +1,141 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.YFAuthGuard = void 0;
10
+ const common_1 = require("@nestjs/common");
11
+ const request_1 = require("request");
12
+ const url_1 = require("url");
13
+ const jsonwebtoken_1 = require("jsonwebtoken");
14
+ const GAdminTokenName = 'gadminToken';
15
+ function getGAdminToken(req) {
16
+ return req.headers[GAdminTokenName] || req.cookies[GAdminTokenName];
17
+ }
18
+ class YuFuId {
19
+ static callApi(url, params, options) {
20
+ return new Promise((resolve, reject) => {
21
+ (0, request_1.default)(Object.assign({ url: `${YuFuId.config.apiBase}${url}`, method: 'POST', json: true, body: params }, options), (error, _response, body) => {
22
+ if (error) {
23
+ reject(error);
24
+ return;
25
+ }
26
+ if (body.error) {
27
+ reject(new Error(body.error_description));
28
+ return;
29
+ }
30
+ resolve(body);
31
+ });
32
+ });
33
+ }
34
+ static getToken(code) {
35
+ return YuFuId.callApi('/token', {
36
+ client_id: YuFuId.config.clientId,
37
+ client_secret: YuFuId.config.clientSecret,
38
+ grant_type: 'authorization_code',
39
+ redirect_uri: YuFuId.config.callback,
40
+ code,
41
+ });
42
+ }
43
+ static refreshToken(refreshToken) {
44
+ return YuFuId.callApi('/token', {
45
+ client_id: YuFuId.config.clientId,
46
+ client_secret: YuFuId.config.clientSecret,
47
+ grant_type: 'refresh_token',
48
+ refresh_token: refreshToken,
49
+ });
50
+ }
51
+ static getUserInfo(accessToken) {
52
+ return YuFuId.callApi('/userinfo', undefined, {
53
+ method: 'GET',
54
+ headers: {
55
+ Authorization: `Bearer ${accessToken}`,
56
+ },
57
+ });
58
+ }
59
+ static authorize(redirectUrl, uiLocales = 'zh-CN') {
60
+ const map = new Map();
61
+ map.set('response_type', 'code');
62
+ map.set('client_id', YuFuId.config.clientId);
63
+ map.set('ui_locales', uiLocales);
64
+ map.set('scope', 'openid profile email');
65
+ map.set('redirect_uri', YuFuId.config.callback);
66
+ map.set('state', redirectUrl);
67
+ const params = new url_1.URLSearchParams(map);
68
+ return `${YuFuId.config.apiBase}/authorize?${params.toString()}`;
69
+ }
70
+ static logout(redirectUrl) {
71
+ const map = new Map();
72
+ map.set('return_to', redirectUrl);
73
+ const params = new url_1.URLSearchParams(map);
74
+ return `${YuFuId.config.logout}?${params.toString()}`;
75
+ }
76
+ static sign(payload, expiresIn = 1800) {
77
+ return new Promise((resolve, reject) => {
78
+ jsonwebtoken_1.default.sign(payload, YuFuId.config.clientSecret, { expiresIn }, (err, token) => {
79
+ if (err) {
80
+ reject(err);
81
+ return;
82
+ }
83
+ resolve(token);
84
+ });
85
+ });
86
+ }
87
+ static verify(token) {
88
+ return new Promise((resolve, reject) => {
89
+ if (!token) {
90
+ reject(new Error('no token'));
91
+ return;
92
+ }
93
+ jsonwebtoken_1.default.verify(token, YuFuId.config.clientSecret, {}, (err, decoded) => {
94
+ if (err) {
95
+ reject(err);
96
+ return;
97
+ }
98
+ resolve(decoded);
99
+ });
100
+ });
101
+ }
102
+ }
103
+ YuFuId.config = {
104
+ clientId: process.env.YUFU_CLIENT_ID,
105
+ clientSecret: process.env.YUFU_CLIENT_SECRET || 'gadmin-default-secret',
106
+ apiBase: process.env.YUFU_BASE,
107
+ callback: process.env.YUFU_CALLBACK,
108
+ logout: process.env.YUFU_LOGOUT,
109
+ };
110
+ let YFAuthGuard = class YFAuthGuard {
111
+ canActivate(context) {
112
+ let req;
113
+ const contextType = context.getType();
114
+ if (contextType === 'http') {
115
+ req = context.switchToHttp().getRequest();
116
+ }
117
+ else if (contextType === 'rpc') {
118
+ throw new Error('Rpc context is not implemented yet');
119
+ }
120
+ else if (contextType === 'ws') {
121
+ throw new Error('Websockets context is not implemented yet');
122
+ }
123
+ else if (contextType === 'graphql') {
124
+ throw new Error('Graphql context is not implemented yet');
125
+ }
126
+ const token = getGAdminToken(req);
127
+ return YuFuId.verify(token).then(userInfo => {
128
+ const user = {
129
+ roles: userInfo.perms || [],
130
+ userid: userInfo.user_id,
131
+ username: userInfo.sub,
132
+ };
133
+ req.user = user;
134
+ return true;
135
+ }).catch(_ => { throw new common_1.UnauthorizedException(); });
136
+ }
137
+ };
138
+ YFAuthGuard = __decorate([
139
+ (0, common_1.Injectable)()
140
+ ], YFAuthGuard);
141
+ exports.YFAuthGuard = YFAuthGuard;
@@ -0,0 +1,2 @@
1
+ export declare function excludeController<TFunction extends Function>(cls: TFunction): void;
2
+ export declare function excludeEndpoint<TFunction extends Function>(cls: TFunction, methodName: string | symbol): void;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.excludeEndpoint = exports.excludeController = void 0;
4
+ const swagger_1 = require("@nestjs/swagger");
5
+ function excludeController(cls) {
6
+ (0, swagger_1.ApiExcludeController)()(cls);
7
+ }
8
+ exports.excludeController = excludeController;
9
+ function excludeEndpoint(cls, methodName) {
10
+ (0, swagger_1.ApiExcludeEndpoint)()(cls, methodName, Object.getOwnPropertyDescriptor(cls.prototype, methodName));
11
+ }
12
+ exports.excludeEndpoint = excludeEndpoint;
@@ -0,0 +1,2 @@
1
+ export * from './interceptor.decorators';
2
+ export * from './controller-exclude';
@@ -0,0 +1,18 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./interceptor.decorators"), exports);
18
+ __exportStar(require("./controller-exclude"), exports);
@@ -0,0 +1 @@
1
+ export declare function UseInterceptorFor<TFunction extends Function>(cls: TFunction, key?: string | symbol): (Interceptor: any) => any;
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.UseInterceptorFor = void 0;
4
+ const common_1 = require("@nestjs/common");
5
+ function UseInterceptorFor(cls, key) {
6
+ if (key) {
7
+ return (Interceptor) => {
8
+ (0, common_1.UseInterceptors)(Interceptor)(cls, key, Object.getOwnPropertyDescriptor(cls.prototype, key));
9
+ return Interceptor;
10
+ };
11
+ }
12
+ return (Interceptor) => {
13
+ (0, common_1.UseInterceptors)(Interceptor)(cls);
14
+ return Interceptor;
15
+ };
16
+ }
17
+ exports.UseInterceptorFor = UseInterceptorFor;
@@ -0,0 +1,4 @@
1
+ import { ExceptionFilter, ArgumentsHost } from '@nestjs/common';
2
+ export declare class AllExceptionsFilter implements ExceptionFilter {
3
+ catch(exception: any, host: ArgumentsHost): void;
4
+ }
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
3
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
4
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
5
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
6
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
7
+ };
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.AllExceptionsFilter = void 0;
10
+ const common_1 = require("@nestjs/common");
11
+ let AllExceptionsFilter = class AllExceptionsFilter {
12
+ catch(exception, host) {
13
+ var _a, _b, _c, _d, _e;
14
+ const ctx = host.switchToHttp();
15
+ const response = ctx.getResponse();
16
+ const request = ctx.getRequest();
17
+ const statusCode = ((_a = exception === null || exception === void 0 ? void 0 : exception.getStatus) === null || _a === void 0 ? void 0 : _a.call(exception)) || common_1.HttpStatus.INTERNAL_SERVER_ERROR;
18
+ const message = ((_c = (_b = exception === null || exception === void 0 ? void 0 : exception.getResponse) === null || _b === void 0 ? void 0 : _b.call(exception)) === null || _c === void 0 ? void 0 : _c.message) ||
19
+ ((_e = (_d = exception === null || exception === void 0 ? void 0 : exception.message) === null || _d === void 0 ? void 0 : _d.replace) === null || _e === void 0 ? void 0 : _e.call(_d, /\n/g, '')) ||
20
+ 'Internal server error.';
21
+ response.status(statusCode).json({
22
+ statusCode,
23
+ message,
24
+ error: (exception === null || exception === void 0 ? void 0 : exception.name) || message,
25
+ path: request.url,
26
+ });
27
+ }
28
+ };
29
+ AllExceptionsFilter = __decorate([
30
+ (0, common_1.Catch)()
31
+ ], AllExceptionsFilter);
32
+ exports.AllExceptionsFilter = AllExceptionsFilter;
@@ -0,0 +1 @@
1
+ export * from './all-exception.filter';
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./all-exception.filter"), exports);
@@ -0,0 +1,6 @@
1
+ export * from './swagger-pagination';
2
+ export * from './auth';
3
+ export * from './access-control';
4
+ export * from './controller';
5
+ export * from './exception';
6
+ export * from './utils';