@saihu/common 1.1.3 → 1.1.4

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.
@@ -0,0 +1,12 @@
1
+ import { CanActivate, ExecutionContext } from '@nestjs/common';
2
+ import { JwtService } from '@nestjs/jwt';
3
+ import { Reflector } from '@nestjs/core';
4
+ export declare class AuthGuard implements CanActivate {
5
+ private jwtService;
6
+ private readonly jwtSecret;
7
+ private reflector;
8
+ constructor(jwtService: JwtService, jwtSecret: string, reflector: Reflector);
9
+ canActivate(context: ExecutionContext): Promise<boolean>;
10
+ private extractTokenFromHeader;
11
+ }
12
+ //# sourceMappingURL=auth-guard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth-guard.d.ts","sourceRoot":"","sources":["../../src/auth/auth-guard.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EACX,gBAAgB,EAIjB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAGzC,qBACa,SAAU,YAAW,WAAW;IAEzC,OAAO,CAAC,UAAU;IACI,OAAO,CAAC,QAAQ,CAAC,SAAS;IAChD,OAAO,CAAC,SAAS;gBAFT,UAAU,EAAE,UAAU,EACS,SAAS,EAAE,MAAM,EAChD,SAAS,EAAE,SAAS;IAGxB,WAAW,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,OAAO,CAAC;IA4B9D,OAAO,CAAC,sBAAsB;CAI/B"}
@@ -0,0 +1,64 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.AuthGuard = void 0;
16
+ const common_1 = require("@nestjs/common");
17
+ const jwt_1 = require("@nestjs/jwt");
18
+ const core_1 = require("@nestjs/core");
19
+ const decorators_1 = require("./decorators");
20
+ let AuthGuard = class AuthGuard {
21
+ constructor(jwtService, jwtSecret, reflector) {
22
+ this.jwtService = jwtService;
23
+ this.jwtSecret = jwtSecret;
24
+ this.reflector = reflector;
25
+ }
26
+ async canActivate(context) {
27
+ const isPublic = this.reflector.getAllAndOverride(decorators_1.IS_PUBLIC_KEY, [
28
+ context.getHandler(),
29
+ context.getClass(),
30
+ ]);
31
+ if (isPublic) {
32
+ // 💡 See this condition
33
+ return true;
34
+ }
35
+ const request = context.switchToHttp().getRequest();
36
+ const token = this.extractTokenFromHeader(request);
37
+ if (!token) {
38
+ throw new common_1.UnauthorizedException();
39
+ }
40
+ try {
41
+ const payload = await this.jwtService.verifyAsync(token, {
42
+ secret: this.jwtSecret,
43
+ });
44
+ // 💡 We're assigning the payload to the request object here
45
+ // so that we can access it in our route handlers
46
+ request.user = payload;
47
+ }
48
+ catch (_a) {
49
+ throw new common_1.UnauthorizedException();
50
+ }
51
+ return true;
52
+ }
53
+ extractTokenFromHeader(request) {
54
+ var _a, _b;
55
+ const [type, token] = (_b = (_a = request.headers.authorization) === null || _a === void 0 ? void 0 : _a.split(' ')) !== null && _b !== void 0 ? _b : [];
56
+ return type === 'Bearer' ? token : undefined;
57
+ }
58
+ };
59
+ exports.AuthGuard = AuthGuard;
60
+ exports.AuthGuard = AuthGuard = __decorate([
61
+ (0, common_1.Injectable)(),
62
+ __param(1, (0, common_1.Inject)('JWT_SECRET')),
63
+ __metadata("design:paramtypes", [jwt_1.JwtService, String, core_1.Reflector])
64
+ ], AuthGuard);
@@ -0,0 +1,3 @@
1
+ export declare const IS_PUBLIC_KEY = "isPublic";
2
+ export declare const Public: () => import("@nestjs/common").CustomDecorator<string>;
3
+ //# sourceMappingURL=decorators.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decorators.d.ts","sourceRoot":"","sources":["../../src/auth/decorators.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,aAAa,aAAa,CAAC;AACxC,eAAO,MAAM,MAAM,wDAAyC,CAAC"}
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Public = exports.IS_PUBLIC_KEY = void 0;
4
+ const common_1 = require("@nestjs/common");
5
+ exports.IS_PUBLIC_KEY = 'isPublic';
6
+ const Public = () => (0, common_1.SetMetadata)(exports.IS_PUBLIC_KEY, true);
7
+ exports.Public = Public;
@@ -0,0 +1,2 @@
1
+ export * from './auth-guard';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/auth/index.ts"],"names":[],"mappings":"AAAA,cAAc,cAAc,CAAC"}
@@ -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("./auth-guard"), exports);
@@ -1,41 +1,9 @@
1
1
  "use strict";
