@lark-apaas/nestjs-authnpaas 1.0.2-alpha.2 → 1.0.2-alpha.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.
- package/README.md +43 -0
- package/dist/index.cjs +285 -11
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +49 -1
- package/dist/index.d.ts +49 -1
- package/dist/index.js +277 -5
- package/dist/index.js.map +1 -1
- package/package.json +6 -7
package/README.md
CHANGED
|
@@ -9,12 +9,15 @@
|
|
|
9
9
|
- [快速开始](#快速开始)
|
|
10
10
|
- [装饰器](#装饰器)
|
|
11
11
|
- [@NeedLogin()](#needlogin)
|
|
12
|
+
- [服务](#服务)
|
|
13
|
+
- [AuthNPaasService](#authnpaasservice)
|
|
12
14
|
- [工作原理](#工作原理)
|
|
13
15
|
|
|
14
16
|
## 功能
|
|
15
17
|
|
|
16
18
|
- **身份验证检查**: 确保用户在访问受保护端点之前已经登录。
|
|
17
19
|
- **登录重定向**: 自动将未经身份验证的用户重定向到登录 URL。
|
|
20
|
+
- **用户 ID 转换**: 支持妙搭用户 ID 与飞书用户 ID 互转。
|
|
18
21
|
|
|
19
22
|
## 安装
|
|
20
23
|
|
|
@@ -87,6 +90,46 @@ export class ApiController {
|
|
|
87
90
|
}
|
|
88
91
|
```
|
|
89
92
|
|
|
93
|
+
## 服务
|
|
94
|
+
|
|
95
|
+
### AuthNPaasService
|
|
96
|
+
|
|
97
|
+
`AuthNPaasService` 提供妙搭用户 ID 与飞书用户 ID 的转换能力。模块注册后即可通过依赖注入使用。
|
|
98
|
+
|
|
99
|
+
```typescript
|
|
100
|
+
import { Injectable } from '@nestjs/common';
|
|
101
|
+
import { AuthNPaasService } from '@lark-apaas/nestjs-authnpaas';
|
|
102
|
+
|
|
103
|
+
@Injectable()
|
|
104
|
+
export class MyService {
|
|
105
|
+
constructor(private readonly authn: AuthNPaasService) {}
|
|
106
|
+
|
|
107
|
+
async example() {
|
|
108
|
+
// 获取当前登录用户的飞书 user_id
|
|
109
|
+
const larkUserId = await this.authn.getCurrentUserLarkUserId();
|
|
110
|
+
// => 'xxx' | null
|
|
111
|
+
|
|
112
|
+
// 批量转换妙搭 userId → 飞书 user_id(最多 100 个)
|
|
113
|
+
const larkUserIds = await this.authn.getBatchLarkUserIds(['uid1', 'uid2']);
|
|
114
|
+
// => ['lark_id_1', 'lark_id_2'] 顺序与输入对应,找不到的为 null
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
#### getCurrentUserLarkUserId
|
|
120
|
+
|
|
121
|
+
从请求上下文获取当前妙搭 userId,调用平台接口转换为飞书 user_id。
|
|
122
|
+
|
|
123
|
+
- **返回值**: `Promise<string | null>` — 飞书 user_id,未登录或转换失败返回 `null`
|
|
124
|
+
|
|
125
|
+
#### getBatchLarkUserIds
|
|
126
|
+
|
|
127
|
+
批量将妙搭 userId 转换为飞书 user_id。
|
|
128
|
+
|
|
129
|
+
- **参数**: `userIds: string[]` — 妙搭用户 ID 列表,最多 100 个
|
|
130
|
+
- **返回值**: `Promise<(string | null)[]>` — 飞书 user_id 数组,与输入顺序一一对应,转换失败的项为 `null`
|
|
131
|
+
- **异常**: 当 `userIds` 超过 100 个时抛出错误
|
|
132
|
+
|
|
90
133
|
## 工作原理
|
|
91
134
|
|
|
92
135
|
### AuthNPaasGuard
|
package/dist/index.cjs
CHANGED
|
@@ -22,8 +22,10 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
22
22
|
var index_exports = {};
|
|
23
23
|
__export(index_exports, {
|
|
24
24
|
AUTHNPAAS_MODULE_OPTIONS: () => AUTHNPAAS_MODULE_OPTIONS,
|
|
25
|
+
AuthNPaasController: () => AuthNPaasController,
|
|
25
26
|
AuthNPaasGuard: () => AuthNPaasGuard,
|
|
26
27
|
AuthNPaasModule: () => AuthNPaasModule,
|
|
28
|
+
AuthNPaasService: () => AuthNPaasService,
|
|
27
29
|
IS_PUBLIC_KEY: () => IS_PUBLIC_KEY,
|
|
28
30
|
NEED_LOGIN_KEY: () => NEED_LOGIN_KEY,
|
|
29
31
|
NeedLogin: () => NeedLogin,
|
|
@@ -32,11 +34,11 @@ __export(index_exports, {
|
|
|
32
34
|
module.exports = __toCommonJS(index_exports);
|
|
33
35
|
|
|
34
36
|
// src/authnpaas.module.ts
|
|
35
|
-
var
|
|
37
|
+
var import_common4 = require("@nestjs/common");
|
|
36
38
|
var import_core2 = require("@nestjs/core");
|
|
37
39
|
|
|
38
40
|
// src/const.ts
|
|
39
|
-
var AUTHNPAAS_MODULE_OPTIONS = Symbol("AUTHNPAAS_MODULE_OPTIONS");
|
|
41
|
+
var AUTHNPAAS_MODULE_OPTIONS = /* @__PURE__ */ Symbol("AUTHNPAAS_MODULE_OPTIONS");
|
|
40
42
|
var NEED_LOGIN_KEY = "authnpaas:needLogin";
|
|
41
43
|
|
|
42
44
|
// src/guards/authnpaas.guard.ts
|
|
@@ -85,7 +87,9 @@ AuthNPaasGuard = _ts_decorate([
|
|
|
85
87
|
])
|
|
86
88
|
], AuthNPaasGuard);
|
|
87
89
|
|
|
88
|
-
// src/authnpaas.
|
|
90
|
+
// src/services/authnpaas.service.ts
|
|
91
|
+
var import_common2 = require("@nestjs/common");
|
|
92
|
+
var import_nestjs_common = require("@lark-apaas/nestjs-common");
|
|
89
93
|
function _ts_decorate2(decorators, target, key, desc) {
|
|
90
94
|
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
91
95
|
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
@@ -93,6 +97,269 @@ function _ts_decorate2(decorators, target, key, desc) {
|
|
|
93
97
|
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
94
98
|
}
|
|
95
99
|
__name(_ts_decorate2, "_ts_decorate");
|
|
100
|
+
function _ts_metadata2(k, v) {
|
|
101
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
102
|
+
}
|
|
103
|
+
__name(_ts_metadata2, "_ts_metadata");
|
|
104
|
+
function _ts_param(paramIndex, decorator) {
|
|
105
|
+
return function(target, key) {
|
|
106
|
+
decorator(target, key, paramIndex);
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
__name(_ts_param, "_ts_param");
|
|
110
|
+
var SDK_MODULE = "authn";
|
|
111
|
+
var CONVERT_TYPE_FORCE_TO_FEISHU = 30;
|
|
112
|
+
var AuthNPaasService = class _AuthNPaasService {
|
|
113
|
+
static {
|
|
114
|
+
__name(this, "AuthNPaasService");
|
|
115
|
+
}
|
|
116
|
+
httpClient;
|
|
117
|
+
obs;
|
|
118
|
+
requestContext;
|
|
119
|
+
logger = new import_common2.Logger(_AuthNPaasService.name);
|
|
120
|
+
constructor(httpClient, obs, requestContext) {
|
|
121
|
+
this.httpClient = httpClient;
|
|
122
|
+
this.obs = obs;
|
|
123
|
+
this.requestContext = requestContext;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* 获取当前登录用户的飞书 user_id
|
|
127
|
+
*
|
|
128
|
+
* 从请求上下文获取当前妙搭 userId,调用转换接口获取对应的飞书 user_id
|
|
129
|
+
*
|
|
130
|
+
* @returns 飞书 user_id,如果当前用户未登录或转换失败返回 null
|
|
131
|
+
*/
|
|
132
|
+
async getCurrentUserLarkUserId() {
|
|
133
|
+
const userId = this.requestContext.get("userId");
|
|
134
|
+
if (!userId) {
|
|
135
|
+
this.logger.warn("getCurrentUserLarkUserId: no userId in request context");
|
|
136
|
+
return null;
|
|
137
|
+
}
|
|
138
|
+
const items = await this.batchConvertUserIds("getCurrentUserLarkUserId", [
|
|
139
|
+
userId
|
|
140
|
+
]);
|
|
141
|
+
if (!items || items.length === 0) {
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
return items[0].targetUserID || null;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* 批量将妙搭 userId 转换为飞书 user_id
|
|
148
|
+
*
|
|
149
|
+
* @param userIds - 妙搭用户 ID 列表,最多 100 个
|
|
150
|
+
* @returns 飞书 user_id 数组,顺序与输入对应,转换失败的项为 null
|
|
151
|
+
*/
|
|
152
|
+
async getBatchLarkUserIds(userIds) {
|
|
153
|
+
if (!userIds || userIds.length === 0) {
|
|
154
|
+
return [];
|
|
155
|
+
}
|
|
156
|
+
if (userIds.length > 100) {
|
|
157
|
+
throw new Error("userIds length must not exceed 100");
|
|
158
|
+
}
|
|
159
|
+
const items = await this.batchConvertUserIds("getBatchLarkUserIds", userIds);
|
|
160
|
+
const mapping = new Map(items.map((item) => [
|
|
161
|
+
item.sourceUserID,
|
|
162
|
+
item.targetUserID
|
|
163
|
+
]));
|
|
164
|
+
return userIds.map((id) => mapping.get(id) ?? null);
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* 调用批量转换接口(带可观测性)
|
|
168
|
+
*/
|
|
169
|
+
async batchConvertUserIds(method, userIds) {
|
|
170
|
+
const appId = this.requestContext.get("appId");
|
|
171
|
+
if (!appId) {
|
|
172
|
+
this.logger.warn(`${method}: no appId in request context`);
|
|
173
|
+
return [];
|
|
174
|
+
}
|
|
175
|
+
const url = `/v1/app/${appId}/account/user/convert`;
|
|
176
|
+
const body = {
|
|
177
|
+
convertType: CONVERT_TYPE_FORCE_TO_FEISHU,
|
|
178
|
+
userIDList: userIds
|
|
179
|
+
};
|
|
180
|
+
const spanName = `${SDK_MODULE}.${method}`;
|
|
181
|
+
const spanAttrs = {
|
|
182
|
+
module: SDK_MODULE,
|
|
183
|
+
method,
|
|
184
|
+
source_type: "platform",
|
|
185
|
+
paas_attributes_module: SDK_MODULE,
|
|
186
|
+
http_method: "POST",
|
|
187
|
+
path: url
|
|
188
|
+
};
|
|
189
|
+
const logAttrs = {
|
|
190
|
+
source_type: "platform",
|
|
191
|
+
paas_attributes_module: SDK_MODULE
|
|
192
|
+
};
|
|
193
|
+
return this.obs.trace(spanName, async (span) => {
|
|
194
|
+
span.setAttributes(spanAttrs);
|
|
195
|
+
const elapsed = (0, import_nestjs_common.createTimer)();
|
|
196
|
+
try {
|
|
197
|
+
this.logger.log(`[batchConvertUserIds] request: ${url} ${JSON.stringify(body)}`);
|
|
198
|
+
const response = await this.httpClient.post(url, body);
|
|
199
|
+
const logId = response.headers?.get?.("x-tt-logid") ?? "";
|
|
200
|
+
const raw = await response.text();
|
|
201
|
+
const durationMs = elapsed();
|
|
202
|
+
this.logger.log(`[batchConvertUserIds] response: status=${response.status} ok=${response.ok} logId=${logId} raw=${raw}`);
|
|
203
|
+
if (!response.ok) {
|
|
204
|
+
span.setAttributes({
|
|
205
|
+
duration_ms: durationMs,
|
|
206
|
+
success: false,
|
|
207
|
+
error: `HTTP ${response.status}`,
|
|
208
|
+
"x-tt-logid": logId
|
|
209
|
+
});
|
|
210
|
+
this.logger.warn(JSON.stringify({
|
|
211
|
+
method,
|
|
212
|
+
path: url,
|
|
213
|
+
duration_ms: durationMs,
|
|
214
|
+
success: false,
|
|
215
|
+
error: `HTTP ${response.status} ${response.statusText}`,
|
|
216
|
+
"x-tt-logid": logId,
|
|
217
|
+
params: {
|
|
218
|
+
convertType: CONVERT_TYPE_FORCE_TO_FEISHU,
|
|
219
|
+
count: userIds.length
|
|
220
|
+
}
|
|
221
|
+
}), logAttrs);
|
|
222
|
+
return [];
|
|
223
|
+
}
|
|
224
|
+
const result = raw ? JSON.parse(raw) : {};
|
|
225
|
+
if (String(result.status_code) !== "0" && result.status_code !== void 0) {
|
|
226
|
+
const errMsg = `[${result.status_code}] ${result.status_message || result.error_msg}`;
|
|
227
|
+
span.setAttributes({
|
|
228
|
+
duration_ms: durationMs,
|
|
229
|
+
success: false,
|
|
230
|
+
error: errMsg,
|
|
231
|
+
"x-tt-logid": logId
|
|
232
|
+
});
|
|
233
|
+
this.logger.error(JSON.stringify({
|
|
234
|
+
method,
|
|
235
|
+
path: url,
|
|
236
|
+
duration_ms: durationMs,
|
|
237
|
+
success: false,
|
|
238
|
+
error: errMsg,
|
|
239
|
+
"x-tt-logid": logId,
|
|
240
|
+
params: {
|
|
241
|
+
convertType: CONVERT_TYPE_FORCE_TO_FEISHU,
|
|
242
|
+
count: userIds.length
|
|
243
|
+
}
|
|
244
|
+
}), logAttrs);
|
|
245
|
+
return [];
|
|
246
|
+
}
|
|
247
|
+
const items = result.data?.items ?? [];
|
|
248
|
+
span.setAttributes({
|
|
249
|
+
duration_ms: durationMs,
|
|
250
|
+
success: true,
|
|
251
|
+
"x-tt-logid": logId,
|
|
252
|
+
result_count: items.length
|
|
253
|
+
});
|
|
254
|
+
this.logger.log(JSON.stringify({
|
|
255
|
+
method,
|
|
256
|
+
path: url,
|
|
257
|
+
duration_ms: durationMs,
|
|
258
|
+
success: true,
|
|
259
|
+
"x-tt-logid": logId,
|
|
260
|
+
params: {
|
|
261
|
+
convertType: CONVERT_TYPE_FORCE_TO_FEISHU,
|
|
262
|
+
count: userIds.length
|
|
263
|
+
},
|
|
264
|
+
result_count: items.length,
|
|
265
|
+
response: raw.length > 1024 ? raw.slice(0, 1024) + "..." : raw
|
|
266
|
+
}), logAttrs);
|
|
267
|
+
return items;
|
|
268
|
+
} catch (error) {
|
|
269
|
+
const durationMs = elapsed();
|
|
270
|
+
const errMsg = error instanceof Error ? error.message : String(error);
|
|
271
|
+
const logId = error?.headers?.get?.("x-tt-logid") ?? error?.response?.headers?.["x-tt-logid"] ?? error?.logId ?? "";
|
|
272
|
+
this.logger.error(`[batchConvertUserIds] CATCH: ${errMsg} logId=${logId}`);
|
|
273
|
+
span.setAttributes({
|
|
274
|
+
duration_ms: durationMs,
|
|
275
|
+
success: false,
|
|
276
|
+
error: errMsg
|
|
277
|
+
});
|
|
278
|
+
this.logger.warn(JSON.stringify({
|
|
279
|
+
method,
|
|
280
|
+
path: url,
|
|
281
|
+
duration_ms: durationMs,
|
|
282
|
+
success: false,
|
|
283
|
+
error: errMsg,
|
|
284
|
+
params: {
|
|
285
|
+
convertType: CONVERT_TYPE_FORCE_TO_FEISHU,
|
|
286
|
+
count: userIds.length
|
|
287
|
+
}
|
|
288
|
+
}), logAttrs);
|
|
289
|
+
return [];
|
|
290
|
+
}
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
AuthNPaasService = _ts_decorate2([
|
|
295
|
+
(0, import_common2.Injectable)(),
|
|
296
|
+
_ts_param(0, (0, import_common2.Inject)(import_nestjs_common.PLATFORM_HTTP_CLIENT)),
|
|
297
|
+
_ts_param(1, (0, import_common2.Inject)(import_nestjs_common.OBSERVABLE_SERVICE)),
|
|
298
|
+
_ts_metadata2("design:type", Function),
|
|
299
|
+
_ts_metadata2("design:paramtypes", [
|
|
300
|
+
typeof PlatformHttpClient === "undefined" ? Object : PlatformHttpClient,
|
|
301
|
+
typeof ObservableService === "undefined" ? Object : ObservableService,
|
|
302
|
+
typeof import_nestjs_common.RequestContextService === "undefined" ? Object : import_nestjs_common.RequestContextService
|
|
303
|
+
])
|
|
304
|
+
], AuthNPaasService);
|
|
305
|
+
|
|
306
|
+
// src/controllers/authnpaas.controller.ts
|
|
307
|
+
var import_common3 = require("@nestjs/common");
|
|
308
|
+
var import_swagger = require("@nestjs/swagger");
|
|
309
|
+
function _ts_decorate3(decorators, target, key, desc) {
|
|
310
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
311
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
312
|
+
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;
|
|
313
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
314
|
+
}
|
|
315
|
+
__name(_ts_decorate3, "_ts_decorate");
|
|
316
|
+
function _ts_metadata3(k, v) {
|
|
317
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
318
|
+
}
|
|
319
|
+
__name(_ts_metadata3, "_ts_metadata");
|
|
320
|
+
var AuthNPaasController = class {
|
|
321
|
+
static {
|
|
322
|
+
__name(this, "AuthNPaasController");
|
|
323
|
+
}
|
|
324
|
+
authnService;
|
|
325
|
+
constructor(authnService) {
|
|
326
|
+
this.authnService = authnService;
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* 获取当前登录用户的飞书 user_id
|
|
330
|
+
*
|
|
331
|
+
* GET /api/authnpaas/lark-user-id
|
|
332
|
+
*/
|
|
333
|
+
async getCurrentUserLarkUserId() {
|
|
334
|
+
const larkUserId = await this.authnService.getCurrentUserLarkUserId();
|
|
335
|
+
return {
|
|
336
|
+
lark_user_id: larkUserId
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
};
|
|
340
|
+
_ts_decorate3([
|
|
341
|
+
(0, import_common3.Get)("lark-user-id"),
|
|
342
|
+
_ts_metadata3("design:type", Function),
|
|
343
|
+
_ts_metadata3("design:paramtypes", []),
|
|
344
|
+
_ts_metadata3("design:returntype", Promise)
|
|
345
|
+
], AuthNPaasController.prototype, "getCurrentUserLarkUserId", null);
|
|
346
|
+
AuthNPaasController = _ts_decorate3([
|
|
347
|
+
(0, import_swagger.ApiExcludeController)(),
|
|
348
|
+
(0, import_common3.Controller)("api/authnpaas"),
|
|
349
|
+
_ts_metadata3("design:type", Function),
|
|
350
|
+
_ts_metadata3("design:paramtypes", [
|
|
351
|
+
typeof AuthNPaasService === "undefined" ? Object : AuthNPaasService
|
|
352
|
+
])
|
|
353
|
+
], AuthNPaasController);
|
|
354
|
+
|
|
355
|
+
// src/authnpaas.module.ts
|
|
356
|
+
function _ts_decorate4(decorators, target, key, desc) {
|
|
357
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
358
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
359
|
+
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;
|
|
360
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
361
|
+
}
|
|
362
|
+
__name(_ts_decorate4, "_ts_decorate");
|
|
96
363
|
var AuthNPaasModule = class _AuthNPaasModule {
|
|
97
364
|
static {
|
|
98
365
|
__name(this, "AuthNPaasModule");
|
|
@@ -101,7 +368,9 @@ var AuthNPaasModule = class _AuthNPaasModule {
|
|
|
101
368
|
return {
|
|
102
369
|
module: _AuthNPaasModule,
|
|
103
370
|
global: true,
|
|
104
|
-
controllers: [
|
|
371
|
+
controllers: [
|
|
372
|
+
AuthNPaasController
|
|
373
|
+
],
|
|
105
374
|
providers: [
|
|
106
375
|
// 配置提供者
|
|
107
376
|
{
|
|
@@ -114,37 +383,42 @@ var AuthNPaasModule = class _AuthNPaasModule {
|
|
|
114
383
|
import_core2.Reflector,
|
|
115
384
|
// 服务提供者
|
|
116
385
|
AuthNPaasGuard,
|
|
386
|
+
AuthNPaasService,
|
|
117
387
|
// 守卫提供者
|
|
118
388
|
{
|
|
119
389
|
provide: import_core2.APP_GUARD,
|
|
120
390
|
useClass: AuthNPaasGuard
|
|
121
391
|
}
|
|
122
392
|
],
|
|
123
|
-
exports: [
|
|
393
|
+
exports: [
|
|
394
|
+
AuthNPaasService
|
|
395
|
+
]
|
|
124
396
|
};
|
|
125
397
|
}
|
|
126
398
|
};
|
|
127
|
-
AuthNPaasModule =
|
|
128
|
-
(0,
|
|
399
|
+
AuthNPaasModule = _ts_decorate4([
|
|
400
|
+
(0, import_common4.Module)({})
|
|
129
401
|
], AuthNPaasModule);
|
|
130
402
|
|
|
131
403
|
// src/decorators/public.decorator.ts
|
|
132
|
-
var
|
|
404
|
+
var import_common5 = require("@nestjs/common");
|
|
133
405
|
var IS_PUBLIC_KEY = "isPublic";
|
|
134
|
-
var Public = /* @__PURE__ */ __name(() => (0,
|
|
406
|
+
var Public = /* @__PURE__ */ __name(() => (0, import_common5.SetMetadata)(IS_PUBLIC_KEY, true), "Public");
|
|
135
407
|
|
|
136
408
|
// src/decorators/need-login.decorator.ts
|
|
137
|
-
var
|
|
409
|
+
var import_common6 = require("@nestjs/common");
|
|
138
410
|
var NeedLogin = /* @__PURE__ */ __name((loginPath) => {
|
|
139
|
-
return (0,
|
|
411
|
+
return (0, import_common6.SetMetadata)(NEED_LOGIN_KEY, {
|
|
140
412
|
loginPath
|
|
141
413
|
});
|
|
142
414
|
}, "NeedLogin");
|
|
143
415
|
// Annotate the CommonJS export names for ESM import in node:
|
|
144
416
|
0 && (module.exports = {
|
|
145
417
|
AUTHNPAAS_MODULE_OPTIONS,
|
|
418
|
+
AuthNPaasController,
|
|
146
419
|
AuthNPaasGuard,
|
|
147
420
|
AuthNPaasModule,
|
|
421
|
+
AuthNPaasService,
|
|
148
422
|
IS_PUBLIC_KEY,
|
|
149
423
|
NEED_LOGIN_KEY,
|
|
150
424
|
NeedLogin,
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/authnpaas.module.ts","../src/const.ts","../src/guards/authnpaas.guard.ts","../src/decorators/public.decorator.ts","../src/decorators/need-login.decorator.ts"],"sourcesContent":["/**\n * @lark-apaas/nestjs-authnpaas\n *\n * 基于 CASL 的 NestJS 权限管理模块\n * 提供角色、权限点位、环境等多维度的鉴权能力\n */\n\n// 主模块\nexport { AuthNPaasModule } from './authnpaas.module';\n\n// 装饰器\nexport * from './decorators';\n\n// 守卫\nexport * from './guards';\n\n// 类型定义\nexport * from './types';\n\n// 常量\nexport * from './const';\n","import { DynamicModule, Module } from '@nestjs/common';\nimport { APP_GUARD, Reflector } from '@nestjs/core';\nimport { AuthNPaasModuleOptions } from './types';\nimport { AUTHNPAAS_MODULE_OPTIONS } from './const';\nimport { AuthNPaasGuard } from './guards/authnpaas.guard';\n\n@Module({})\nexport class AuthNPaasModule {\n static forRoot(options?: AuthNPaasModuleOptions): DynamicModule {\n return {\n module: AuthNPaasModule,\n global: true,\n controllers: [],\n providers: [\n // 配置提供者\n {\n provide: AUTHNPAAS_MODULE_OPTIONS,\n useValue: {\n ...(options || {}),\n },\n },\n // 核心服务\n Reflector,\n // 服务提供者\n AuthNPaasGuard,\n // 守卫提供者\n {\n provide: APP_GUARD,\n useClass: AuthNPaasGuard,\n },\n ],\n exports: [],\n };\n }\n}\n","/**\n * 常量\n */\n\n/** AuthNPaas 模块选项 Token */\nexport const AUTHNPAAS_MODULE_OPTIONS = Symbol('AUTHNPAAS_MODULE_OPTIONS');\n\n/**\n * 元数据键\n */\n\n/** 需要登录元数据键 */\nexport const NEED_LOGIN_KEY = 'authnpaas:needLogin';\n","import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';\nimport { Response } from 'express';\nimport { Reflector } from '@nestjs/core';\nimport { NEED_LOGIN_KEY } from '../const';\n\n/**\n * AuthNPaas 守卫\n * 负责协调所有鉴权检查,具体检查逻辑委托给 PermissionService\n */\n@Injectable()\nexport class AuthNPaasGuard implements CanActivate {\n constructor(private reflector: Reflector) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const http = context.switchToHttp();\n const request = http.getRequest();\n const response = http.getResponse<Response>();\n\n const { userId, loginUrl } = request.userContext || {};\n\n // 读取 NeedLogin 元数据并标记到请求对象,供异常过滤器使用\n const needLoginMeta = this.reflector.getAllAndOverride<{\n loginPath?: string;\n }>(NEED_LOGIN_KEY, [context.getHandler(), context.getClass()]);\n\n // NeedLogin 且无 userId -> 在守卫内透出跳转 url\n if (needLoginMeta && !userId && loginUrl) {\n response.setHeader('x-login-url', loginUrl);\n throw new UnauthorizedException('未登录');\n }\n\n return true;\n }\n}\n","import { SetMetadata } from '@nestjs/common';\n\n/**\n * Public 装饰器的元数据键\n */\nexport const IS_PUBLIC_KEY = 'isPublic';\n\n/**\n * 标记接口为公开接口,跳过 AuthNPaasGuard 的鉴权检查\n * \n * @example\n * ```typescript\n * @Controller('mock-api/users')\n * @Public() // 控制器级别\n * export class MockPermissionController {\n * @Get(':userId/permissions')\n * getUserPermissions() {}\n * }\n * \n * // 或者在方法级别\n * @Controller('api')\n * export class ApiController {\n * @Get('public-info')\n * @Public() // 方法级别\n * getPublicInfo() {}\n * }\n * ```\n */\nexport const Public = () => SetMetadata(IS_PUBLIC_KEY, true);\n\n","import { SetMetadata } from '@nestjs/common';\nimport { NEED_LOGIN_KEY } from '../const';\n\n/**\n * NeedLogin 装饰器\n * 标记接口需要登录。如果鉴权失败(如 401/403),异常过滤器会将请求重定向到登录页。\n * 可选地传入登录页路径,默认 '/login'。\n */\nexport const NeedLogin = (loginPath?: string): MethodDecorator & ClassDecorator => {\n return SetMetadata(NEED_LOGIN_KEY, { loginPath });\n};\n\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;ACAA,IAAAA,iBAAsC;AACtC,IAAAC,eAAqC;;;ACI9B,IAAMC,2BAA2BC,OAAO,0BAAA;AAOxC,IAAMC,iBAAiB;;;ACZ9B,oBAAiF;AAEjF,kBAA0B;;;;;;;;;;;;AAQnB,IAAMC,iBAAN,MAAMA;SAAAA;;;;EACX,YAAoBC,WAAsB;SAAtBA,YAAAA;EAAuB;EAE3C,MAAMC,YAAYC,SAA6C;AAC7D,UAAMC,OAAOD,QAAQE,aAAY;AACjC,UAAMC,UAAUF,KAAKG,WAAU;AAC/B,UAAMC,WAAWJ,KAAKK,YAAW;AAEjC,UAAM,EAAEC,QAAQC,SAAQ,IAAKL,QAAQM,eAAe,CAAC;AAGrD,UAAMC,gBAAgB,KAAKZ,UAAUa,kBAElCC,gBAAgB;MAACZ,QAAQa,WAAU;MAAIb,QAAQc,SAAQ;KAAG;AAG7D,QAAIJ,iBAAiB,CAACH,UAAUC,UAAU;AACxCH,eAASU,UAAU,eAAeP,QAAAA;AAClC,YAAM,IAAIQ,oCAAsB,oBAAA;IAClC;AAEA,WAAO;EACT;AACF;;;;;;;;;;;;;;;;;AF1BO,IAAMC,kBAAN,MAAMA,iBAAAA;SAAAA;;;EACX,OAAOC,QAAQC,SAAiD;AAC9D,WAAO;MACLC,QAAQH;MACRI,QAAQ;MACRC,aAAa,CAAA;MACbC,WAAW;;QAET;UACEC,SAASC;UACTC,UAAU;YACR,GAAIP,WAAW,CAAC;UAClB;QACF;;QAEAQ;;QAEAC;;QAEA;UACEJ,SAASK;UACTC,UAAUF;QACZ;;MAEFG,SAAS,CAAA;IACX;EACF;AACF;;;;;;AGlCA,IAAAC,iBAA4B;AAKrB,IAAMC,gBAAgB;AAuBtB,IAAMC,SAAS,iCAAMC,4BAAYF,eAAe,IAAA,GAAjC;;;AC5BtB,IAAAG,iBAA4B;AAQrB,IAAMC,YAAY,wBAACC,cAAAA;AACxB,aAAOC,4BAAYC,gBAAgB;IAAEF;EAAU,CAAA;AACjD,GAFyB;","names":["import_common","import_core","AUTHNPAAS_MODULE_OPTIONS","Symbol","NEED_LOGIN_KEY","AuthNPaasGuard","reflector","canActivate","context","http","switchToHttp","request","getRequest","response","getResponse","userId","loginUrl","userContext","needLoginMeta","getAllAndOverride","NEED_LOGIN_KEY","getHandler","getClass","setHeader","UnauthorizedException","AuthNPaasModule","forRoot","options","module","global","controllers","providers","provide","AUTHNPAAS_MODULE_OPTIONS","useValue","Reflector","AuthNPaasGuard","APP_GUARD","useClass","exports","import_common","IS_PUBLIC_KEY","Public","SetMetadata","import_common","NeedLogin","loginPath","SetMetadata","NEED_LOGIN_KEY"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/authnpaas.module.ts","../src/const.ts","../src/guards/authnpaas.guard.ts","../src/services/authnpaas.service.ts","../src/controllers/authnpaas.controller.ts","../src/decorators/public.decorator.ts","../src/decorators/need-login.decorator.ts"],"sourcesContent":["/**\n * @lark-apaas/nestjs-authnpaas\n *\n * 基于 CASL 的 NestJS 权限管理模块\n * 提供角色、权限点位、环境等多维度的鉴权能力\n */\n\n// 主模块\nexport { AuthNPaasModule } from './authnpaas.module';\n\n// 服务\nexport * from './services';\n\n// 控制器\nexport * from './controllers';\n\n// 装饰器\nexport * from './decorators';\n\n// 守卫\nexport * from './guards';\n\n// 类型定义\nexport * from './types';\n\n// 常量\nexport * from './const';\n","import { DynamicModule, Module } from '@nestjs/common';\nimport { APP_GUARD, Reflector } from '@nestjs/core';\nimport { AuthNPaasModuleOptions } from './types';\nimport { AUTHNPAAS_MODULE_OPTIONS } from './const';\nimport { AuthNPaasGuard } from './guards/authnpaas.guard';\nimport { AuthNPaasService } from './services/authnpaas.service';\nimport { AuthNPaasController } from './controllers/authnpaas.controller';\n\n@Module({})\nexport class AuthNPaasModule {\n static forRoot(options?: AuthNPaasModuleOptions): DynamicModule {\n return {\n module: AuthNPaasModule,\n global: true,\n controllers: [AuthNPaasController],\n providers: [\n // 配置提供者\n {\n provide: AUTHNPAAS_MODULE_OPTIONS,\n useValue: {\n ...(options || {}),\n },\n },\n // 核心服务\n Reflector,\n // 服务提供者\n AuthNPaasGuard,\n AuthNPaasService,\n // 守卫提供者\n {\n provide: APP_GUARD,\n useClass: AuthNPaasGuard,\n },\n ],\n exports: [AuthNPaasService],\n };\n }\n}\n","/**\n * 常量\n */\n\n/** AuthNPaas 模块选项 Token */\nexport const AUTHNPAAS_MODULE_OPTIONS = Symbol('AUTHNPAAS_MODULE_OPTIONS');\n\n/**\n * 元数据键\n */\n\n/** 需要登录元数据键 */\nexport const NEED_LOGIN_KEY = 'authnpaas:needLogin';\n","import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';\nimport { Response } from 'express';\nimport { Reflector } from '@nestjs/core';\nimport { NEED_LOGIN_KEY } from '../const';\n\n/**\n * AuthNPaas 守卫\n * 负责协调所有鉴权检查,具体检查逻辑委托给 PermissionService\n */\n@Injectable()\nexport class AuthNPaasGuard implements CanActivate {\n constructor(private reflector: Reflector) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const http = context.switchToHttp();\n const request = http.getRequest();\n const response = http.getResponse<Response>();\n\n const { userId, loginUrl } = request.userContext || {};\n\n // 读取 NeedLogin 元数据并标记到请求对象,供异常过滤器使用\n const needLoginMeta = this.reflector.getAllAndOverride<{\n loginPath?: string;\n }>(NEED_LOGIN_KEY, [context.getHandler(), context.getClass()]);\n\n // NeedLogin 且无 userId -> 在守卫内透出跳转 url\n if (needLoginMeta && !userId && loginUrl) {\n response.setHeader('x-login-url', loginUrl);\n throw new UnauthorizedException('未登录');\n }\n\n return true;\n }\n}\n","import { Injectable, Inject, Logger } from '@nestjs/common';\nimport {\n PLATFORM_HTTP_CLIENT,\n OBSERVABLE_SERVICE,\n type PlatformHttpClient,\n type ObservableService,\n RequestContextService,\n createTimer,\n} from '@lark-apaas/nestjs-common';\n\nconst SDK_MODULE = 'authn';\n\n/**\n * 妙搭用户ID → 飞书用户ID 的转换类型\n */\nconst CONVERT_TYPE_FORCE_TO_FEISHU = 30;\n\n/**\n * ID 转换结果项\n */\nexport interface UserIDMappingItem {\n sourceUserID: string;\n targetUserID: string;\n}\n\n/**\n * 批量转换响应\n */\ninterface BatchConvertResponse {\n data?: {\n items?: UserIDMappingItem[];\n };\n status_code?: string;\n status_message?: string;\n error_msg?: string;\n}\n\n@Injectable()\nexport class AuthNPaasService {\n private readonly logger = new Logger(AuthNPaasService.name);\n\n constructor(\n @Inject(PLATFORM_HTTP_CLIENT) private readonly httpClient: PlatformHttpClient,\n @Inject(OBSERVABLE_SERVICE) private readonly obs: ObservableService,\n private readonly requestContext: RequestContextService,\n ) {}\n\n /**\n * 获取当前登录用户的飞书 user_id\n *\n * 从请求上下文获取当前妙搭 userId,调用转换接口获取对应的飞书 user_id\n *\n * @returns 飞书 user_id,如果当前用户未登录或转换失败返回 null\n */\n async getCurrentUserLarkUserId(): Promise<string | null> {\n const userId = this.requestContext.get('userId');\n if (!userId) {\n this.logger.warn('getCurrentUserLarkUserId: no userId in request context');\n return null;\n }\n\n const items = await this.batchConvertUserIds('getCurrentUserLarkUserId', [userId]);\n if (!items || items.length === 0) {\n return null;\n }\n\n return items[0].targetUserID || null;\n }\n\n /**\n * 批量将妙搭 userId 转换为飞书 user_id\n *\n * @param userIds - 妙搭用户 ID 列表,最多 100 个\n * @returns 飞书 user_id 数组,顺序与输入对应,转换失败的项为 null\n */\n async getBatchLarkUserIds(userIds: string[]): Promise<(string | null)[]> {\n if (!userIds || userIds.length === 0) {\n return [];\n }\n\n if (userIds.length > 100) {\n throw new Error('userIds length must not exceed 100');\n }\n\n const items = await this.batchConvertUserIds('getBatchLarkUserIds', userIds);\n const mapping = new Map(items.map(item => [item.sourceUserID, item.targetUserID]));\n return userIds.map(id => mapping.get(id) ?? null);\n }\n\n /**\n * 调用批量转换接口(带可观测性)\n */\n private async batchConvertUserIds(method: string, userIds: string[]): Promise<UserIDMappingItem[]> {\n const appId = this.requestContext.get('appId');\n if (!appId) {\n this.logger.warn(`${method}: no appId in request context`);\n return [];\n }\n\n const url = `/v1/app/${appId}/account/user/convert`;\n const body = {\n convertType: CONVERT_TYPE_FORCE_TO_FEISHU,\n userIDList: userIds,\n };\n\n const spanName = `${SDK_MODULE}.${method}`;\n const spanAttrs: Record<string, unknown> = {\n module: SDK_MODULE,\n method,\n source_type: 'platform',\n paas_attributes_module: SDK_MODULE,\n http_method: 'POST',\n path: url,\n };\n const logAttrs: Record<string, unknown> = {\n source_type: 'platform',\n paas_attributes_module: SDK_MODULE,\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return this.obs.trace(spanName, async (span: any) => {\n span.setAttributes(spanAttrs);\n const elapsed = createTimer();\n\n try {\n this.logger.log(`[batchConvertUserIds] request: ${url} ${JSON.stringify(body)}`);\n const response = await this.httpClient.post(url, body);\n const logId = response.headers?.get?.('x-tt-logid') ?? '';\n const raw = await response.text();\n const durationMs = elapsed();\n\n this.logger.log(`[batchConvertUserIds] response: status=${response.status} ok=${response.ok} logId=${logId} raw=${raw}`);\n\n if (!response.ok) {\n span.setAttributes({ duration_ms: durationMs, success: false, error: `HTTP ${response.status}`, 'x-tt-logid': logId });\n this.logger.warn(JSON.stringify({\n method, path: url, duration_ms: durationMs, success: false,\n error: `HTTP ${response.status} ${response.statusText}`,\n 'x-tt-logid': logId, params: { convertType: CONVERT_TYPE_FORCE_TO_FEISHU, count: userIds.length },\n }), logAttrs);\n return [];\n }\n\n const result: BatchConvertResponse = raw ? JSON.parse(raw) : {};\n\n if (String(result.status_code) !== '0' && result.status_code !== undefined) {\n const errMsg = `[${result.status_code}] ${result.status_message || result.error_msg}`;\n span.setAttributes({ duration_ms: durationMs, success: false, error: errMsg, 'x-tt-logid': logId });\n this.logger.error(JSON.stringify({\n method, path: url, duration_ms: durationMs, success: false,\n error: errMsg, 'x-tt-logid': logId,\n params: { convertType: CONVERT_TYPE_FORCE_TO_FEISHU, count: userIds.length },\n }), logAttrs);\n return [];\n }\n\n const items = result.data?.items ?? [];\n\n span.setAttributes({ duration_ms: durationMs, success: true, 'x-tt-logid': logId, result_count: items.length });\n this.logger.log(JSON.stringify({\n method, path: url, duration_ms: durationMs, success: true,\n 'x-tt-logid': logId,\n params: { convertType: CONVERT_TYPE_FORCE_TO_FEISHU, count: userIds.length },\n result_count: items.length,\n response: raw.length > 1024 ? raw.slice(0, 1024) + '...' : raw,\n }), logAttrs);\n\n return items;\n } catch (error: any) {\n const durationMs = elapsed();\n const errMsg = error instanceof Error ? error.message : String(error);\n\n const logId = error?.headers?.get?.('x-tt-logid') ?? error?.response?.headers?.['x-tt-logid'] ?? error?.logId ?? '';\n this.logger.error(`[batchConvertUserIds] CATCH: ${errMsg} logId=${logId}`);\n\n span.setAttributes({ duration_ms: durationMs, success: false, error: errMsg });\n this.logger.warn(JSON.stringify({\n method, path: url, duration_ms: durationMs, success: false,\n error: errMsg,\n params: { convertType: CONVERT_TYPE_FORCE_TO_FEISHU, count: userIds.length },\n }), logAttrs);\n return [];\n }\n });\n }\n}\n","import { Controller, Get } from '@nestjs/common';\nimport { ApiExcludeController } from '@nestjs/swagger';\nimport { AuthNPaasService } from '../services/authnpaas.service';\n\n@ApiExcludeController()\n@Controller('api/authnpaas')\nexport class AuthNPaasController {\n constructor(private readonly authnService: AuthNPaasService) {}\n\n /**\n * 获取当前登录用户的飞书 user_id\n *\n * GET /api/authnpaas/lark-user-id\n */\n @Get('lark-user-id')\n async getCurrentUserLarkUserId() {\n const larkUserId = await this.authnService.getCurrentUserLarkUserId();\n return { lark_user_id: larkUserId };\n }\n}\n","import { SetMetadata } from '@nestjs/common';\n\n/**\n * Public 装饰器的元数据键\n */\nexport const IS_PUBLIC_KEY = 'isPublic';\n\n/**\n * 标记接口为公开接口,跳过 AuthNPaasGuard 的鉴权检查\n * \n * @example\n * ```typescript\n * @Controller('mock-api/users')\n * @Public() // 控制器级别\n * export class MockPermissionController {\n * @Get(':userId/permissions')\n * getUserPermissions() {}\n * }\n * \n * // 或者在方法级别\n * @Controller('api')\n * export class ApiController {\n * @Get('public-info')\n * @Public() // 方法级别\n * getPublicInfo() {}\n * }\n * ```\n */\nexport const Public = () => SetMetadata(IS_PUBLIC_KEY, true);\n\n","import { SetMetadata } from '@nestjs/common';\nimport { NEED_LOGIN_KEY } from '../const';\n\n/**\n * NeedLogin 装饰器\n * 标记接口需要登录。如果鉴权失败(如 401/403),异常过滤器会将请求重定向到登录页。\n * 可选地传入登录页路径,默认 '/login'。\n */\nexport const NeedLogin = (loginPath?: string): MethodDecorator & ClassDecorator => {\n return SetMetadata(NEED_LOGIN_KEY, { loginPath });\n};\n\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;ACAA,IAAAA,iBAAsC;AACtC,IAAAC,eAAqC;;;ACI9B,IAAMC,2BAA2BC,uBAAO,0BAAA;AAOxC,IAAMC,iBAAiB;;;ACZ9B,oBAAiF;AAEjF,kBAA0B;;;;;;;;;;;;AAQnB,IAAMC,iBAAN,MAAMA;SAAAA;;;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9D,WAAO;MACLC,QAAQH;MACRI,QAAQ;MACRC,aAAa;QAACC;;MACdC,WAAW;;QAET;UACEC,SAASC;UACTC,UAAU;YACR,GAAIR,WAAW,CAAC;UAClB;QACF;;QAEAS;;QAEAC;QACAC;;QAEA;UACEL,SAASM;UACTC,UAAUH;QACZ;;MAEFI,SAAS;QAACH;;IACZ;EACF;AACF;;;;;;AKrCA,IAAAI,iBAA4B;AAKrB,IAAMC,gBAAgB;AAuBtB,IAAMC,SAAS,iCAAMC,4BAAYF,eAAe,IAAA,GAAjC;;;AC5BtB,IAAAG,iBAA4B;AAQrB,IAAMC,YAAY,wBAACC,cAAAA;AACxB,aAAOC,4BAAYC,gBAAgB;IAAEF;EAAU,CAAA;AACjD,GAFyB;","names":["import_common","import_core","AUTHNPAAS_MODULE_OPTIONS","Symbol","NEED_LOGIN_KEY","AuthNPaasGuard","reflector","canActivate","context","http","switchToHttp","request","getRequest","response","getResponse","userId","loginUrl","userContext","needLoginMeta","getAllAndOverride","NEED_LOGIN_KEY","getHandler","getClass","setHeader","UnauthorizedException","import_common","SDK_MODULE","CONVERT_TYPE_FORCE_TO_FEISHU","AuthNPaasService","logger","Logger","name","httpClient","obs","requestContext","getCurrentUserLarkUserId","userId","get","warn","items","batchConvertUserIds","length","targetUserID","getBatchLarkUserIds","userIds","Error","mapping","Map","map","item","sourceUserID","id","method","appId","url","body","convertType","userIDList","spanName","spanAttrs","module","source_type","paas_attributes_module","http_method","path","logAttrs","trace","span","setAttributes","elapsed","createTimer","log","JSON","stringify","response","post","logId","headers","raw","text","durationMs","status","ok","duration_ms","success","error","statusText","params","count","result","parse","String","status_code","undefined","errMsg","status_message","error_msg","data","result_count","slice","message","import_common","AuthNPaasController","authnService","getCurrentUserLarkUserId","larkUserId","lark_user_id","AuthNPaasModule","forRoot","options","module","global","controllers","AuthNPaasController","providers","provide","AUTHNPAAS_MODULE_OPTIONS","useValue","Reflector","AuthNPaasGuard","AuthNPaasService","APP_GUARD","useClass","exports","import_common","IS_PUBLIC_KEY","Public","SetMetadata","import_common","NeedLogin","loginPath","SetMetadata","NEED_LOGIN_KEY"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import * as _nestjs_common from '@nestjs/common';
|
|
2
2
|
import { DynamicModule, CanActivate, ExecutionContext } from '@nestjs/common';
|
|
3
|
+
import { PlatformHttpClient, ObservableService, RequestContextService } from '@lark-apaas/nestjs-common';
|
|
3
4
|
import { Reflector } from '@nestjs/core';
|
|
4
5
|
|
|
5
6
|
/**
|
|
@@ -14,6 +15,53 @@ declare class AuthNPaasModule {
|
|
|
14
15
|
static forRoot(options?: AuthNPaasModuleOptions): DynamicModule;
|
|
15
16
|
}
|
|
16
17
|
|
|
18
|
+
/**
|
|
19
|
+
* ID 转换结果项
|
|
20
|
+
*/
|
|
21
|
+
interface UserIDMappingItem {
|
|
22
|
+
sourceUserID: string;
|
|
23
|
+
targetUserID: string;
|
|
24
|
+
}
|
|
25
|
+
declare class AuthNPaasService {
|
|
26
|
+
private readonly httpClient;
|
|
27
|
+
private readonly obs;
|
|
28
|
+
private readonly requestContext;
|
|
29
|
+
private readonly logger;
|
|
30
|
+
constructor(httpClient: PlatformHttpClient, obs: ObservableService, requestContext: RequestContextService);
|
|
31
|
+
/**
|
|
32
|
+
* 获取当前登录用户的飞书 user_id
|
|
33
|
+
*
|
|
34
|
+
* 从请求上下文获取当前妙搭 userId,调用转换接口获取对应的飞书 user_id
|
|
35
|
+
*
|
|
36
|
+
* @returns 飞书 user_id,如果当前用户未登录或转换失败返回 null
|
|
37
|
+
*/
|
|
38
|
+
getCurrentUserLarkUserId(): Promise<string | null>;
|
|
39
|
+
/**
|
|
40
|
+
* 批量将妙搭 userId 转换为飞书 user_id
|
|
41
|
+
*
|
|
42
|
+
* @param userIds - 妙搭用户 ID 列表,最多 100 个
|
|
43
|
+
* @returns 飞书 user_id 数组,顺序与输入对应,转换失败的项为 null
|
|
44
|
+
*/
|
|
45
|
+
getBatchLarkUserIds(userIds: string[]): Promise<(string | null)[]>;
|
|
46
|
+
/**
|
|
47
|
+
* 调用批量转换接口(带可观测性)
|
|
48
|
+
*/
|
|
49
|
+
private batchConvertUserIds;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
declare class AuthNPaasController {
|
|
53
|
+
private readonly authnService;
|
|
54
|
+
constructor(authnService: AuthNPaasService);
|
|
55
|
+
/**
|
|
56
|
+
* 获取当前登录用户的飞书 user_id
|
|
57
|
+
*
|
|
58
|
+
* GET /api/authnpaas/lark-user-id
|
|
59
|
+
*/
|
|
60
|
+
getCurrentUserLarkUserId(): Promise<{
|
|
61
|
+
lark_user_id: string | null;
|
|
62
|
+
}>;
|
|
63
|
+
}
|
|
64
|
+
|
|
17
65
|
/**
|
|
18
66
|
* Public 装饰器的元数据键
|
|
19
67
|
*/
|
|
@@ -69,4 +117,4 @@ declare const AUTHNPAAS_MODULE_OPTIONS: unique symbol;
|
|
|
69
117
|
/** 需要登录元数据键 */
|
|
70
118
|
declare const NEED_LOGIN_KEY = "authnpaas:needLogin";
|
|
71
119
|
|
|
72
|
-
export { AUTHNPAAS_MODULE_OPTIONS, AuthNPaasGuard, AuthNPaasModule, type AuthNPaasModuleOptions, IS_PUBLIC_KEY, NEED_LOGIN_KEY, NeedLogin, Public };
|
|
120
|
+
export { AUTHNPAAS_MODULE_OPTIONS, AuthNPaasController, AuthNPaasGuard, AuthNPaasModule, type AuthNPaasModuleOptions, AuthNPaasService, IS_PUBLIC_KEY, NEED_LOGIN_KEY, NeedLogin, Public, type UserIDMappingItem };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import * as _nestjs_common from '@nestjs/common';
|
|
2
2
|
import { DynamicModule, CanActivate, ExecutionContext } from '@nestjs/common';
|
|
3
|
+
import { PlatformHttpClient, ObservableService, RequestContextService } from '@lark-apaas/nestjs-common';
|
|
3
4
|
import { Reflector } from '@nestjs/core';
|
|
4
5
|
|
|
5
6
|
/**
|
|
@@ -14,6 +15,53 @@ declare class AuthNPaasModule {
|
|
|
14
15
|
static forRoot(options?: AuthNPaasModuleOptions): DynamicModule;
|
|
15
16
|
}
|
|
16
17
|
|
|
18
|
+
/**
|
|
19
|
+
* ID 转换结果项
|
|
20
|
+
*/
|
|
21
|
+
interface UserIDMappingItem {
|
|
22
|
+
sourceUserID: string;
|
|
23
|
+
targetUserID: string;
|
|
24
|
+
}
|
|
25
|
+
declare class AuthNPaasService {
|
|
26
|
+
private readonly httpClient;
|
|
27
|
+
private readonly obs;
|
|
28
|
+
private readonly requestContext;
|
|
29
|
+
private readonly logger;
|
|
30
|
+
constructor(httpClient: PlatformHttpClient, obs: ObservableService, requestContext: RequestContextService);
|
|
31
|
+
/**
|
|
32
|
+
* 获取当前登录用户的飞书 user_id
|
|
33
|
+
*
|
|
34
|
+
* 从请求上下文获取当前妙搭 userId,调用转换接口获取对应的飞书 user_id
|
|
35
|
+
*
|
|
36
|
+
* @returns 飞书 user_id,如果当前用户未登录或转换失败返回 null
|
|
37
|
+
*/
|
|
38
|
+
getCurrentUserLarkUserId(): Promise<string | null>;
|
|
39
|
+
/**
|
|
40
|
+
* 批量将妙搭 userId 转换为飞书 user_id
|
|
41
|
+
*
|
|
42
|
+
* @param userIds - 妙搭用户 ID 列表,最多 100 个
|
|
43
|
+
* @returns 飞书 user_id 数组,顺序与输入对应,转换失败的项为 null
|
|
44
|
+
*/
|
|
45
|
+
getBatchLarkUserIds(userIds: string[]): Promise<(string | null)[]>;
|
|
46
|
+
/**
|
|
47
|
+
* 调用批量转换接口(带可观测性)
|
|
48
|
+
*/
|
|
49
|
+
private batchConvertUserIds;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
declare class AuthNPaasController {
|
|
53
|
+
private readonly authnService;
|
|
54
|
+
constructor(authnService: AuthNPaasService);
|
|
55
|
+
/**
|
|
56
|
+
* 获取当前登录用户的飞书 user_id
|
|
57
|
+
*
|
|
58
|
+
* GET /api/authnpaas/lark-user-id
|
|
59
|
+
*/
|
|
60
|
+
getCurrentUserLarkUserId(): Promise<{
|
|
61
|
+
lark_user_id: string | null;
|
|
62
|
+
}>;
|
|
63
|
+
}
|
|
64
|
+
|
|
17
65
|
/**
|
|
18
66
|
* Public 装饰器的元数据键
|
|
19
67
|
*/
|
|
@@ -69,4 +117,4 @@ declare const AUTHNPAAS_MODULE_OPTIONS: unique symbol;
|
|
|
69
117
|
/** 需要登录元数据键 */
|
|
70
118
|
declare const NEED_LOGIN_KEY = "authnpaas:needLogin";
|
|
71
119
|
|
|
72
|
-
export { AUTHNPAAS_MODULE_OPTIONS, AuthNPaasGuard, AuthNPaasModule, type AuthNPaasModuleOptions, IS_PUBLIC_KEY, NEED_LOGIN_KEY, NeedLogin, Public };
|
|
120
|
+
export { AUTHNPAAS_MODULE_OPTIONS, AuthNPaasController, AuthNPaasGuard, AuthNPaasModule, type AuthNPaasModuleOptions, AuthNPaasService, IS_PUBLIC_KEY, NEED_LOGIN_KEY, NeedLogin, Public, type UserIDMappingItem };
|
package/dist/index.js
CHANGED
|
@@ -6,7 +6,7 @@ import { Module } from "@nestjs/common";
|
|
|
6
6
|
import { APP_GUARD, Reflector as Reflector2 } from "@nestjs/core";
|
|
7
7
|
|
|
8
8
|
// src/const.ts
|
|
9
|
-
var AUTHNPAAS_MODULE_OPTIONS = Symbol("AUTHNPAAS_MODULE_OPTIONS");
|
|
9
|
+
var AUTHNPAAS_MODULE_OPTIONS = /* @__PURE__ */ Symbol("AUTHNPAAS_MODULE_OPTIONS");
|
|
10
10
|
var NEED_LOGIN_KEY = "authnpaas:needLogin";
|
|
11
11
|
|
|
12
12
|
// src/guards/authnpaas.guard.ts
|
|
@@ -55,7 +55,9 @@ AuthNPaasGuard = _ts_decorate([
|
|
|
55
55
|
])
|
|
56
56
|
], AuthNPaasGuard);
|
|
57
57
|
|
|
58
|
-
// src/authnpaas.
|
|
58
|
+
// src/services/authnpaas.service.ts
|
|
59
|
+
import { Injectable as Injectable2, Inject, Logger } from "@nestjs/common";
|
|
60
|
+
import { PLATFORM_HTTP_CLIENT, OBSERVABLE_SERVICE, RequestContextService, createTimer } from "@lark-apaas/nestjs-common";
|
|
59
61
|
function _ts_decorate2(decorators, target, key, desc) {
|
|
60
62
|
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
61
63
|
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
@@ -63,6 +65,269 @@ function _ts_decorate2(decorators, target, key, desc) {
|
|
|
63
65
|
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
64
66
|
}
|
|
65
67
|
__name(_ts_decorate2, "_ts_decorate");
|
|
68
|
+
function _ts_metadata2(k, v) {
|
|
69
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
70
|
+
}
|
|
71
|
+
__name(_ts_metadata2, "_ts_metadata");
|
|
72
|
+
function _ts_param(paramIndex, decorator) {
|
|
73
|
+
return function(target, key) {
|
|
74
|
+
decorator(target, key, paramIndex);
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
__name(_ts_param, "_ts_param");
|
|
78
|
+
var SDK_MODULE = "authn";
|
|
79
|
+
var CONVERT_TYPE_FORCE_TO_FEISHU = 30;
|
|
80
|
+
var AuthNPaasService = class _AuthNPaasService {
|
|
81
|
+
static {
|
|
82
|
+
__name(this, "AuthNPaasService");
|
|
83
|
+
}
|
|
84
|
+
httpClient;
|
|
85
|
+
obs;
|
|
86
|
+
requestContext;
|
|
87
|
+
logger = new Logger(_AuthNPaasService.name);
|
|
88
|
+
constructor(httpClient, obs, requestContext) {
|
|
89
|
+
this.httpClient = httpClient;
|
|
90
|
+
this.obs = obs;
|
|
91
|
+
this.requestContext = requestContext;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* 获取当前登录用户的飞书 user_id
|
|
95
|
+
*
|
|
96
|
+
* 从请求上下文获取当前妙搭 userId,调用转换接口获取对应的飞书 user_id
|
|
97
|
+
*
|
|
98
|
+
* @returns 飞书 user_id,如果当前用户未登录或转换失败返回 null
|
|
99
|
+
*/
|
|
100
|
+
async getCurrentUserLarkUserId() {
|
|
101
|
+
const userId = this.requestContext.get("userId");
|
|
102
|
+
if (!userId) {
|
|
103
|
+
this.logger.warn("getCurrentUserLarkUserId: no userId in request context");
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
const items = await this.batchConvertUserIds("getCurrentUserLarkUserId", [
|
|
107
|
+
userId
|
|
108
|
+
]);
|
|
109
|
+
if (!items || items.length === 0) {
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
return items[0].targetUserID || null;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* 批量将妙搭 userId 转换为飞书 user_id
|
|
116
|
+
*
|
|
117
|
+
* @param userIds - 妙搭用户 ID 列表,最多 100 个
|
|
118
|
+
* @returns 飞书 user_id 数组,顺序与输入对应,转换失败的项为 null
|
|
119
|
+
*/
|
|
120
|
+
async getBatchLarkUserIds(userIds) {
|
|
121
|
+
if (!userIds || userIds.length === 0) {
|
|
122
|
+
return [];
|
|
123
|
+
}
|
|
124
|
+
if (userIds.length > 100) {
|
|
125
|
+
throw new Error("userIds length must not exceed 100");
|
|
126
|
+
}
|
|
127
|
+
const items = await this.batchConvertUserIds("getBatchLarkUserIds", userIds);
|
|
128
|
+
const mapping = new Map(items.map((item) => [
|
|
129
|
+
item.sourceUserID,
|
|
130
|
+
item.targetUserID
|
|
131
|
+
]));
|
|
132
|
+
return userIds.map((id) => mapping.get(id) ?? null);
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* 调用批量转换接口(带可观测性)
|
|
136
|
+
*/
|
|
137
|
+
async batchConvertUserIds(method, userIds) {
|
|
138
|
+
const appId = this.requestContext.get("appId");
|
|
139
|
+
if (!appId) {
|
|
140
|
+
this.logger.warn(`${method}: no appId in request context`);
|
|
141
|
+
return [];
|
|
142
|
+
}
|
|
143
|
+
const url = `/v1/app/${appId}/account/user/convert`;
|
|
144
|
+
const body = {
|
|
145
|
+
convertType: CONVERT_TYPE_FORCE_TO_FEISHU,
|
|
146
|
+
userIDList: userIds
|
|
147
|
+
};
|
|
148
|
+
const spanName = `${SDK_MODULE}.${method}`;
|
|
149
|
+
const spanAttrs = {
|
|
150
|
+
module: SDK_MODULE,
|
|
151
|
+
method,
|
|
152
|
+
source_type: "platform",
|
|
153
|
+
paas_attributes_module: SDK_MODULE,
|
|
154
|
+
http_method: "POST",
|
|
155
|
+
path: url
|
|
156
|
+
};
|
|
157
|
+
const logAttrs = {
|
|
158
|
+
source_type: "platform",
|
|
159
|
+
paas_attributes_module: SDK_MODULE
|
|
160
|
+
};
|
|
161
|
+
return this.obs.trace(spanName, async (span) => {
|
|
162
|
+
span.setAttributes(spanAttrs);
|
|
163
|
+
const elapsed = createTimer();
|
|
164
|
+
try {
|
|
165
|
+
this.logger.log(`[batchConvertUserIds] request: ${url} ${JSON.stringify(body)}`);
|
|
166
|
+
const response = await this.httpClient.post(url, body);
|
|
167
|
+
const logId = response.headers?.get?.("x-tt-logid") ?? "";
|
|
168
|
+
const raw = await response.text();
|
|
169
|
+
const durationMs = elapsed();
|
|
170
|
+
this.logger.log(`[batchConvertUserIds] response: status=${response.status} ok=${response.ok} logId=${logId} raw=${raw}`);
|
|
171
|
+
if (!response.ok) {
|
|
172
|
+
span.setAttributes({
|
|
173
|
+
duration_ms: durationMs,
|
|
174
|
+
success: false,
|
|
175
|
+
error: `HTTP ${response.status}`,
|
|
176
|
+
"x-tt-logid": logId
|
|
177
|
+
});
|
|
178
|
+
this.logger.warn(JSON.stringify({
|
|
179
|
+
method,
|
|
180
|
+
path: url,
|
|
181
|
+
duration_ms: durationMs,
|
|
182
|
+
success: false,
|
|
183
|
+
error: `HTTP ${response.status} ${response.statusText}`,
|
|
184
|
+
"x-tt-logid": logId,
|
|
185
|
+
params: {
|
|
186
|
+
convertType: CONVERT_TYPE_FORCE_TO_FEISHU,
|
|
187
|
+
count: userIds.length
|
|
188
|
+
}
|
|
189
|
+
}), logAttrs);
|
|
190
|
+
return [];
|
|
191
|
+
}
|
|
192
|
+
const result = raw ? JSON.parse(raw) : {};
|
|
193
|
+
if (String(result.status_code) !== "0" && result.status_code !== void 0) {
|
|
194
|
+
const errMsg = `[${result.status_code}] ${result.status_message || result.error_msg}`;
|
|
195
|
+
span.setAttributes({
|
|
196
|
+
duration_ms: durationMs,
|
|
197
|
+
success: false,
|
|
198
|
+
error: errMsg,
|
|
199
|
+
"x-tt-logid": logId
|
|
200
|
+
});
|
|
201
|
+
this.logger.error(JSON.stringify({
|
|
202
|
+
method,
|
|
203
|
+
path: url,
|
|
204
|
+
duration_ms: durationMs,
|
|
205
|
+
success: false,
|
|
206
|
+
error: errMsg,
|
|
207
|
+
"x-tt-logid": logId,
|
|
208
|
+
params: {
|
|
209
|
+
convertType: CONVERT_TYPE_FORCE_TO_FEISHU,
|
|
210
|
+
count: userIds.length
|
|
211
|
+
}
|
|
212
|
+
}), logAttrs);
|
|
213
|
+
return [];
|
|
214
|
+
}
|
|
215
|
+
const items = result.data?.items ?? [];
|
|
216
|
+
span.setAttributes({
|
|
217
|
+
duration_ms: durationMs,
|
|
218
|
+
success: true,
|
|
219
|
+
"x-tt-logid": logId,
|
|
220
|
+
result_count: items.length
|
|
221
|
+
});
|
|
222
|
+
this.logger.log(JSON.stringify({
|
|
223
|
+
method,
|
|
224
|
+
path: url,
|
|
225
|
+
duration_ms: durationMs,
|
|
226
|
+
success: true,
|
|
227
|
+
"x-tt-logid": logId,
|
|
228
|
+
params: {
|
|
229
|
+
convertType: CONVERT_TYPE_FORCE_TO_FEISHU,
|
|
230
|
+
count: userIds.length
|
|
231
|
+
},
|
|
232
|
+
result_count: items.length,
|
|
233
|
+
response: raw.length > 1024 ? raw.slice(0, 1024) + "..." : raw
|
|
234
|
+
}), logAttrs);
|
|
235
|
+
return items;
|
|
236
|
+
} catch (error) {
|
|
237
|
+
const durationMs = elapsed();
|
|
238
|
+
const errMsg = error instanceof Error ? error.message : String(error);
|
|
239
|
+
const logId = error?.headers?.get?.("x-tt-logid") ?? error?.response?.headers?.["x-tt-logid"] ?? error?.logId ?? "";
|
|
240
|
+
this.logger.error(`[batchConvertUserIds] CATCH: ${errMsg} logId=${logId}`);
|
|
241
|
+
span.setAttributes({
|
|
242
|
+
duration_ms: durationMs,
|
|
243
|
+
success: false,
|
|
244
|
+
error: errMsg
|
|
245
|
+
});
|
|
246
|
+
this.logger.warn(JSON.stringify({
|
|
247
|
+
method,
|
|
248
|
+
path: url,
|
|
249
|
+
duration_ms: durationMs,
|
|
250
|
+
success: false,
|
|
251
|
+
error: errMsg,
|
|
252
|
+
params: {
|
|
253
|
+
convertType: CONVERT_TYPE_FORCE_TO_FEISHU,
|
|
254
|
+
count: userIds.length
|
|
255
|
+
}
|
|
256
|
+
}), logAttrs);
|
|
257
|
+
return [];
|
|
258
|
+
}
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
};
|
|
262
|
+
AuthNPaasService = _ts_decorate2([
|
|
263
|
+
Injectable2(),
|
|
264
|
+
_ts_param(0, Inject(PLATFORM_HTTP_CLIENT)),
|
|
265
|
+
_ts_param(1, Inject(OBSERVABLE_SERVICE)),
|
|
266
|
+
_ts_metadata2("design:type", Function),
|
|
267
|
+
_ts_metadata2("design:paramtypes", [
|
|
268
|
+
typeof PlatformHttpClient === "undefined" ? Object : PlatformHttpClient,
|
|
269
|
+
typeof ObservableService === "undefined" ? Object : ObservableService,
|
|
270
|
+
typeof RequestContextService === "undefined" ? Object : RequestContextService
|
|
271
|
+
])
|
|
272
|
+
], AuthNPaasService);
|
|
273
|
+
|
|
274
|
+
// src/controllers/authnpaas.controller.ts
|
|
275
|
+
import { Controller, Get } from "@nestjs/common";
|
|
276
|
+
import { ApiExcludeController } from "@nestjs/swagger";
|
|
277
|
+
function _ts_decorate3(decorators, target, key, desc) {
|
|
278
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
279
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
280
|
+
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;
|
|
281
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
282
|
+
}
|
|
283
|
+
__name(_ts_decorate3, "_ts_decorate");
|
|
284
|
+
function _ts_metadata3(k, v) {
|
|
285
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
286
|
+
}
|
|
287
|
+
__name(_ts_metadata3, "_ts_metadata");
|
|
288
|
+
var AuthNPaasController = class {
|
|
289
|
+
static {
|
|
290
|
+
__name(this, "AuthNPaasController");
|
|
291
|
+
}
|
|
292
|
+
authnService;
|
|
293
|
+
constructor(authnService) {
|
|
294
|
+
this.authnService = authnService;
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* 获取当前登录用户的飞书 user_id
|
|
298
|
+
*
|
|
299
|
+
* GET /api/authnpaas/lark-user-id
|
|
300
|
+
*/
|
|
301
|
+
async getCurrentUserLarkUserId() {
|
|
302
|
+
const larkUserId = await this.authnService.getCurrentUserLarkUserId();
|
|
303
|
+
return {
|
|
304
|
+
lark_user_id: larkUserId
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
};
|
|
308
|
+
_ts_decorate3([
|
|
309
|
+
Get("lark-user-id"),
|
|
310
|
+
_ts_metadata3("design:type", Function),
|
|
311
|
+
_ts_metadata3("design:paramtypes", []),
|
|
312
|
+
_ts_metadata3("design:returntype", Promise)
|
|
313
|
+
], AuthNPaasController.prototype, "getCurrentUserLarkUserId", null);
|
|
314
|
+
AuthNPaasController = _ts_decorate3([
|
|
315
|
+
ApiExcludeController(),
|
|
316
|
+
Controller("api/authnpaas"),
|
|
317
|
+
_ts_metadata3("design:type", Function),
|
|
318
|
+
_ts_metadata3("design:paramtypes", [
|
|
319
|
+
typeof AuthNPaasService === "undefined" ? Object : AuthNPaasService
|
|
320
|
+
])
|
|
321
|
+
], AuthNPaasController);
|
|
322
|
+
|
|
323
|
+
// src/authnpaas.module.ts
|
|
324
|
+
function _ts_decorate4(decorators, target, key, desc) {
|
|
325
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
326
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
327
|
+
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;
|
|
328
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
329
|
+
}
|
|
330
|
+
__name(_ts_decorate4, "_ts_decorate");
|
|
66
331
|
var AuthNPaasModule = class _AuthNPaasModule {
|
|
67
332
|
static {
|
|
68
333
|
__name(this, "AuthNPaasModule");
|
|
@@ -71,7 +336,9 @@ var AuthNPaasModule = class _AuthNPaasModule {
|
|
|
71
336
|
return {
|
|
72
337
|
module: _AuthNPaasModule,
|
|
73
338
|
global: true,
|
|
74
|
-
controllers: [
|
|
339
|
+
controllers: [
|
|
340
|
+
AuthNPaasController
|
|
341
|
+
],
|
|
75
342
|
providers: [
|
|
76
343
|
// 配置提供者
|
|
77
344
|
{
|
|
@@ -84,17 +351,20 @@ var AuthNPaasModule = class _AuthNPaasModule {
|
|
|
84
351
|
Reflector2,
|
|
85
352
|
// 服务提供者
|
|
86
353
|
AuthNPaasGuard,
|
|
354
|
+
AuthNPaasService,
|
|
87
355
|
// 守卫提供者
|
|
88
356
|
{
|
|
89
357
|
provide: APP_GUARD,
|
|
90
358
|
useClass: AuthNPaasGuard
|
|
91
359
|
}
|
|
92
360
|
],
|
|
93
|
-
exports: [
|
|
361
|
+
exports: [
|
|
362
|
+
AuthNPaasService
|
|
363
|
+
]
|
|
94
364
|
};
|
|
95
365
|
}
|
|
96
366
|
};
|
|
97
|
-
AuthNPaasModule =
|
|
367
|
+
AuthNPaasModule = _ts_decorate4([
|
|
98
368
|
Module({})
|
|
99
369
|
], AuthNPaasModule);
|
|
100
370
|
|
|
@@ -112,8 +382,10 @@ var NeedLogin = /* @__PURE__ */ __name((loginPath) => {
|
|
|
112
382
|
}, "NeedLogin");
|
|
113
383
|
export {
|
|
114
384
|
AUTHNPAAS_MODULE_OPTIONS,
|
|
385
|
+
AuthNPaasController,
|
|
115
386
|
AuthNPaasGuard,
|
|
116
387
|
AuthNPaasModule,
|
|
388
|
+
AuthNPaasService,
|
|
117
389
|
IS_PUBLIC_KEY,
|
|
118
390
|
NEED_LOGIN_KEY,
|
|
119
391
|
NeedLogin,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/authnpaas.module.ts","../src/const.ts","../src/guards/authnpaas.guard.ts","../src/decorators/public.decorator.ts","../src/decorators/need-login.decorator.ts"],"sourcesContent":["import { DynamicModule, Module } from '@nestjs/common';\nimport { APP_GUARD, Reflector } from '@nestjs/core';\nimport { AuthNPaasModuleOptions } from './types';\nimport { AUTHNPAAS_MODULE_OPTIONS } from './const';\nimport { AuthNPaasGuard } from './guards/authnpaas.guard';\n\n@Module({})\nexport class AuthNPaasModule {\n static forRoot(options?: AuthNPaasModuleOptions): DynamicModule {\n return {\n module: AuthNPaasModule,\n global: true,\n controllers: [],\n providers: [\n // 配置提供者\n {\n provide: AUTHNPAAS_MODULE_OPTIONS,\n useValue: {\n ...(options || {}),\n },\n },\n // 核心服务\n Reflector,\n // 服务提供者\n AuthNPaasGuard,\n // 守卫提供者\n {\n provide: APP_GUARD,\n useClass: AuthNPaasGuard,\n },\n ],\n exports: [],\n };\n }\n}\n","/**\n * 常量\n */\n\n/** AuthNPaas 模块选项 Token */\nexport const AUTHNPAAS_MODULE_OPTIONS = Symbol('AUTHNPAAS_MODULE_OPTIONS');\n\n/**\n * 元数据键\n */\n\n/** 需要登录元数据键 */\nexport const NEED_LOGIN_KEY = 'authnpaas:needLogin';\n","import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';\nimport { Response } from 'express';\nimport { Reflector } from '@nestjs/core';\nimport { NEED_LOGIN_KEY } from '../const';\n\n/**\n * AuthNPaas 守卫\n * 负责协调所有鉴权检查,具体检查逻辑委托给 PermissionService\n */\n@Injectable()\nexport class AuthNPaasGuard implements CanActivate {\n constructor(private reflector: Reflector) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const http = context.switchToHttp();\n const request = http.getRequest();\n const response = http.getResponse<Response>();\n\n const { userId, loginUrl } = request.userContext || {};\n\n // 读取 NeedLogin 元数据并标记到请求对象,供异常过滤器使用\n const needLoginMeta = this.reflector.getAllAndOverride<{\n loginPath?: string;\n }>(NEED_LOGIN_KEY, [context.getHandler(), context.getClass()]);\n\n // NeedLogin 且无 userId -> 在守卫内透出跳转 url\n if (needLoginMeta && !userId && loginUrl) {\n response.setHeader('x-login-url', loginUrl);\n throw new UnauthorizedException('未登录');\n }\n\n return true;\n }\n}\n","import { SetMetadata } from '@nestjs/common';\n\n/**\n * Public 装饰器的元数据键\n */\nexport const IS_PUBLIC_KEY = 'isPublic';\n\n/**\n * 标记接口为公开接口,跳过 AuthNPaasGuard 的鉴权检查\n * \n * @example\n * ```typescript\n * @Controller('mock-api/users')\n * @Public() // 控制器级别\n * export class MockPermissionController {\n * @Get(':userId/permissions')\n * getUserPermissions() {}\n * }\n * \n * // 或者在方法级别\n * @Controller('api')\n * export class ApiController {\n * @Get('public-info')\n * @Public() // 方法级别\n * getPublicInfo() {}\n * }\n * ```\n */\nexport const Public = () => SetMetadata(IS_PUBLIC_KEY, true);\n\n","import { SetMetadata } from '@nestjs/common';\nimport { NEED_LOGIN_KEY } from '../const';\n\n/**\n * NeedLogin 装饰器\n * 标记接口需要登录。如果鉴权失败(如 401/403),异常过滤器会将请求重定向到登录页。\n * 可选地传入登录页路径,默认 '/login'。\n */\nexport const NeedLogin = (loginPath?: string): MethodDecorator & ClassDecorator => {\n return SetMetadata(NEED_LOGIN_KEY, { loginPath });\n};\n\n\n"],"mappings":";;;;AAAA,SAAwBA,cAAc;AACtC,SAASC,WAAWC,aAAAA,kBAAiB;;;ACI9B,IAAMC,2BAA2BC,OAAO,0BAAA;AAOxC,IAAMC,iBAAiB;;;ACZ9B,SAASC,YAA2CC,6BAA6B;AAEjF,SAASC,iBAAiB;;;;;;;;;;;;AAQnB,IAAMC,iBAAN,MAAMA;SAAAA;;;;EACX,YAAoBC,WAAsB;SAAtBA,YAAAA;EAAuB;EAE3C,MAAMC,YAAYC,SAA6C;AAC7D,UAAMC,OAAOD,QAAQE,aAAY;AACjC,UAAMC,UAAUF,KAAKG,WAAU;AAC/B,UAAMC,WAAWJ,KAAKK,YAAW;AAEjC,UAAM,EAAEC,QAAQC,SAAQ,IAAKL,QAAQM,eAAe,CAAC;AAGrD,UAAMC,gBAAgB,KAAKZ,UAAUa,kBAElCC,gBAAgB;MAACZ,QAAQa,WAAU;MAAIb,QAAQc,SAAQ;KAAG;AAG7D,QAAIJ,iBAAiB,CAACH,UAAUC,UAAU;AACxCH,eAASU,UAAU,eAAeP,QAAAA;AAClC,YAAM,IAAIQ,sBAAsB,oBAAA;IAClC;AAEA,WAAO;EACT;AACF;;;;;;;;;;;;;;;;;AF1BO,IAAMC,kBAAN,MAAMA,iBAAAA;SAAAA;;;EACX,OAAOC,QAAQC,SAAiD;AAC9D,WAAO;MACLC,QAAQH;MACRI,QAAQ;MACRC,aAAa,CAAA;MACbC,WAAW;;QAET;UACEC,SAASC;UACTC,UAAU;YACR,GAAIP,WAAW,CAAC;UAClB;QACF;;QAEAQ;;QAEAC;;QAEA;UACEJ,SAASK;UACTC,UAAUF;QACZ;;MAEFG,SAAS,CAAA;IACX;EACF;AACF;;;;;;AGlCA,SAASC,mBAAmB;AAKrB,IAAMC,gBAAgB;AAuBtB,IAAMC,SAAS,6BAAMC,YAAYF,eAAe,IAAA,GAAjC;;;AC5BtB,SAASG,eAAAA,oBAAmB;AAQrB,IAAMC,YAAY,wBAACC,cAAAA;AACxB,SAAOC,aAAYC,gBAAgB;IAAEF;EAAU,CAAA;AACjD,GAFyB;","names":["Module","APP_GUARD","Reflector","AUTHNPAAS_MODULE_OPTIONS","Symbol","NEED_LOGIN_KEY","Injectable","UnauthorizedException","Reflector","AuthNPaasGuard","reflector","canActivate","context","http","switchToHttp","request","getRequest","response","getResponse","userId","loginUrl","userContext","needLoginMeta","getAllAndOverride","NEED_LOGIN_KEY","getHandler","getClass","setHeader","UnauthorizedException","AuthNPaasModule","forRoot","options","module","global","controllers","providers","provide","AUTHNPAAS_MODULE_OPTIONS","useValue","Reflector","AuthNPaasGuard","APP_GUARD","useClass","exports","SetMetadata","IS_PUBLIC_KEY","Public","SetMetadata","SetMetadata","NeedLogin","loginPath","SetMetadata","NEED_LOGIN_KEY"]}
|
|
1
|
+
{"version":3,"sources":["../src/authnpaas.module.ts","../src/const.ts","../src/guards/authnpaas.guard.ts","../src/services/authnpaas.service.ts","../src/controllers/authnpaas.controller.ts","../src/decorators/public.decorator.ts","../src/decorators/need-login.decorator.ts"],"sourcesContent":["import { DynamicModule, Module } from '@nestjs/common';\nimport { APP_GUARD, Reflector } from '@nestjs/core';\nimport { AuthNPaasModuleOptions } from './types';\nimport { AUTHNPAAS_MODULE_OPTIONS } from './const';\nimport { AuthNPaasGuard } from './guards/authnpaas.guard';\nimport { AuthNPaasService } from './services/authnpaas.service';\nimport { AuthNPaasController } from './controllers/authnpaas.controller';\n\n@Module({})\nexport class AuthNPaasModule {\n static forRoot(options?: AuthNPaasModuleOptions): DynamicModule {\n return {\n module: AuthNPaasModule,\n global: true,\n controllers: [AuthNPaasController],\n providers: [\n // 配置提供者\n {\n provide: AUTHNPAAS_MODULE_OPTIONS,\n useValue: {\n ...(options || {}),\n },\n },\n // 核心服务\n Reflector,\n // 服务提供者\n AuthNPaasGuard,\n AuthNPaasService,\n // 守卫提供者\n {\n provide: APP_GUARD,\n useClass: AuthNPaasGuard,\n },\n ],\n exports: [AuthNPaasService],\n };\n }\n}\n","/**\n * 常量\n */\n\n/** AuthNPaas 模块选项 Token */\nexport const AUTHNPAAS_MODULE_OPTIONS = Symbol('AUTHNPAAS_MODULE_OPTIONS');\n\n/**\n * 元数据键\n */\n\n/** 需要登录元数据键 */\nexport const NEED_LOGIN_KEY = 'authnpaas:needLogin';\n","import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';\nimport { Response } from 'express';\nimport { Reflector } from '@nestjs/core';\nimport { NEED_LOGIN_KEY } from '../const';\n\n/**\n * AuthNPaas 守卫\n * 负责协调所有鉴权检查,具体检查逻辑委托给 PermissionService\n */\n@Injectable()\nexport class AuthNPaasGuard implements CanActivate {\n constructor(private reflector: Reflector) {}\n\n async canActivate(context: ExecutionContext): Promise<boolean> {\n const http = context.switchToHttp();\n const request = http.getRequest();\n const response = http.getResponse<Response>();\n\n const { userId, loginUrl } = request.userContext || {};\n\n // 读取 NeedLogin 元数据并标记到请求对象,供异常过滤器使用\n const needLoginMeta = this.reflector.getAllAndOverride<{\n loginPath?: string;\n }>(NEED_LOGIN_KEY, [context.getHandler(), context.getClass()]);\n\n // NeedLogin 且无 userId -> 在守卫内透出跳转 url\n if (needLoginMeta && !userId && loginUrl) {\n response.setHeader('x-login-url', loginUrl);\n throw new UnauthorizedException('未登录');\n }\n\n return true;\n }\n}\n","import { Injectable, Inject, Logger } from '@nestjs/common';\nimport {\n PLATFORM_HTTP_CLIENT,\n OBSERVABLE_SERVICE,\n type PlatformHttpClient,\n type ObservableService,\n RequestContextService,\n createTimer,\n} from '@lark-apaas/nestjs-common';\n\nconst SDK_MODULE = 'authn';\n\n/**\n * 妙搭用户ID → 飞书用户ID 的转换类型\n */\nconst CONVERT_TYPE_FORCE_TO_FEISHU = 30;\n\n/**\n * ID 转换结果项\n */\nexport interface UserIDMappingItem {\n sourceUserID: string;\n targetUserID: string;\n}\n\n/**\n * 批量转换响应\n */\ninterface BatchConvertResponse {\n data?: {\n items?: UserIDMappingItem[];\n };\n status_code?: string;\n status_message?: string;\n error_msg?: string;\n}\n\n@Injectable()\nexport class AuthNPaasService {\n private readonly logger = new Logger(AuthNPaasService.name);\n\n constructor(\n @Inject(PLATFORM_HTTP_CLIENT) private readonly httpClient: PlatformHttpClient,\n @Inject(OBSERVABLE_SERVICE) private readonly obs: ObservableService,\n private readonly requestContext: RequestContextService,\n ) {}\n\n /**\n * 获取当前登录用户的飞书 user_id\n *\n * 从请求上下文获取当前妙搭 userId,调用转换接口获取对应的飞书 user_id\n *\n * @returns 飞书 user_id,如果当前用户未登录或转换失败返回 null\n */\n async getCurrentUserLarkUserId(): Promise<string | null> {\n const userId = this.requestContext.get('userId');\n if (!userId) {\n this.logger.warn('getCurrentUserLarkUserId: no userId in request context');\n return null;\n }\n\n const items = await this.batchConvertUserIds('getCurrentUserLarkUserId', [userId]);\n if (!items || items.length === 0) {\n return null;\n }\n\n return items[0].targetUserID || null;\n }\n\n /**\n * 批量将妙搭 userId 转换为飞书 user_id\n *\n * @param userIds - 妙搭用户 ID 列表,最多 100 个\n * @returns 飞书 user_id 数组,顺序与输入对应,转换失败的项为 null\n */\n async getBatchLarkUserIds(userIds: string[]): Promise<(string | null)[]> {\n if (!userIds || userIds.length === 0) {\n return [];\n }\n\n if (userIds.length > 100) {\n throw new Error('userIds length must not exceed 100');\n }\n\n const items = await this.batchConvertUserIds('getBatchLarkUserIds', userIds);\n const mapping = new Map(items.map(item => [item.sourceUserID, item.targetUserID]));\n return userIds.map(id => mapping.get(id) ?? null);\n }\n\n /**\n * 调用批量转换接口(带可观测性)\n */\n private async batchConvertUserIds(method: string, userIds: string[]): Promise<UserIDMappingItem[]> {\n const appId = this.requestContext.get('appId');\n if (!appId) {\n this.logger.warn(`${method}: no appId in request context`);\n return [];\n }\n\n const url = `/v1/app/${appId}/account/user/convert`;\n const body = {\n convertType: CONVERT_TYPE_FORCE_TO_FEISHU,\n userIDList: userIds,\n };\n\n const spanName = `${SDK_MODULE}.${method}`;\n const spanAttrs: Record<string, unknown> = {\n module: SDK_MODULE,\n method,\n source_type: 'platform',\n paas_attributes_module: SDK_MODULE,\n http_method: 'POST',\n path: url,\n };\n const logAttrs: Record<string, unknown> = {\n source_type: 'platform',\n paas_attributes_module: SDK_MODULE,\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return this.obs.trace(spanName, async (span: any) => {\n span.setAttributes(spanAttrs);\n const elapsed = createTimer();\n\n try {\n this.logger.log(`[batchConvertUserIds] request: ${url} ${JSON.stringify(body)}`);\n const response = await this.httpClient.post(url, body);\n const logId = response.headers?.get?.('x-tt-logid') ?? '';\n const raw = await response.text();\n const durationMs = elapsed();\n\n this.logger.log(`[batchConvertUserIds] response: status=${response.status} ok=${response.ok} logId=${logId} raw=${raw}`);\n\n if (!response.ok) {\n span.setAttributes({ duration_ms: durationMs, success: false, error: `HTTP ${response.status}`, 'x-tt-logid': logId });\n this.logger.warn(JSON.stringify({\n method, path: url, duration_ms: durationMs, success: false,\n error: `HTTP ${response.status} ${response.statusText}`,\n 'x-tt-logid': logId, params: { convertType: CONVERT_TYPE_FORCE_TO_FEISHU, count: userIds.length },\n }), logAttrs);\n return [];\n }\n\n const result: BatchConvertResponse = raw ? JSON.parse(raw) : {};\n\n if (String(result.status_code) !== '0' && result.status_code !== undefined) {\n const errMsg = `[${result.status_code}] ${result.status_message || result.error_msg}`;\n span.setAttributes({ duration_ms: durationMs, success: false, error: errMsg, 'x-tt-logid': logId });\n this.logger.error(JSON.stringify({\n method, path: url, duration_ms: durationMs, success: false,\n error: errMsg, 'x-tt-logid': logId,\n params: { convertType: CONVERT_TYPE_FORCE_TO_FEISHU, count: userIds.length },\n }), logAttrs);\n return [];\n }\n\n const items = result.data?.items ?? [];\n\n span.setAttributes({ duration_ms: durationMs, success: true, 'x-tt-logid': logId, result_count: items.length });\n this.logger.log(JSON.stringify({\n method, path: url, duration_ms: durationMs, success: true,\n 'x-tt-logid': logId,\n params: { convertType: CONVERT_TYPE_FORCE_TO_FEISHU, count: userIds.length },\n result_count: items.length,\n response: raw.length > 1024 ? raw.slice(0, 1024) + '...' : raw,\n }), logAttrs);\n\n return items;\n } catch (error: any) {\n const durationMs = elapsed();\n const errMsg = error instanceof Error ? error.message : String(error);\n\n const logId = error?.headers?.get?.('x-tt-logid') ?? error?.response?.headers?.['x-tt-logid'] ?? error?.logId ?? '';\n this.logger.error(`[batchConvertUserIds] CATCH: ${errMsg} logId=${logId}`);\n\n span.setAttributes({ duration_ms: durationMs, success: false, error: errMsg });\n this.logger.warn(JSON.stringify({\n method, path: url, duration_ms: durationMs, success: false,\n error: errMsg,\n params: { convertType: CONVERT_TYPE_FORCE_TO_FEISHU, count: userIds.length },\n }), logAttrs);\n return [];\n }\n });\n }\n}\n","import { Controller, Get } from '@nestjs/common';\nimport { ApiExcludeController } from '@nestjs/swagger';\nimport { AuthNPaasService } from '../services/authnpaas.service';\n\n@ApiExcludeController()\n@Controller('api/authnpaas')\nexport class AuthNPaasController {\n constructor(private readonly authnService: AuthNPaasService) {}\n\n /**\n * 获取当前登录用户的飞书 user_id\n *\n * GET /api/authnpaas/lark-user-id\n */\n @Get('lark-user-id')\n async getCurrentUserLarkUserId() {\n const larkUserId = await this.authnService.getCurrentUserLarkUserId();\n return { lark_user_id: larkUserId };\n }\n}\n","import { SetMetadata } from '@nestjs/common';\n\n/**\n * Public 装饰器的元数据键\n */\nexport const IS_PUBLIC_KEY = 'isPublic';\n\n/**\n * 标记接口为公开接口,跳过 AuthNPaasGuard 的鉴权检查\n * \n * @example\n * ```typescript\n * @Controller('mock-api/users')\n * @Public() // 控制器级别\n * export class MockPermissionController {\n * @Get(':userId/permissions')\n * getUserPermissions() {}\n * }\n * \n * // 或者在方法级别\n * @Controller('api')\n * export class ApiController {\n * @Get('public-info')\n * @Public() // 方法级别\n * getPublicInfo() {}\n * }\n * ```\n */\nexport const Public = () => SetMetadata(IS_PUBLIC_KEY, true);\n\n","import { SetMetadata } from '@nestjs/common';\nimport { NEED_LOGIN_KEY } from '../const';\n\n/**\n * NeedLogin 装饰器\n * 标记接口需要登录。如果鉴权失败(如 401/403),异常过滤器会将请求重定向到登录页。\n * 可选地传入登录页路径,默认 '/login'。\n */\nexport const NeedLogin = (loginPath?: string): MethodDecorator & ClassDecorator => {\n return SetMetadata(NEED_LOGIN_KEY, { loginPath });\n};\n\n\n"],"mappings":";;;;AAAA,SAAwBA,cAAc;AACtC,SAASC,WAAWC,aAAAA,kBAAiB;;;ACI9B,IAAMC,2BAA2BC,uBAAO,0BAAA;AAOxC,IAAMC,iBAAiB;;;ACZ9B,SAASC,YAA2CC,6BAA6B;AAEjF,SAASC,iBAAiB;;;;;;;;;;;;AAQnB,IAAMC,iBAAN,MAAMA;SAAAA;;;;EACX,YAAoBC,WAAsB;SAAtBA,YAAAA;EAAuB;EAE3C,MAAMC,YAAYC,SAA6C;AAC7D,UAAMC,OAAOD,QAAQE,aAAY;AACjC,UAAMC,UAAUF,KAAKG,WAAU;AAC/B,UAAMC,WAAWJ,KAAKK,YAAW;AAEjC,UAAM,EAAEC,QAAQC,SAAQ,IAAKL,QAAQM,eAAe,CAAC;AAGrD,UAAMC,gBAAgB,KAAKZ,UAAUa,kBAElCC,gBAAgB;MAACZ,QAAQa,WAAU;MAAIb,QAAQc,SAAQ;KAAG;AAG7D,QAAIJ,iBAAiB,CAACH,UAAUC,UAAU;AACxCH,eAASU,UAAU,eAAeP,QAAAA;AAClC,YAAM,IAAIQ,sBAAsB,oBAAA;IAClC;AAEA,WAAO;EACT;AACF;;;;;;;;;;ACjCA,SAASC,cAAAA,aAAYC,QAAQC,cAAc;AAC3C,SACEC,sBACAC,oBAGAC,uBACAC,mBACK;;;;;;;;;;;;;;;;;;AAEP,IAAMC,aAAa;AAKnB,IAAMC,+BAA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,OAAOS;QAAO,CAAA;AAC5E,aAAKjE,OAAOS,KAAKkC,KAAKC,UAAU;UAC9BrB;UAAQY,MAAMV;UAAK6B,aAAaH;UAAYI,SAAS;UACrDC,OAAOS;UACPP,QAAQ;YAAE/B,aAAa7B;YAA8B6D,OAAO5C,QAAQH;UAAO;QAC7E,CAAA,GAAIwB,QAAAA;AACJ,eAAO,CAAA;MACT;IACF,CAAA;EACF;AACF;;;;;;;;;;;;;;ACzLA,SAASoC,YAAYC,WAAW;AAChC,SAASC,4BAA4B;;;;;;;;;;;;AAK9B,IAAMC,sBAAN,MAAMA;SAAAA;;;;EACX,YAA6BC,cAAgC;SAAhCA,eAAAA;EAAiC;;;;;;EAO9D,MACMC,2BAA2B;AAC/B,UAAMC,aAAa,MAAM,KAAKF,aAAaC,yBAAwB;AACnE,WAAO;MAAEE,cAAcD;IAAW;EACpC;AACF;;;;;;;;;;;;;;;;;;;;;;;;AJVO,IAAME,kBAAN,MAAMA,iBAAAA;SAAAA;;;EACX,OAAOC,QAAQC,SAAiD;AAC9D,WAAO;MACLC,QAAQH;MACRI,QAAQ;MACRC,aAAa;QAACC;;MACdC,WAAW;;QAET;UACEC,SAASC;UACTC,UAAU;YACR,GAAIR,WAAW,CAAC;UAClB;QACF;;QAEAS;;QAEAC;QACAC;;QAEA;UACEL,SAASM;UACTC,UAAUH;QACZ;;MAEFI,SAAS;QAACH;;IACZ;EACF;AACF;;;;;;AKrCA,SAASI,mBAAmB;AAKrB,IAAMC,gBAAgB;AAuBtB,IAAMC,SAAS,6BAAMC,YAAYF,eAAe,IAAA,GAAjC;;;AC5BtB,SAASG,eAAAA,oBAAmB;AAQrB,IAAMC,YAAY,wBAACC,cAAAA;AACxB,SAAOC,aAAYC,gBAAgB;IAAEF;EAAU,CAAA;AACjD,GAFyB;","names":["Module","APP_GUARD","Reflector","AUTHNPAAS_MODULE_OPTIONS","Symbol","NEED_LOGIN_KEY","Injectable","UnauthorizedException","Reflector","AuthNPaasGuard","reflector","canActivate","context","http","switchToHttp","request","getRequest","response","getResponse","userId","loginUrl","userContext","needLoginMeta","getAllAndOverride","NEED_LOGIN_KEY","getHandler","getClass","setHeader","UnauthorizedException","Injectable","Inject","Logger","PLATFORM_HTTP_CLIENT","OBSERVABLE_SERVICE","RequestContextService","createTimer","SDK_MODULE","CONVERT_TYPE_FORCE_TO_FEISHU","AuthNPaasService","logger","Logger","name","httpClient","obs","requestContext","getCurrentUserLarkUserId","userId","get","warn","items","batchConvertUserIds","length","targetUserID","getBatchLarkUserIds","userIds","Error","mapping","Map","map","item","sourceUserID","id","method","appId","url","body","convertType","userIDList","spanName","spanAttrs","module","source_type","paas_attributes_module","http_method","path","logAttrs","trace","span","setAttributes","elapsed","createTimer","log","JSON","stringify","response","post","logId","headers","raw","text","durationMs","status","ok","duration_ms","success","error","statusText","params","count","result","parse","String","status_code","undefined","errMsg","status_message","error_msg","data","result_count","slice","message","Controller","Get","ApiExcludeController","AuthNPaasController","authnService","getCurrentUserLarkUserId","larkUserId","lark_user_id","AuthNPaasModule","forRoot","options","module","global","controllers","AuthNPaasController","providers","provide","AUTHNPAAS_MODULE_OPTIONS","useValue","Reflector","AuthNPaasGuard","AuthNPaasService","APP_GUARD","useClass","exports","SetMetadata","IS_PUBLIC_KEY","Public","SetMetadata","SetMetadata","NeedLogin","loginPath","SetMetadata","NEED_LOGIN_KEY"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lark-apaas/nestjs-authnpaas",
|
|
3
|
-
"version": "1.0.2-alpha.
|
|
3
|
+
"version": "1.0.2-alpha.4",
|
|
4
4
|
"description": "FullStack Nestjs authnpaas",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -34,8 +34,8 @@
|
|
|
34
34
|
"clean": "rm -rf dist",
|
|
35
35
|
"lint": "eslint src/**/*.ts",
|
|
36
36
|
"type-check": "tsc --noEmit",
|
|
37
|
-
"test": "
|
|
38
|
-
"test:watch": "
|
|
37
|
+
"test": "vitest run",
|
|
38
|
+
"test:watch": "vitest --watch",
|
|
39
39
|
"prepublishOnly": "npm run build"
|
|
40
40
|
},
|
|
41
41
|
"dependencies": {
|
|
@@ -45,19 +45,18 @@
|
|
|
45
45
|
"@nestjs/testing": "^10.0.0",
|
|
46
46
|
"@testcontainers/postgresql": "^10.13.2",
|
|
47
47
|
"@types/express": "^5.0.0",
|
|
48
|
-
"@types/jest": "^29.5.0",
|
|
49
48
|
"@types/node": "^20.0.0",
|
|
50
49
|
"@typescript-eslint/eslint-plugin": "^6.0.0",
|
|
51
50
|
"@typescript-eslint/parser": "^6.0.0",
|
|
52
51
|
"eslint": "^8.42.0",
|
|
53
|
-
"jest": "^29.7.0",
|
|
54
52
|
"testcontainers": "^10.13.2",
|
|
55
|
-
"ts-jest": "^29.1.1",
|
|
56
53
|
"ts-node": "^10.9.2",
|
|
57
54
|
"tsup": "^8.0.0",
|
|
58
|
-
"typescript": "^5.0.0"
|
|
55
|
+
"typescript": "^5.0.0",
|
|
56
|
+
"vitest": "^3.2.4"
|
|
59
57
|
},
|
|
60
58
|
"peerDependencies": {
|
|
59
|
+
"@lark-apaas/nestjs-common": "workspace:*",
|
|
61
60
|
"@nestjs/common": "^10.0.0",
|
|
62
61
|
"@nestjs/core": "^10.0.0",
|
|
63
62
|
"@nestjs/swagger": "^7.4.2"
|