@my-nestjs-kit/auth 0.0.0-stage → 0.1.0-dev.20261129010337
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.
- package/LICENSE +21 -0
- package/README.md +27 -2
- package/dist/access-tokens/access-token.d.ts +13 -0
- package/dist/access-tokens/access-token.js +10 -0
- package/dist/access-tokens/access-tokens.module.d.ts +2 -0
- package/dist/access-tokens/access-tokens.module.js +22 -0
- package/dist/access-tokens/access-tokens.service.d.ts +16 -0
- package/dist/access-tokens/access-tokens.service.js +72 -0
- package/dist/access-tokens/access-tokens.types.d.ts +5 -0
- package/dist/access-tokens/access-tokens.types.js +9 -0
- package/dist/access-tokens/dto/access-token.dto.d.ts +13 -0
- package/dist/access-tokens/dto/access-token.dto.js +33 -0
- package/dist/auth-sessions/devices/dto/create-device.dto.d.ts +6 -0
- package/dist/auth-sessions/devices/dto/create-device.dto.js +33 -0
- package/dist/auth-sessions/dto/create-auth-session.dto.d.ts +8 -0
- package/dist/auth-sessions/dto/create-auth-session.dto.js +36 -0
- package/dist/auth.constants.d.ts +30 -0
- package/dist/auth.constants.js +36 -0
- package/dist/decorators/GetAuthParams.decorator.d.ts +34 -0
- package/dist/decorators/GetAuthParams.decorator.js +64 -0
- package/dist/decorators/GetSession.decorator.d.ts +2 -0
- package/dist/decorators/GetSession.decorator.js +13 -0
- package/dist/decorators/GetUser.decorator.d.ts +2 -0
- package/dist/decorators/GetUser.decorator.js +13 -0
- package/dist/decorators/Public.decorator.d.ts +3 -0
- package/dist/decorators/Public.decorator.js +18 -0
- package/dist/decorators/SetAuthConfig.decorator.d.ts +3 -0
- package/dist/decorators/SetAuthConfig.decorator.js +13 -0
- package/dist/dto/confirm-secure-action.dto.d.ts +8 -0
- package/dist/dto/confirm-secure-action.dto.js +46 -0
- package/dist/dto/log-in-by-email.dto.d.ts +16 -0
- package/dist/dto/log-in-by-email.dto.js +15 -0
- package/dist/dto/login-user-auth.dto.d.ts +4 -0
- package/dist/dto/login-user-auth.dto.js +29 -0
- package/dist/dto/verify-user-registration.dto.d.ts +4 -0
- package/dist/dto/verify-user-registration.dto.js +25 -0
- package/dist/entities/abstract-device-base.entity.d.ts +10 -0
- package/dist/entities/abstract-device-base.entity.js +77 -0
- package/dist/entities/abstract-o-auth-connection.entity.d.ts +28 -0
- package/dist/entities/abstract-o-auth-connection.entity.js +100 -0
- package/dist/entities/abstract-o-auth-profile.entity.d.ts +10 -0
- package/dist/entities/abstract-o-auth-profile.entity.js +38 -0
- package/dist/entities/auth-session-base.entity.d.ts +18 -0
- package/dist/entities/auth-session-base.entity.js +73 -0
- package/dist/guards/AbstractRefreshJwtToken.guard.d.ts +9 -0
- package/dist/guards/AbstractRefreshJwtToken.guard.js +45 -0
- package/dist/guards/abstract/AppAuthGuard-abstract.d.ts +219 -0
- package/dist/guards/abstract/AppAuthGuard-abstract.js +187 -0
- package/dist/guards/index.d.ts +0 -0
- package/dist/guards/index.js +0 -0
- package/dist/helper/base-auth-service.helper.d.ts +60 -0
- package/dist/helper/base-auth-service.helper.js +184 -0
- package/dist/helper/jsw-auth-controller-abstract.d.ts +33 -0
- package/dist/helper/jsw-auth-controller-abstract.js +89 -0
- package/dist/helper/jwt-auth-service-abstract.d.ts +40 -0
- package/dist/helper/jwt-auth-service-abstract.js +181 -0
- package/dist/index.d.ts +31 -0
- package/dist/index.js +55 -0
- package/dist/jwt/index.d.ts +5 -0
- package/dist/jwt/index.js +21 -0
- package/dist/jwt/jwt-auth.module.d.ts +6 -0
- package/dist/jwt/jwt-auth.module.js +45 -0
- package/dist/jwt/jwt-auth.service.d.ts +33 -0
- package/dist/jwt/jwt-auth.service.js +170 -0
- package/dist/jwt/jwt-keys.helper.d.ts +12 -0
- package/dist/jwt/jwt-keys.helper.js +32 -0
- package/dist/jwt/types/enums.d.ts +19 -0
- package/dist/jwt/types/enums.js +26 -0
- package/dist/jwt/types/index.d.ts +2 -0
- package/dist/jwt/types/index.js +18 -0
- package/dist/jwt/types/jwt-auth.types.d.ts +44 -0
- package/dist/jwt/types/jwt-auth.types.js +2 -0
- package/dist/o-auth/abstract-o-auth.service.d.ts +30 -0
- package/dist/o-auth/abstract-o-auth.service.js +64 -0
- package/dist/o-auth/o-auth.namespace.d.ts +131 -0
- package/dist/o-auth/o-auth.namespace.js +256 -0
- package/dist/o-auth/sdk/base-ext-o-auth-sdk.d.ts +104 -0
- package/dist/o-auth/sdk/base-ext-o-auth-sdk.js +56 -0
- package/dist/route-auth-configs.helper.d.ts +29 -0
- package/dist/route-auth-configs.helper.js +36 -0
- package/dist/services/abstrac-auth-sessions.service.d.ts +28 -0
- package/dist/services/abstrac-auth-sessions.service.js +41 -0
- package/dist/services/abstract-sessions-repo.service.d.ts +28 -0
- package/dist/services/abstract-sessions-repo.service.js +28 -0
- package/dist/types/app-request.inteface.d.ts +14 -0
- package/dist/types/app-request.inteface.js +2 -0
- package/dist/types/auth.types.d.ts +43 -0
- package/dist/types/auth.types.js +12 -0
- package/dist/types/ws-client.types.d.ts +14 -0
- package/dist/types/ws-client.types.js +2 -0
- package/package.json +95 -3
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
import { CanActivate, ContextType, ExecutionContext, HttpStatus, Logger } from '@nestjs/common';
|
|
3
|
+
import { AppHttpExceptionResponse, AppWsExceptionPayload, ExceptionResponseArgs } from '@my-nestjs-kit/core';
|
|
4
|
+
import type { AppWs } from '../../types/ws-client.types';
|
|
5
|
+
import { HttpApi, JwtIssuerEnum, PermissionHolderEnum, ValuesOf } from '@my-nestjs-kit/core';
|
|
6
|
+
import { JwtTypeEnum } from '../../jwt/types/enums';
|
|
7
|
+
import { Observable } from 'rxjs';
|
|
8
|
+
import { Reflector } from '@nestjs/core';
|
|
9
|
+
import { AuthConfigsMetaStorage } from '../../route-auth-configs.helper';
|
|
10
|
+
import HeaderName = HttpApi.HeaderName;
|
|
11
|
+
export interface AuthGuardMeta {
|
|
12
|
+
type: string;
|
|
13
|
+
model?: JwtIssuerEnum;
|
|
14
|
+
ignorePublic?: boolean;
|
|
15
|
+
models?: {
|
|
16
|
+
whiteList?: (keyof typeof JwtIssuerEnum | JwtIssuerEnum)[];
|
|
17
|
+
blackList?: (keyof typeof JwtIssuerEnum | JwtIssuerEnum)[];
|
|
18
|
+
skipList?: (keyof typeof JwtIssuerEnum | JwtIssuerEnum)[];
|
|
19
|
+
};
|
|
20
|
+
routes?: {
|
|
21
|
+
whiteList?: string[];
|
|
22
|
+
blackList?: string[];
|
|
23
|
+
skipList?: string[];
|
|
24
|
+
};
|
|
25
|
+
headers?: [
|
|
26
|
+
whiteList?: (HeaderName | string)[],
|
|
27
|
+
blackList?: (HeaderName | string)[],
|
|
28
|
+
skipList?: (HeaderName | string)[]
|
|
29
|
+
];
|
|
30
|
+
cookiesKeys?: string[];
|
|
31
|
+
recipient?: PermissionHolderEnum;
|
|
32
|
+
tokenTypes?: JwtTypeEnum;
|
|
33
|
+
failStatusCode?: HttpStatus;
|
|
34
|
+
}
|
|
35
|
+
export type RequestTargetByCtxType = {
|
|
36
|
+
ws: AppWs.Client;
|
|
37
|
+
http: HttpApi.Request;
|
|
38
|
+
rpc: AppWs.Client;
|
|
39
|
+
};
|
|
40
|
+
export type RequestTarget = ValuesOf<RequestTargetByCtxType>;
|
|
41
|
+
export interface BaseValidateAsyncAuthInput {
|
|
42
|
+
target: ValuesOf<RequestTargetByCtxType>;
|
|
43
|
+
configs: AuthConfigsMetaStorage;
|
|
44
|
+
ctxType: ContextType;
|
|
45
|
+
ctx: ExecutionContext;
|
|
46
|
+
publicKey?: string;
|
|
47
|
+
privateKey?: string;
|
|
48
|
+
access_token?: string;
|
|
49
|
+
refresh_token?: string;
|
|
50
|
+
}
|
|
51
|
+
export declare abstract class AbstractAuthGuard<Input = BaseValidateAsyncAuthInput> implements CanActivate {
|
|
52
|
+
protected readonly reflector: Reflector;
|
|
53
|
+
protected readonly meta: AuthGuardMeta;
|
|
54
|
+
protected readonly __logger: Logger;
|
|
55
|
+
protected readonly _logger: Logger;
|
|
56
|
+
protected readonly msgs: {
|
|
57
|
+
ACCESS_GRANTED: string;
|
|
58
|
+
ACCESS_DENY: string;
|
|
59
|
+
isDeactivated: string;
|
|
60
|
+
modelIsInSkipList: string;
|
|
61
|
+
routeIsInSkipList: string;
|
|
62
|
+
isModelRefmeActive: string;
|
|
63
|
+
isNotActive: string;
|
|
64
|
+
authConfigsNotFound: string;
|
|
65
|
+
isPublic: string;
|
|
66
|
+
isExpired: string;
|
|
67
|
+
notHasPermission: string;
|
|
68
|
+
unknownError: string;
|
|
69
|
+
jwtCheckIsActive: string;
|
|
70
|
+
jwtErpCheckIsActive: string;
|
|
71
|
+
modelErpIsActive: string;
|
|
72
|
+
tokenNotFound: string;
|
|
73
|
+
forbiddenAction: string;
|
|
74
|
+
xTokenCheckIsActive: string;
|
|
75
|
+
tokenIsExpired: string;
|
|
76
|
+
authHeaderNotFound: string;
|
|
77
|
+
isNotBearer: string;
|
|
78
|
+
userNotFound: string;
|
|
79
|
+
unauthorized: string;
|
|
80
|
+
forbiddenForModel: string;
|
|
81
|
+
forbiddenForRole: string;
|
|
82
|
+
forbiddenForHolder: string;
|
|
83
|
+
};
|
|
84
|
+
protected constructor(reflector: Reflector, meta: AuthGuardMeta);
|
|
85
|
+
canActivate(ctx: ExecutionContext): boolean | Promise<boolean> | Observable<boolean>;
|
|
86
|
+
protected _getTargetDict: {
|
|
87
|
+
http: (ctx: ExecutionContext) => HttpApi.Request<any, HttpApi.BaseReqQuery, import("@my-nestjs-kit/core").AppCookies, HttpApi.BaseReqParams, import("http").IncomingHttpHeaders & {
|
|
88
|
+
permission?: string;
|
|
89
|
+
Authorization?: string;
|
|
90
|
+
"Track-Id"?: string;
|
|
91
|
+
"Refresh-Token"?: string;
|
|
92
|
+
"refresh-token"?: string;
|
|
93
|
+
"track-id"?: string;
|
|
94
|
+
"User-Reference"?: string;
|
|
95
|
+
"user-reference"?: string;
|
|
96
|
+
"user-agent"?: string;
|
|
97
|
+
dnt?: string;
|
|
98
|
+
"crm-authorization"?: string;
|
|
99
|
+
"verify-token"?: string;
|
|
100
|
+
"p-token"?: string;
|
|
101
|
+
"P-Token"?: string;
|
|
102
|
+
"x-token"?: string;
|
|
103
|
+
"x-ai-request"?: string;
|
|
104
|
+
"X-Global-RateLimit"?: string;
|
|
105
|
+
"x-signatue"?: string;
|
|
106
|
+
"X-Token-Private"?: string;
|
|
107
|
+
"X-Token-Server"?: string;
|
|
108
|
+
"x-token-server"?: string;
|
|
109
|
+
"X-Server-Super-Admin-Token"?: string;
|
|
110
|
+
"X-Token"?: string;
|
|
111
|
+
"X-S-To-S-Sig"?: string;
|
|
112
|
+
"x-token-private"?: string;
|
|
113
|
+
"x-token-crm"?: string;
|
|
114
|
+
realIp?: string;
|
|
115
|
+
"X-Workflow-Id"?: string;
|
|
116
|
+
"X-token"?: string;
|
|
117
|
+
"X-sign"?: string;
|
|
118
|
+
"x-forwarded-for"?: string;
|
|
119
|
+
"x-real-ip"?: string;
|
|
120
|
+
Cookie?: string;
|
|
121
|
+
Origin?: string;
|
|
122
|
+
Referer?: string;
|
|
123
|
+
"Content-Type"?: string;
|
|
124
|
+
"Access-Allow-Origin"?: string;
|
|
125
|
+
authorization?: string;
|
|
126
|
+
"x-global-ratelimit"?: string;
|
|
127
|
+
"x-server-super-admin-token"?: string;
|
|
128
|
+
"x-s-to-s-sig"?: string;
|
|
129
|
+
realip?: string;
|
|
130
|
+
"x-workflow-id"?: string;
|
|
131
|
+
"x-sign"?: string;
|
|
132
|
+
cookie?: string;
|
|
133
|
+
origin?: string;
|
|
134
|
+
referer?: string;
|
|
135
|
+
"content-type"?: string;
|
|
136
|
+
"access-allow-origin"?: string;
|
|
137
|
+
"Cache-Control"?: string;
|
|
138
|
+
Connection?: string;
|
|
139
|
+
"Sse-Connection-Id"?: string;
|
|
140
|
+
connection?: string;
|
|
141
|
+
"cache-control"?: string;
|
|
142
|
+
"sse-connection-id"?: string;
|
|
143
|
+
}>;
|
|
144
|
+
ws: (ctx: ExecutionContext) => AppWs.Client;
|
|
145
|
+
rpc: (ctx: ExecutionContext) => HttpApi.Request<any, HttpApi.BaseReqQuery, import("@my-nestjs-kit/core").AppCookies, HttpApi.BaseReqParams, import("http").IncomingHttpHeaders & {
|
|
146
|
+
permission?: string;
|
|
147
|
+
Authorization?: string;
|
|
148
|
+
"Track-Id"?: string;
|
|
149
|
+
"Refresh-Token"?: string;
|
|
150
|
+
"refresh-token"?: string;
|
|
151
|
+
"track-id"?: string;
|
|
152
|
+
"User-Reference"?: string;
|
|
153
|
+
"user-reference"?: string;
|
|
154
|
+
"user-agent"?: string;
|
|
155
|
+
dnt?: string;
|
|
156
|
+
"crm-authorization"?: string;
|
|
157
|
+
"verify-token"?: string;
|
|
158
|
+
"p-token"?: string;
|
|
159
|
+
"P-Token"?: string;
|
|
160
|
+
"x-token"?: string;
|
|
161
|
+
"x-ai-request"?: string;
|
|
162
|
+
"X-Global-RateLimit"?: string;
|
|
163
|
+
"x-signatue"?: string;
|
|
164
|
+
"X-Token-Private"?: string;
|
|
165
|
+
"X-Token-Server"?: string;
|
|
166
|
+
"x-token-server"?: string;
|
|
167
|
+
"X-Server-Super-Admin-Token"?: string;
|
|
168
|
+
"X-Token"?: string;
|
|
169
|
+
"X-S-To-S-Sig"?: string;
|
|
170
|
+
"x-token-private"?: string;
|
|
171
|
+
"x-token-crm"?: string;
|
|
172
|
+
realIp?: string;
|
|
173
|
+
"X-Workflow-Id"?: string;
|
|
174
|
+
"X-token"?: string;
|
|
175
|
+
"X-sign"?: string;
|
|
176
|
+
"x-forwarded-for"?: string;
|
|
177
|
+
"x-real-ip"?: string;
|
|
178
|
+
Cookie?: string;
|
|
179
|
+
Origin?: string;
|
|
180
|
+
Referer?: string;
|
|
181
|
+
"Content-Type"?: string;
|
|
182
|
+
"Access-Allow-Origin"?: string;
|
|
183
|
+
authorization?: string;
|
|
184
|
+
"x-global-ratelimit"?: string;
|
|
185
|
+
"x-server-super-admin-token"?: string;
|
|
186
|
+
"x-s-to-s-sig"?: string;
|
|
187
|
+
realip?: string;
|
|
188
|
+
"x-workflow-id"?: string;
|
|
189
|
+
"x-sign"?: string;
|
|
190
|
+
cookie?: string;
|
|
191
|
+
origin?: string;
|
|
192
|
+
referer?: string;
|
|
193
|
+
"content-type"?: string;
|
|
194
|
+
"access-allow-origin"?: string;
|
|
195
|
+
"Cache-Control"?: string;
|
|
196
|
+
Connection?: string;
|
|
197
|
+
"Sse-Connection-Id"?: string;
|
|
198
|
+
connection?: string;
|
|
199
|
+
"cache-control"?: string;
|
|
200
|
+
"sse-connection-id"?: string;
|
|
201
|
+
}>;
|
|
202
|
+
};
|
|
203
|
+
getTarget<CtxType extends ContextType>(ctxType: CtxType, ctx: ExecutionContext): RequestTargetByCtxType[CtxType];
|
|
204
|
+
canActivateSync<CtxType extends ContextType = ContextType>({ configs, ctx, target, ctxType, }: {
|
|
205
|
+
configs: AuthConfigsMetaStorage;
|
|
206
|
+
ctx: ExecutionContext;
|
|
207
|
+
ctxType: CtxType;
|
|
208
|
+
target: RequestTargetByCtxType[CtxType];
|
|
209
|
+
}): boolean | Promise<boolean>;
|
|
210
|
+
abstract validateAsync(input: Input): Promise<boolean>;
|
|
211
|
+
abstract validate(context: ExecutionContext, configs: AuthConfigsMetaStorage): boolean | Promise<boolean>;
|
|
212
|
+
protected fail(exc: ExceptionResponseArgs): void;
|
|
213
|
+
protected failFor(input: {
|
|
214
|
+
error?: any;
|
|
215
|
+
http?: AppHttpExceptionResponse;
|
|
216
|
+
ws?: AppWsExceptionPayload;
|
|
217
|
+
}): void;
|
|
218
|
+
protected failWs(res: AppWsExceptionPayload): void;
|
|
219
|
+
}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.AbstractAuthGuard = void 0;
|
|
4
|
+
const common_1 = require("@nestjs/common");
|
|
5
|
+
const core_1 = require("@my-nestjs-kit/core");
|
|
6
|
+
const core_2 = require("@my-nestjs-kit/core");
|
|
7
|
+
const constants_1 = require("@nestjs/common/constants");
|
|
8
|
+
const GetAuthParams_decorator_1 = require("../../decorators/GetAuthParams.decorator");
|
|
9
|
+
const route_auth_configs_helper_1 = require("../../route-auth-configs.helper");
|
|
10
|
+
const Public_decorator_1 = require("../../decorators/Public.decorator");
|
|
11
|
+
var HeaderName = core_2.HttpApi.HeaderName;
|
|
12
|
+
const msgs = {
|
|
13
|
+
ACCESS_GRANTED: 'ACCESS GRANTED',
|
|
14
|
+
ACCESS_DENY: 'ACCESS DENY',
|
|
15
|
+
isDeactivated: 'DEACTIVATED',
|
|
16
|
+
modelIsInSkipList: 'Model is in skip list',
|
|
17
|
+
routeIsInSkipList: 'Route is in skip list',
|
|
18
|
+
isModelRefmeActive: 'Auth model REFME is Active',
|
|
19
|
+
isNotActive: 'IS NOT ACTIVE',
|
|
20
|
+
authConfigsNotFound: 'Auth configs not found',
|
|
21
|
+
isPublic: 'Route is public',
|
|
22
|
+
isExpired: 'Integration is expired',
|
|
23
|
+
notHasPermission: 'Integration not has permission',
|
|
24
|
+
unknownError: 'Unknown error occurred',
|
|
25
|
+
jwtCheckIsActive: 'JWT token check is ACTIVE',
|
|
26
|
+
jwtErpCheckIsActive: 'JWT Erp check is ACTIVE',
|
|
27
|
+
modelErpIsActive: 'Auth model ERP is Active',
|
|
28
|
+
tokenNotFound: 'Token not found',
|
|
29
|
+
forbiddenAction: 'Forbidden action',
|
|
30
|
+
xTokenCheckIsActive: 'Check by X-Token is ACTIVE',
|
|
31
|
+
tokenIsExpired: 'TOKEN is expired',
|
|
32
|
+
authHeaderNotFound: 'Authorization header not found',
|
|
33
|
+
isNotBearer: 'Authorization token is not Bearer token',
|
|
34
|
+
userNotFound: 'User not found',
|
|
35
|
+
unauthorized: 'Unauthorized',
|
|
36
|
+
forbiddenForModel: 'Forbidden action for this token model',
|
|
37
|
+
forbiddenForRole: 'Forbidden action for this token role',
|
|
38
|
+
forbiddenForHolder: 'Forbidden action for this token holder',
|
|
39
|
+
};
|
|
40
|
+
class AbstractAuthGuard {
|
|
41
|
+
constructor(reflector, meta) {
|
|
42
|
+
this.reflector = reflector;
|
|
43
|
+
this.meta = meta;
|
|
44
|
+
this.__logger = new common_1.Logger(AbstractAuthGuard.name);
|
|
45
|
+
this.msgs = msgs;
|
|
46
|
+
this._getTargetDict = {
|
|
47
|
+
http: (ctx) => ctx.switchToHttp().getRequest(),
|
|
48
|
+
ws: (ctx) => ctx.switchToWs().getClient(),
|
|
49
|
+
rpc: (ctx) => ctx.switchToHttp().getRequest(),
|
|
50
|
+
};
|
|
51
|
+
this._logger = new common_1.Logger(this.constructor.name);
|
|
52
|
+
}
|
|
53
|
+
canActivate(ctx) {
|
|
54
|
+
const ctxType = ctx.getType();
|
|
55
|
+
if (!this.meta.ignorePublic) {
|
|
56
|
+
const isPublic = (0, Public_decorator_1.isPublicRoute)(this.reflector, ctx.getClass(), ctx.getHandler());
|
|
57
|
+
if (isPublic) {
|
|
58
|
+
this._logger.warn(this.msgs.ACCESS_GRANTED + ' | ' + this.msgs.isPublic);
|
|
59
|
+
return true;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
const getFor = (target) => {
|
|
63
|
+
return this.reflector.get(route_auth_configs_helper_1.AuthConfigsMetaStorage.KEY, target);
|
|
64
|
+
};
|
|
65
|
+
// the route's own config wins over the controller-level one
|
|
66
|
+
const meta = getFor(ctx.getHandler()) ?? getFor(ctx.getClass());
|
|
67
|
+
if (!meta) {
|
|
68
|
+
// no auth config on a guarded route = deny (secure default); 401, not 400: the caller is not authorized
|
|
69
|
+
this.fail({
|
|
70
|
+
statusCode: common_1.HttpStatus.UNAUTHORIZED,
|
|
71
|
+
reason: this.msgs.authConfigsNotFound,
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
// Server actions are never public: they pass this (user-auth) guard only when the route declares its own
|
|
75
|
+
// guard (e.g. a server-token guard via @UseGuards) that authenticates the calling service. No such guard -> deny.
|
|
76
|
+
if (meta.isServerAction) {
|
|
77
|
+
const routeGuards = this.reflector.get(constants_1.GUARDS_METADATA, ctx.getHandler()) ?? [];
|
|
78
|
+
if (!routeGuards.length) {
|
|
79
|
+
this.fail({
|
|
80
|
+
statusCode: common_1.HttpStatus.UNAUTHORIZED,
|
|
81
|
+
reason: 'Server action route has no server guard',
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
if (!this.meta.ignorePublic)
|
|
85
|
+
return true;
|
|
86
|
+
}
|
|
87
|
+
if (!this.meta.ignorePublic && meta.isPublic) {
|
|
88
|
+
this._logger.warn(this.msgs.ACCESS_GRANTED + ' | ' + this.msgs.isPublic);
|
|
89
|
+
return true;
|
|
90
|
+
}
|
|
91
|
+
const target = this.getTarget(ctxType, ctx);
|
|
92
|
+
return this.canActivateSync({
|
|
93
|
+
configs: meta,
|
|
94
|
+
ctx,
|
|
95
|
+
target,
|
|
96
|
+
ctxType,
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
getTarget(ctxType, ctx) {
|
|
100
|
+
const getter = this._getTargetDict[ctxType];
|
|
101
|
+
return getter(ctx);
|
|
102
|
+
}
|
|
103
|
+
canActivateSync({ configs, ctx, target, ctxType, }) {
|
|
104
|
+
if (target.headers?.[HeaderName.x_token_private]) {
|
|
105
|
+
target.authParams.isSecure = true;
|
|
106
|
+
target.authParams.isServerToServer = true;
|
|
107
|
+
}
|
|
108
|
+
const skipList = this.meta?.routes?.skipList;
|
|
109
|
+
if ('path' in target) {
|
|
110
|
+
if (skipList) {
|
|
111
|
+
const url = target.path;
|
|
112
|
+
for (const route of skipList) {
|
|
113
|
+
if (url?.includes(route)) {
|
|
114
|
+
this._logger.warn(this.msgs.ACCESS_GRANTED +
|
|
115
|
+
` | [${route}] | ` +
|
|
116
|
+
this.msgs.routeIsInSkipList);
|
|
117
|
+
return true;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
if (this.meta?.models?.skipList?.length &&
|
|
123
|
+
target?.authParams instanceof GetAuthParams_decorator_1.AuthParams) {
|
|
124
|
+
const m = target.authParams.model;
|
|
125
|
+
if (this.meta?.models?.skipList?.includes(m)) {
|
|
126
|
+
this._logger.warn([this.msgs.ACCESS_GRANTED, this.msgs.routeIsInSkipList, m].join(' | '));
|
|
127
|
+
return true;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
if (this.meta?.routes?.skipList?.length && 'url' in target) {
|
|
131
|
+
const isSkipped = this.meta?.routes?.skipList.find((route) => {
|
|
132
|
+
return target.url.startsWith(route);
|
|
133
|
+
});
|
|
134
|
+
if (isSkipped) {
|
|
135
|
+
this._logger.warn([
|
|
136
|
+
this.msgs.ACCESS_GRANTED,
|
|
137
|
+
this.msgs.routeIsInSkipList,
|
|
138
|
+
target.url,
|
|
139
|
+
].join(' | '));
|
|
140
|
+
return true;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
if (this.meta.model && configs.model?.[this.meta.model] === false) {
|
|
144
|
+
this._logger.warn(this.msgs.ACCESS_GRANTED + ' | ' + this.msgs.isDeactivated);
|
|
145
|
+
return true;
|
|
146
|
+
}
|
|
147
|
+
return this.validate(ctx, configs);
|
|
148
|
+
}
|
|
149
|
+
fail(exc) {
|
|
150
|
+
this._logger.error(this.msgs.ACCESS_DENY + ' | ' + exc.reason);
|
|
151
|
+
// console.log(exc);
|
|
152
|
+
throw new core_1.AppHttpException({
|
|
153
|
+
statusCode: this.meta.failStatusCode,
|
|
154
|
+
reason: exc?.reason || exc.message,
|
|
155
|
+
...exc,
|
|
156
|
+
message: this.msgs.ACCESS_DENY,
|
|
157
|
+
meta: { ...exc.meta, guard: this.constructor.name },
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
failFor(input) {
|
|
161
|
+
if (input.ws) {
|
|
162
|
+
this.failWs(input.ws);
|
|
163
|
+
}
|
|
164
|
+
else if (input.http) {
|
|
165
|
+
this.fail(input.http);
|
|
166
|
+
}
|
|
167
|
+
else if (input.error) {
|
|
168
|
+
this.fail(input.error);
|
|
169
|
+
}
|
|
170
|
+
else {
|
|
171
|
+
this.fail({ message: 'Internal server error' });
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
//
|
|
175
|
+
// abstract validateWsAsync?(input: Input): Promise<boolean>;
|
|
176
|
+
failWs(res) {
|
|
177
|
+
this._logger.error(this.msgs.ACCESS_DENY + ' | ' + res.reason);
|
|
178
|
+
throw new core_1.AppWsException({
|
|
179
|
+
statusCode: this.meta.failStatusCode,
|
|
180
|
+
...res,
|
|
181
|
+
reason: res?.reason || res.message,
|
|
182
|
+
message: this.msgs.ACCESS_DENY,
|
|
183
|
+
meta: { ...res.meta, guard: this.constructor.name },
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
exports.AbstractAuthGuard = AbstractAuthGuard;
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { HttpException, Logger } from '@nestjs/common';
|
|
2
|
+
import { JwtAuthService, JwtTypeInput } from '../jwt/jwt-auth.service';
|
|
3
|
+
import { JwtAudienceEnum, JwtType } from '../jwt/types/enums';
|
|
4
|
+
import { AppHttpExceptionResponse, ExceptionResponseArgs } from '@my-nestjs-kit/core';
|
|
5
|
+
import { Response } from 'express';
|
|
6
|
+
import { AuthCookieOptions } from '@my-nestjs-kit/core';
|
|
7
|
+
import { AuthSessionBaseEntity } from '../entities/auth-session-base.entity';
|
|
8
|
+
export interface BaseAuthServiceMeta {
|
|
9
|
+
/** `aud` claim of the tokens this service signs and accepts */
|
|
10
|
+
jwtAudience?: JwtAudienceEnum | string;
|
|
11
|
+
cookies?: {
|
|
12
|
+
refreshTokenMaxAgeDays?: number;
|
|
13
|
+
userRefMaxAgeDay?: number;
|
|
14
|
+
refreshToken?: AuthCookieOptions;
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
export interface LoggerUserCookies {
|
|
18
|
+
access_token?: string;
|
|
19
|
+
refresh_token?: string;
|
|
20
|
+
trackId?: string;
|
|
21
|
+
reference?: string;
|
|
22
|
+
}
|
|
23
|
+
export type JwtTokensPayloadMap = Partial<Record<JwtType, any>>;
|
|
24
|
+
export declare abstract class AbstractAuthService<TokenPayloadByTokenType extends JwtTokensPayloadMap = JwtTokensPayloadMap> {
|
|
25
|
+
protected readonly jwtServ: JwtAuthService;
|
|
26
|
+
protected readonly configs: BaseAuthServiceMeta;
|
|
27
|
+
protected logger: Logger;
|
|
28
|
+
private readonly _REFRESH_TOKEN_MAX_AGE_DAYS;
|
|
29
|
+
private readonly _ACCESS_TOKEN_MAX_AGE_DAYS;
|
|
30
|
+
private readonly _USER_REF_MAX_AGE_DAYS;
|
|
31
|
+
protected constructor(configs: BaseAuthServiceMeta, jwtServ: JwtAuthService);
|
|
32
|
+
readonly _GET_REFRESH_TOKEN_MAX_AGE: (days?: number) => number;
|
|
33
|
+
readonly _GET_ACCESS_TOKEN_MAX_AGE: (days?: number) => number;
|
|
34
|
+
readonly _GET_USER_REF_MAX_AGE: (days?: number) => number;
|
|
35
|
+
private _ref;
|
|
36
|
+
readonly genRefCode: () => string;
|
|
37
|
+
signTokenAsync<TokenType extends keyof TokenPayloadByTokenType & JwtTypeInput>(tokenType: TokenType, payload: TokenPayloadByTokenType[TokenType]): Promise<string>;
|
|
38
|
+
verifyTokenAsync<TokenType extends keyof TokenPayloadByTokenType & JwtTypeInput>(tokenType: TokenType, token: string): Promise<TokenPayloadByTokenType[TokenType]>;
|
|
39
|
+
setInitialCookies(res: Response, cookies: Partial<LoggerUserCookies>): void;
|
|
40
|
+
setRefreshTokenCookie(res: Response, session: {
|
|
41
|
+
refresh_token?: string;
|
|
42
|
+
[key: string]: any;
|
|
43
|
+
}): void;
|
|
44
|
+
setInitialHeaders(res: Response, loggedUser: Partial<LoggerUserCookies>): void;
|
|
45
|
+
resetResCookies(res: Response): void;
|
|
46
|
+
toRegisteredUser: <User extends Record<string, any>>(user: User, { isSecure }?: {
|
|
47
|
+
isSecure?: boolean;
|
|
48
|
+
}) => Pick<User, "name" | "label" | "_id" | "reference" | "email" | "phone" | "registeredAt" | "verifiedAt">;
|
|
49
|
+
toLoggedSession: <Session extends AuthSessionBaseEntity<any, import("@my-nestjs-kit/core").ProviderNameEnum> & {
|
|
50
|
+
user?: any;
|
|
51
|
+
}>({ user, ...session }: Session, { withRefresh }?: {
|
|
52
|
+
withRefresh?: boolean;
|
|
53
|
+
}) => {
|
|
54
|
+
access_token: Session["access_token"];
|
|
55
|
+
session: Partial<Omit<Session, "user">>;
|
|
56
|
+
};
|
|
57
|
+
protected fail(exc: ExceptionResponseArgs | AppHttpExceptionResponse | HttpException): never;
|
|
58
|
+
private _getMaxAgeInDays;
|
|
59
|
+
private _getMaxAgeInHours;
|
|
60
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.AbstractAuthService = void 0;
|
|
4
|
+
const common_1 = require("@nestjs/common");
|
|
5
|
+
const core_1 = require("@my-nestjs-kit/core");
|
|
6
|
+
const core_2 = require("@my-nestjs-kit/core");
|
|
7
|
+
const date_fns_1 = require("date-fns");
|
|
8
|
+
const core_3 = require("@my-nestjs-kit/core");
|
|
9
|
+
const lodash_1 = require("lodash");
|
|
10
|
+
class AbstractAuthService {
|
|
11
|
+
constructor(configs, jwtServ) {
|
|
12
|
+
this.jwtServ = jwtServ;
|
|
13
|
+
this.logger = new common_1.Logger(this.constructor.name);
|
|
14
|
+
this._REFRESH_TOKEN_MAX_AGE_DAYS = 7;
|
|
15
|
+
this._ACCESS_TOKEN_MAX_AGE_DAYS = 1;
|
|
16
|
+
this._USER_REF_MAX_AGE_DAYS = 7;
|
|
17
|
+
this._GET_REFRESH_TOKEN_MAX_AGE = (days) => this._getMaxAgeInDays(days ??
|
|
18
|
+
this.configs?.cookies?.refreshTokenMaxAgeDays ??
|
|
19
|
+
this._REFRESH_TOKEN_MAX_AGE_DAYS);
|
|
20
|
+
this._GET_ACCESS_TOKEN_MAX_AGE = (days) => this._getMaxAgeInDays(days ??
|
|
21
|
+
this.configs?.cookies?.refreshTokenMaxAgeDays ??
|
|
22
|
+
this._ACCESS_TOKEN_MAX_AGE_DAYS);
|
|
23
|
+
this._GET_USER_REF_MAX_AGE = (days) => this._getMaxAgeInDays(days ??
|
|
24
|
+
this.configs?.cookies?.userRefMaxAgeDay ??
|
|
25
|
+
this._USER_REF_MAX_AGE_DAYS);
|
|
26
|
+
this._ref = new core_2.RefCode().addPrefix('ref').setAlphabet('alphanumeric');
|
|
27
|
+
this.genRefCode = () => this._ref.doMagic();
|
|
28
|
+
this.toRegisteredUser = (user, { isSecure } = {}) => {
|
|
29
|
+
return (0, lodash_1.pick)(user, [
|
|
30
|
+
'_id',
|
|
31
|
+
'email',
|
|
32
|
+
'phone',
|
|
33
|
+
'name',
|
|
34
|
+
'label',
|
|
35
|
+
'registeredAt',
|
|
36
|
+
'verifiedAt',
|
|
37
|
+
'reference',
|
|
38
|
+
]);
|
|
39
|
+
};
|
|
40
|
+
this.toLoggedSession = ({ user, ...session }, { withRefresh } = {}) => {
|
|
41
|
+
if (!session.access_token) {
|
|
42
|
+
throw new Error('Not found session.access_token');
|
|
43
|
+
}
|
|
44
|
+
const retData = {
|
|
45
|
+
...(0, lodash_1.omit)(user, ['passwordHash']),
|
|
46
|
+
access_token: session.access_token,
|
|
47
|
+
session: (0, lodash_1.omit)(session, ['refresh_token', 'access_token']),
|
|
48
|
+
};
|
|
49
|
+
if (withRefresh) {
|
|
50
|
+
Object.assign(retData, {
|
|
51
|
+
refresh_token: session.refresh_token,
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
return retData;
|
|
55
|
+
};
|
|
56
|
+
this.configs = configs;
|
|
57
|
+
}
|
|
58
|
+
signTokenAsync(tokenType, payload) {
|
|
59
|
+
return this.jwtServ.signAsync(tokenType, payload, {
|
|
60
|
+
audience: this.configs?.jwtAudience,
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
verifyTokenAsync(tokenType, token) {
|
|
64
|
+
return this.jwtServ.verifyAsync(tokenType, token, {
|
|
65
|
+
audience: this.configs?.jwtAudience,
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
setInitialCookies(res, cookies) {
|
|
69
|
+
const list = [
|
|
70
|
+
{
|
|
71
|
+
name: core_3.AppCookiesKeyEnum.refresh_token,
|
|
72
|
+
value: cookies.refresh_token,
|
|
73
|
+
options: {
|
|
74
|
+
path: this.configs?.cookies?.refreshToken?.path,
|
|
75
|
+
maxAge: this._GET_REFRESH_TOKEN_MAX_AGE(),
|
|
76
|
+
httpOnly: true,
|
|
77
|
+
sameSite: true,
|
|
78
|
+
secure: true,
|
|
79
|
+
},
|
|
80
|
+
},
|
|
81
|
+
{
|
|
82
|
+
name: core_3.AppCookiesKeyEnum.access_token,
|
|
83
|
+
value: cookies.access_token,
|
|
84
|
+
options: {
|
|
85
|
+
maxAge: this._GET_ACCESS_TOKEN_MAX_AGE(),
|
|
86
|
+
httpOnly: true,
|
|
87
|
+
sameSite: true,
|
|
88
|
+
secure: true,
|
|
89
|
+
},
|
|
90
|
+
},
|
|
91
|
+
{
|
|
92
|
+
name: core_3.AppCookiesKeyEnum.reference,
|
|
93
|
+
value: cookies?.reference,
|
|
94
|
+
options: {
|
|
95
|
+
maxAge: this._GET_USER_REF_MAX_AGE(),
|
|
96
|
+
sameSite: true,
|
|
97
|
+
},
|
|
98
|
+
},
|
|
99
|
+
{
|
|
100
|
+
name: core_3.AppCookiesKeyEnum.track_id,
|
|
101
|
+
value: cookies?.trackId,
|
|
102
|
+
options: {
|
|
103
|
+
sameSite: true,
|
|
104
|
+
},
|
|
105
|
+
},
|
|
106
|
+
];
|
|
107
|
+
for (const { name, value = '', options } of list) {
|
|
108
|
+
value && res.cookie(name, value, options);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
setRefreshTokenCookie(res, session) {
|
|
112
|
+
const data = {
|
|
113
|
+
name: core_3.AppCookiesKeyEnum.refresh_token,
|
|
114
|
+
value: session.refresh_token,
|
|
115
|
+
options: {
|
|
116
|
+
path: this.configs?.cookies?.refreshToken?.path,
|
|
117
|
+
maxAge: this._GET_REFRESH_TOKEN_MAX_AGE(),
|
|
118
|
+
httpOnly: true,
|
|
119
|
+
secure: true,
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
res.cookie(data.name, data.value, data.options);
|
|
123
|
+
}
|
|
124
|
+
setInitialHeaders(res, loggedUser) {
|
|
125
|
+
const headers = [
|
|
126
|
+
{
|
|
127
|
+
name: core_3.AppCookiesKeyEnum.refresh_token,
|
|
128
|
+
value: loggedUser.refresh_token,
|
|
129
|
+
},
|
|
130
|
+
{
|
|
131
|
+
name: core_3.AppCookiesKeyEnum.track_id,
|
|
132
|
+
value: loggedUser?.trackId,
|
|
133
|
+
},
|
|
134
|
+
];
|
|
135
|
+
for (const { name, value = '', options } of headers) {
|
|
136
|
+
value && res.setHeader(name, value);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
resetResCookies(res) {
|
|
140
|
+
const cookies = [
|
|
141
|
+
{
|
|
142
|
+
name: core_3.AppCookiesKeyEnum.refresh_token,
|
|
143
|
+
options: {
|
|
144
|
+
path: this.configs?.cookies?.refreshToken?.path,
|
|
145
|
+
},
|
|
146
|
+
},
|
|
147
|
+
{ name: core_3.AppCookiesKeyEnum.reference },
|
|
148
|
+
{ name: core_3.AppCookiesKeyEnum.role },
|
|
149
|
+
{ name: core_3.AppCookiesKeyEnum.track_id },
|
|
150
|
+
];
|
|
151
|
+
for (const { name, value = '', options } of cookies) {
|
|
152
|
+
res.cookie(name, value, options);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
fail(exc) {
|
|
156
|
+
if (exc instanceof core_1.AppHttpException) {
|
|
157
|
+
const res = exc.getResponse();
|
|
158
|
+
(0, lodash_1.set)(res, 'meta.service', this.constructor.name);
|
|
159
|
+
throw new core_1.AppHttpException({
|
|
160
|
+
statusCode: common_1.HttpStatus.UNAUTHORIZED,
|
|
161
|
+
...res,
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
if (exc instanceof common_1.HttpException) {
|
|
165
|
+
const raw = exc.getResponse();
|
|
166
|
+
const res = typeof raw === 'string' ? { message: raw } : raw;
|
|
167
|
+
(0, lodash_1.set)(res, 'statusCode', common_1.HttpStatus.UNAUTHORIZED);
|
|
168
|
+
(0, lodash_1.set)(res, 'meta.service', this.constructor.name);
|
|
169
|
+
throw new core_1.AppHttpException(res);
|
|
170
|
+
}
|
|
171
|
+
(0, lodash_1.set)(exc, 'meta.service', this.constructor.name);
|
|
172
|
+
throw new core_1.AppHttpException({
|
|
173
|
+
statusCode: common_1.HttpStatus.UNAUTHORIZED,
|
|
174
|
+
...exc,
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
_getMaxAgeInDays(days) {
|
|
178
|
+
return (0, date_fns_1.addDays)(Date.now(), days).valueOf() - Date.now();
|
|
179
|
+
}
|
|
180
|
+
_getMaxAgeInHours(hours) {
|
|
181
|
+
return (0, date_fns_1.addHours)(Date.now(), hours).valueOf() - Date.now();
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
exports.AbstractAuthService = AbstractAuthService;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { AbstractAppController } from '@my-nestjs-kit/core';
|
|
2
|
+
import { JwtAuthServiceAbstract } from './jwt-auth-service-abstract';
|
|
3
|
+
import { HttpSuccessRes } from '@my-nestjs-kit/core';
|
|
4
|
+
import { AuthSessionBaseEntity } from '../entities/auth-session-base.entity';
|
|
5
|
+
export declare class GetAuthVerificationTokens {
|
|
6
|
+
email: string;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Server-to-server verification endpoints (they return verification codes/tokens).
|
|
10
|
+
* `isServerAction` routes are denied by the kit auth guards unless the subclass adds a server guard,
|
|
11
|
+
* e.g. `@UseGuards(ServerActionGuard)` on an override — never expose them to end users.
|
|
12
|
+
*/
|
|
13
|
+
export declare abstract class JwtAuthControllerAbstract<Session extends AuthSessionBaseEntity = AuthSessionBaseEntity> extends AbstractAppController {
|
|
14
|
+
protected abstract readonly authService: JwtAuthServiceAbstract<Session>;
|
|
15
|
+
getVerificationInfo(query: GetAuthVerificationTokens): Promise<HttpSuccessRes<{
|
|
16
|
+
code?: string;
|
|
17
|
+
token?: string;
|
|
18
|
+
Bearer?: string;
|
|
19
|
+
email: string;
|
|
20
|
+
}, any>>;
|
|
21
|
+
setVerificationInfo(query: GetAuthVerificationTokens): Promise<HttpSuccessRes<{
|
|
22
|
+
code?: string;
|
|
23
|
+
token?: string;
|
|
24
|
+
Bearer?: string;
|
|
25
|
+
email: string;
|
|
26
|
+
}, any>>;
|
|
27
|
+
deleteVerificationInfo(query: GetAuthVerificationTokens): Promise<HttpSuccessRes<{
|
|
28
|
+
code?: boolean;
|
|
29
|
+
token?: boolean;
|
|
30
|
+
Bearer?: boolean;
|
|
31
|
+
email: string;
|
|
32
|
+
}, any>>;
|
|
33
|
+
}
|