feat: 支持按品牌配置微信登录凭据
This commit is contained in:
1 parent
e75c524343
commit
d0a0eeea8c
23 files changed
+460
-62
No files matched your search
@@ -18,4 +18,9 @@ export class UpdateMiniAppSettingsDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
privateKey?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(128)
|
||||
appSecret?: string;
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import { Prisma } from "@prisma/client";
|
||||
import { AdminMiniAppReleaseService } from "./admin-miniapp-release.service.js";
|
||||
import { miniappArtifactRoot } from "./miniapp-artifact.js";
|
||||
import { miniappApiBaseUrl, validateApiBaseUrl, weappAppId } from "./miniapp-build-config.js";
|
||||
import { encryptMiniAppCredential } from "./miniapp-credential-crypto.js";
|
||||
import { encryptMiniAppCredential } from "../../miniapp-credential-crypto.js";
|
||||
import { inspectPrivateKey, normalizePrivateKey } from "./miniapp-private-key.js";
|
||||
import type { UpdateMiniAppSettingsDto } from "./admin-miniapp-settings.dto.js";
|
||||
|
||||
@@ -18,10 +18,17 @@ export class AdminMiniAppSettingsService {
|
||||
|
||||
async update(brandId: string, body: UpdateMiniAppSettingsDto & { privateKey?: string }) {
|
||||
if (body.privateKey !== undefined) this.validatePrivateKey(body.privateKey);
|
||||
if (body.appSecret !== undefined) this.validateAppSecret(body.appSecret);
|
||||
const current = this.jsonObject(await this.releases.settings(brandId));
|
||||
const currentAppId = typeof current.appId === "string" ? current.appId : "";
|
||||
const nextAppId = body.appId === undefined ? currentAppId : body.appId.trim();
|
||||
if (currentAppId && nextAppId !== currentAppId && body.appSecret === undefined)
|
||||
throw new BadRequestException(
|
||||
"修改微信 AppID 时必须同时填写该 AppID 对应的 AppSecret,避免登录凭据与小程序不匹配",
|
||||
);
|
||||
const settings = {
|
||||
...current,
|
||||
appId: body.appId ?? current.appId ?? "",
|
||||
appId: nextAppId,
|
||||
apiBaseUrl:
|
||||
body.apiBaseUrl === undefined ? (current.apiBaseUrl ?? "") : this.apiBaseUrl(body),
|
||||
build: {
|
||||
@@ -31,6 +38,9 @@ export class AdminMiniAppSettingsService {
|
||||
...(body.privateKey === undefined
|
||||
? {}
|
||||
: { credential: encryptMiniAppCredential(normalizePrivateKey(body.privateKey)) }),
|
||||
...(body.appSecret === undefined
|
||||
? {}
|
||||
: { appSecretCredential: encryptMiniAppCredential(body.appSecret.trim()) }),
|
||||
templateKey: current.templateKey ?? null,
|
||||
} satisfies Prisma.InputJsonObject;
|
||||
await this.releases.saveSettings(brandId, settings);
|
||||
@@ -47,6 +57,14 @@ export class AdminMiniAppSettingsService {
|
||||
);
|
||||
}
|
||||
|
||||
private validateAppSecret(appSecret: string) {
|
||||
const trimmed = appSecret.trim();
|
||||
if (!/^[A-Za-z0-9]{16,64}$/.test(trimmed))
|
||||
throw new BadRequestException(
|
||||
"微信登录 AppSecret 格式无效:应为 16-64 位字母或数字,请从微信公众平台复制完整值",
|
||||
);
|
||||
}
|
||||
|
||||
private apiBaseUrl(body: UpdateMiniAppSettingsDto) {
|
||||
const trimmed = body.apiBaseUrl?.trim();
|
||||
if (!trimmed) throw new BadRequestException("小程序请求地址不能为空");
|
||||
@@ -58,16 +76,21 @@ export class AdminMiniAppSettingsService {
|
||||
}
|
||||
|
||||
private present(settings: Record<string, unknown>) {
|
||||
const { credential, appSecretCredential, ...rest } = settings;
|
||||
delete rest.appSecret;
|
||||
const appId = typeof rest.appId === "string" ? rest.appId : "";
|
||||
return {
|
||||
appId: "",
|
||||
artifactPath: miniappArtifactRoot(),
|
||||
build: {},
|
||||
...settings,
|
||||
apiBaseUrl: this.effectiveApiBaseUrl(settings.apiBaseUrl),
|
||||
...rest,
|
||||
apiBaseUrl: this.effectiveApiBaseUrl(rest.apiBaseUrl),
|
||||
privateKey: undefined,
|
||||
credential: settings.credential ? { algorithm: "aes-256-gcm" } : null,
|
||||
hasStoredCredentials: Boolean(settings.credential),
|
||||
...this.buildConfigSummary(settings.apiBaseUrl, settings.appId),
|
||||
credential: credential ? { algorithm: "aes-256-gcm" } : null,
|
||||
hasStoredCredentials: Boolean(credential),
|
||||
hasStoredAppSecret: Boolean(appSecretCredential),
|
||||
loginConfigured: Boolean(appId && appSecretCredential),
|
||||
...this.buildConfigSummary(rest.apiBaseUrl, rest.appId),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
import { miniappReleaseProjectPath, miniappTaroOutputRoot } from "./miniapp-artifact.js";
|
||||
import { miniappApiBaseUrl, weappAppId } from "./miniapp-build-config.js";
|
||||
import { buildingStaleMs, isStaleBuilding } from "./miniapp-build-status.js";
|
||||
import { decryptMiniAppCredential } from "./miniapp-credential-crypto.js";
|
||||
import { decryptMiniAppCredential } from "../../miniapp-credential-crypto.js";
|
||||
import { inspectPrivateKey, normalizePrivateKey } from "./miniapp-private-key.js";
|
||||
import { runMiniAppUpload } from "./miniapp-upload.js";
|
||||
|
||||
@@ -68,7 +68,7 @@ export class AdminMiniAppUploadService {
|
||||
const keyInspection = inspectPrivateKey(normalizedPrivateKey);
|
||||
if (!keyInspection.valid)
|
||||
throw new BadRequestException(
|
||||
`上传私钥无法解析(${keyInspection.reason ?? "PEM 格式错误"})。请在“小程序上传配置”里重新粘贴完整私钥。`,
|
||||
`上传私钥无法解析(${keyInspection.reason ?? "PEM 格式错误"})。请在“小程序配置”里重新粘贴完整私钥。`,
|
||||
);
|
||||
|
||||
const templateManifest = miniAppTemplateManifest(brand.templateKey);
|
||||
|
||||
@@ -26,7 +26,7 @@ export function miniappApiBaseUrl(
|
||||
normalizeBaseUrl(`${normalizeBaseUrl(publicBase)}${env.MINIAPP_API_PATH ?? "/api"}`),
|
||||
);
|
||||
throw new Error(
|
||||
"未配置小程序请求地址:请在“配置与发布 → 小程序上传配置”里填写“小程序请求地址”,例如 https://wechat.app.que01.top/api",
|
||||
"未配置小程序请求地址:请在“配置与发布 → 小程序配置”里填写“小程序请求地址”,例如 https://wechat.app.que01.top/api",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -53,6 +53,6 @@ export function weappAppId(storedAppId: unknown, env: NodeJS.ProcessEnv = proces
|
||||
? storedAppId.trim()
|
||||
: (env.WEAPP_APP_ID?.trim() ?? "");
|
||||
if (!candidate || candidate === "undefined" || candidate === "touristappid")
|
||||
throw new Error("未配置微信 AppID:请在“小程序上传配置”里填写或设置 WEAPP_APP_ID");
|
||||
throw new Error("未配置微信 AppID:请在“小程序配置”里填写或设置 WEAPP_APP_ID");
|
||||
return candidate;
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
|
||||
import { UnauthorizedException } from "@nestjs/common";
|
||||
|
||||
const ALGORITHM = "aes-256-gcm";
|
||||
|
||||
export function encryptionKey(): Buffer {
|
||||
const value = process.env.MINIAPP_CREDENTIAL_ENCRYPTION_KEY ?? process.env.SESSION_SECRET;
|
||||
if (!value || value.length < 32) throw new UnauthorizedException("小程序凭据加密密钥未正确配置");
|
||||
return createHash("sha256").update(value).digest();
|
||||
}
|
||||
|
||||
export function encryptMiniAppCredential(plaintext: string): {
|
||||
ciphertext: string;
|
||||
iv: string;
|
||||
authTag: string;
|
||||
algorithm: string;
|
||||
} {
|
||||
const iv = randomBytes(12);
|
||||
const cipher = createCipheriv(ALGORITHM, encryptionKey(), iv);
|
||||
const ciphertext = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
|
||||
return {
|
||||
algorithm: ALGORITHM,
|
||||
ciphertext: ciphertext.toString("base64"),
|
||||
iv: iv.toString("base64"),
|
||||
authTag: cipher.getAuthTag().toString("base64"),
|
||||
};
|
||||
}
|
||||
|
||||
export function decryptMiniAppCredential(value: unknown): string {
|
||||
const payload =
|
||||
value && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: null;
|
||||
if (
|
||||
!payload ||
|
||||
payload.algorithm !== ALGORITHM ||
|
||||
typeof payload.ciphertext !== "string" ||
|
||||
typeof payload.iv !== "string" ||
|
||||
typeof payload.authTag !== "string"
|
||||
)
|
||||
throw new UnauthorizedException("小程序上传凭据不可用");
|
||||
const decipher = createDecipheriv(ALGORITHM, encryptionKey(), Buffer.from(payload.iv, "base64"));
|
||||
decipher.setAuthTag(Buffer.from(payload.authTag, "base64"));
|
||||
return Buffer.concat([
|
||||
decipher.update(Buffer.from(payload.ciphertext, "base64")),
|
||||
decipher.final(),
|
||||
]).toString("utf8");
|
||||
}
|
||||
@@ -1,7 +1,11 @@
|
||||
import { BadRequestException, Injectable } from "@nestjs/common";
|
||||
import { PrismaService } from "../../prisma.service.js";
|
||||
import { signIdentity } from "../../auth.js";
|
||||
import type { WechatSession } from "../../wechat-auth.js";
|
||||
import {
|
||||
WechatAuthService,
|
||||
resolveWechatLoginCredentials,
|
||||
type WechatSession,
|
||||
} from "../../wechat-auth.js";
|
||||
import { PublicBrandContextService } from "../public/public-brand-context.service.js";
|
||||
|
||||
@Injectable()
|
||||
@@ -9,15 +13,18 @@ export class CustomerSessionService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly brandContext: PublicBrandContextService,
|
||||
private readonly wechatAuth: WechatAuthService,
|
||||
) {}
|
||||
|
||||
async loginWithWechat(session: WechatSession, brandSlug?: string): Promise<{ token: string }> {
|
||||
async loginWithWechat(code: string, brandSlug?: string): Promise<{ token: string }> {
|
||||
const brandId = await this.brandContext.resolveId(brandSlug);
|
||||
const brand = await this.prisma.brandProfile.findUnique({
|
||||
where: { id: brandId },
|
||||
select: { id: true },
|
||||
select: { id: true, miniAppSettings: true },
|
||||
});
|
||||
if (!brand) throw new BadRequestException("品牌尚未初始化");
|
||||
const credentials = resolveWechatLoginCredentials(brand.miniAppSettings);
|
||||
const session: WechatSession = await this.wechatAuth.exchangeCode(code, credentials);
|
||||
const customer = await this.prisma.customerUser.upsert({
|
||||
where: { brandId_openid: { brandId: brand.id, openid: session.openid } },
|
||||
update: { lastLoginAt: new Date() },
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { Body, Controller, Get, Post, Query, Req, Res } from "@nestjs/common";
|
||||
import type { FastifyReply, FastifyRequest } from "fastify";
|
||||
import { WechatAuthService } from "../../wechat-auth.js";
|
||||
import { AdminPublic, AdminTokenOnly } from "../../admin-auth.decorators.js";
|
||||
import { clearAdminSessionCookie, setAdminSessionCookie } from "../../admin-session-cookie.js";
|
||||
import { AdminAuthService } from "../../admin-auth.service.js";
|
||||
@@ -11,18 +10,14 @@ import { ChangeAdminPasswordDto } from "../../admin.dto.js";
|
||||
|
||||
@Controller("customer/session")
|
||||
export class CustomerSessionController {
|
||||
constructor(
|
||||
private readonly wechatAuth: WechatAuthService,
|
||||
private readonly sessions: CustomerSessionService,
|
||||
) {}
|
||||
constructor(private readonly sessions: CustomerSessionService) {}
|
||||
|
||||
@Post("wechat")
|
||||
async wechatLogin(
|
||||
@Body() body: WechatLoginDto,
|
||||
@Query("brandSlug") brandSlug?: string,
|
||||
): Promise<{ token: string }> {
|
||||
const session = await this.wechatAuth.exchangeCode(body.code);
|
||||
return this.sessions.loginWithWechat(session, brandSlug);
|
||||
return this.sessions.loginWithWechat(body.code, brandSlug);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user