2
- var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
3
- function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
4
- var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
5
- var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
6
- var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
7
- var _, done = false;
8
- for (var i = decorators.length - 1; i >= 0; i--) {
9
- var context = {};
10
- for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
11
- for (var p in contextIn.access) context.access[p] = contextIn.access[p];
12
- context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
13
- var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
14
- if (kind === "accessor") {
15
- if (result === void 0) continue;
16
- if (result === null || typeof result !== "object") throw new TypeError("Object expected");
17
- if (_ = accept(result.get)) descriptor.get = _;
18
- if (_ = accept(result.set)) descriptor.set = _;
19
- if (_ = accept(result.init)) initializers.unshift(_);
20
- }
21
- else if (_ = accept(result)) {
22
- if (kind === "field") initializers.unshift(_);
23
- else descriptor[key] = _;
24
- }
25
- }
26
- if (target) Object.defineProperty(target, contextIn.name, descriptor);
27
- done = true;
28
- };
29
- var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
30
- var useValue = arguments.length > 2;
31
- for (var i = 0; i < initializers.length; i++) {
32
- value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
33
- }
34
- return useValue ? value : void 0;
35
- };
36
- var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) {
37
- if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
38
- return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
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;
39
7
  };
40
8
  Object.defineProperty(exports, "__esModule", { value: true });
41
9
  exports.BaseErrorFilter = void 0;
@@ -43,50 +11,38 @@ exports.BaseErrorFilter = void 0;
43
11
  const common_1 = require("@nestjs/common");
44
12
  const base_res_dto_1 = require("../dto/base-res.dto");
45
13
  const base_res_dto_2 = require("../dto/base-res.dto");
46
- let BaseErrorFilter = (() => {
47
- let _classDecorators = [(0, common_1.Catch)(base_res_dto_1.BaseError)];
48
- let _classDescriptor;
49
- let _classExtraInitializers = [];
50
- let _classThis;
51
- var BaseErrorFilter = _classThis = class {
52
- catch(exception, host) {
53
- const ctx = host.switchToHttp();
54
- const response = ctx.getResponse();
55
- // Map your BaseError code to an appropriate HTTP status code
56
- const statusCode = this.mapErrorCodeToHttpStatus(exception.code);
57
- // Return the response in your standard format
58
- response.status(statusCode).json({
59
- code: exception.code,
60
- msg: exception.message,
61
- data: exception.data,
62
- });
63
- }
64
- mapErrorCodeToHttpStatus(errorCode) {
65
- // Map your custom error codes to HTTP status codes
66
- switch (errorCode) {
67
- case base_res_dto_2.BaseResponseDto.CODE_NOT_FOUND:
68
- return common_1.HttpStatus.NOT_FOUND;
69
- case base_res_dto_2.BaseResponseDto.CODE_UNAUTHORIZED:
70
- return common_1.HttpStatus.UNAUTHORIZED;
71
- case base_res_dto_2.BaseResponseDto.CODE_FORBIDDEN:
72
- return common_1.HttpStatus.FORBIDDEN;
73
- case base_res_dto_2.BaseResponseDto.CODE_BAD_REQUEST:
74
- return common_1.HttpStatus.BAD_REQUEST;
75
- case base_res_dto_2.BaseResponseDto.CODE_SERVER_ERROR:
76
- return common_1.HttpStatus.INTERNAL_SERVER_ERROR;
77
- default:
78
- return common_1.HttpStatus.INTERNAL_SERVER_ERROR;
79
- }
14
+ let BaseErrorFilter = class BaseErrorFilter {
15
+ catch(exception, host) {
16
+ const ctx = host.switchToHttp();
17
+ const response = ctx.getResponse();
18
+ // Map your BaseError code to an appropriate HTTP status code
19
+ const statusCode = this.mapErrorCodeToHttpStatus(exception.code);
20
+ // Return the response in your standard format
21
+ response.status(statusCode).json({
22
+ code: exception.code,
23
+ msg: exception.message,
24
+ data: exception.data,
25
+ });
26
+ }
27
+ mapErrorCodeToHttpStatus(errorCode) {
28
+ // Map your custom error codes to HTTP status codes
29
+ switch (errorCode) {
30
+ case base_res_dto_2.BaseResponseDto.CODE_NOT_FOUND:
31
+ return common_1.HttpStatus.NOT_FOUND;
32
+ case base_res_dto_2.BaseResponseDto.CODE_UNAUTHORIZED:
33
+ return common_1.HttpStatus.UNAUTHORIZED;
34
+ case base_res_dto_2.BaseResponseDto.CODE_FORBIDDEN:
35
+ return common_1.HttpStatus.FORBIDDEN;
36
+ case base_res_dto_2.BaseResponseDto.CODE_BAD_REQUEST:
37
+ return common_1.HttpStatus.BAD_REQUEST;
38
+ case base_res_dto_2.BaseResponseDto.CODE_SERVER_ERROR:
39
+ return common_1.HttpStatus.INTERNAL_SERVER_ERROR;
40
+ default:
41
+ return common_1.HttpStatus.INTERNAL_SERVER_ERROR;
80
42
  }
81
- };
82
- __setFunctionName(_classThis, "BaseErrorFilter");
83
- (() => {
84
- const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
85
- __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
86
- BaseErrorFilter = _classThis = _classDescriptor.value;
87
- if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
88
- __runInitializers(_classThis, _classExtraInitializers);
89
- })();
90
- return BaseErrorFilter = _classThis;
91
- })();
43
+ }
44
+ };
92
45
  exports.BaseErrorFilter = BaseErrorFilter;
46
+ exports.BaseErrorFilter = BaseErrorFilter = __decorate([
47
+ (0, common_1.Catch)(base_res_dto_1.BaseError)
48
+ ], BaseErrorFilter);
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export * from './dto';
2
2
  export * from './interceptors';
3
3
  export * from './filters';
4
+ export * from './auth';
4
5
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,OAAO,CAAC;AACtB,cAAc,gBAAgB,CAAC;AAC/B,cAAc,WAAW,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,OAAO,CAAC;AACtB,cAAc,gBAAgB,CAAC;AAC/B,cAAc,WAAW,CAAC;AAC1B,cAAc,QAAQ,CAAC"}
package/dist/index.js CHANGED
@@ -17,3 +17,4 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./dto"), exports);
18
18
  __exportStar(require("./interceptors"), exports);
19
19
  __exportStar(require("./filters"), exports);
20
+ __exportStar(require("./auth"), exports);
@@ -1,41 +1,9 @@
1
1
  "use strict";
2
- var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
3
- function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
4
- var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
5
- var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
6
- var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
7
- var _, done = false;
8
- for (var i = decorators.length - 1; i >= 0; i--) {
9
- var context = {};
10
- for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
11
- for (var p in contextIn.access) context.access[p] = contextIn.access[p];
12
- context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
13
- var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
14
- if (kind === "accessor") {
15
- if (result === void 0) continue;
16
- if (result === null || typeof result !== "object") throw new TypeError("Object expected");
17
- if (_ = accept(result.get)) descriptor.get = _;
18
- if (_ = accept(result.set)) descriptor.set = _;
19
- if (_ = accept(result.init)) initializers.unshift(_);
20
- }
21
- else if (_ = accept(result)) {
22
- if (kind === "field") initializers.unshift(_);
23
- else descriptor[key] = _;
24
- }
25
- }
26
- if (target) Object.defineProperty(target, contextIn.name, descriptor);
27
- done = true;
28
- };
29
- var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
30
- var useValue = arguments.length > 2;
31
- for (var i = 0; i < initializers.length; i++) {
32
- value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
33
- }
34
- return useValue ? value : void 0;
35
- };
36
- var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) {
37
- if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
38
- return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
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;
39
7
  };
40
8
  Object.defineProperty(exports, "__esModule", { value: true });
41
9
  exports.TransformInterceptor = void 0;
@@ -43,31 +11,19 @@ exports.TransformInterceptor = void 0;
43
11
  const common_1 = require("@nestjs/common");
44
12
  const operators_1 = require("rxjs/operators");
45
13
  const base_res_dto_1 = require("../dto/base-res.dto");
46
- let TransformInterceptor = (() => {
47
- let _classDecorators = [(0, common_1.Injectable)()];
48
- let _classDescriptor;
49
- let _classExtraInitializers = [];
50
- let _classThis;
51
- var TransformInterceptor = _classThis = class {
52
- intercept(context, next) {
53
- return next.handle().pipe((0, operators_1.map)((data) => {
54
- // If the response is already a BaseResponseDto, return it as is
55
- if (data instanceof base_res_dto_1.BaseResponseDto) {
56
- return data;
57
- }
58
- // Otherwise, wrap it in a success response
59
- return base_res_dto_1.BaseResponseDto.success(data);
60
- }));
61
- }
62
- };
63
- __setFunctionName(_classThis, "TransformInterceptor");
64
- (() => {
65
- const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
66
- __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
67
- TransformInterceptor = _classThis = _classDescriptor.value;
68
- if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
69
- __runInitializers(_classThis, _classExtraInitializers);
70
- })();
71
- return TransformInterceptor = _classThis;
72
- })();
14
+ let TransformInterceptor = class TransformInterceptor {
15
+ intercept(context, next) {
16
+ return next.handle().pipe((0, operators_1.map)((data) => {
17
+ // If the response is already a BaseResponseDto, return it as is
18
+ if (data instanceof base_res_dto_1.BaseResponseDto) {
19
+ return data;
20
+ }
21
+ // Otherwise, wrap it in a success response
22
+ return base_res_dto_1.BaseResponseDto.success(data);
23
+ }));
24
+ }
25
+ };
73
26
  exports.TransformInterceptor = TransformInterceptor;
27
+ exports.TransformInterceptor = TransformInterceptor = __decorate([
28
+ (0, common_1.Injectable)()
29
+ ], TransformInterceptor);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@saihu/common",
3
- "version": "1.1.3",
3
+ "version": "1.1.4",
4
4
  "description": "Common utilities for NestJS applications",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -28,6 +28,8 @@
28
28
  "typescript": "^5.8.3"
29
29
  },
30
30
  "dependencies": {
31
+ "@nestjs/core": "^11.1.1",
32
+ "@nestjs/jwt": "^11.0.0",
31
33
  "express": "^5.1.0"
32
34
  }
33
35
  }