feat(M02-B): 实现微信登录与可撤销会话
This commit is contained in:
@@ -8,10 +8,12 @@ import {
|
||||
registerPlatformBootstrapRoutes,
|
||||
type PlatformConfigResolver
|
||||
} from './routes/platform-bootstrap.js';
|
||||
import { registerAuthRoutes, type AuthRouteOptions } from './routes/auth.js';
|
||||
|
||||
export interface BuildAppOptions {
|
||||
config?: AppConfig;
|
||||
platformConfigRepository?: PlatformConfigResolver;
|
||||
auth?: AuthRouteOptions;
|
||||
}
|
||||
|
||||
declare module 'fastify' {
|
||||
@@ -57,6 +59,9 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
||||
if (options.platformConfigRepository) {
|
||||
await registerPlatformBootstrapRoutes(app, options.platformConfigRepository);
|
||||
}
|
||||
if (options.auth) {
|
||||
await registerAuthRoutes(app, options.auth);
|
||||
}
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
import type { PoolConnection, ResultSetHeader, RowDataPacket } from 'mysql2/promise';
|
||||
import type { MySqlPool } from '../db/mysql.js';
|
||||
|
||||
export interface LoginContext {
|
||||
tenantId: string;
|
||||
platformAppId: string;
|
||||
appId: string;
|
||||
}
|
||||
|
||||
export interface AuthUser {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
userType: string;
|
||||
status: string;
|
||||
roleVersion: number;
|
||||
nickname: string;
|
||||
avatarUrl: string;
|
||||
phone: string;
|
||||
}
|
||||
|
||||
export interface AuthSession {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
platformAppId: string;
|
||||
user: AuthUser;
|
||||
expiresAt: Date;
|
||||
}
|
||||
|
||||
interface LoginContextRow extends RowDataPacket {
|
||||
tenantId: string;
|
||||
platformAppId: string;
|
||||
appId: string;
|
||||
}
|
||||
|
||||
interface UserRow extends RowDataPacket {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
userType: string;
|
||||
status: string;
|
||||
roleVersion: number;
|
||||
nickname: string;
|
||||
avatarUrl: string;
|
||||
phone: string;
|
||||
}
|
||||
|
||||
interface SessionRow extends UserRow {
|
||||
sessionId: string;
|
||||
platformAppId: string;
|
||||
expiresAt: Date;
|
||||
}
|
||||
|
||||
export class AuthRepository {
|
||||
constructor(private readonly pool: MySqlPool) {}
|
||||
|
||||
async resolveLoginContext(appId: string, tenantId?: string): Promise<LoginContext | null> {
|
||||
const tenantFilter = tenantId ? 'AND ta.tenant_id = ?' : '';
|
||||
const [rows] = await this.pool.execute<LoginContextRow[]>(
|
||||
`SELECT ta.tenant_id AS tenantId, pa.id AS platformAppId, pa.appid AS appId
|
||||
FROM qipai_platform_apps pa
|
||||
INNER JOIN qipai_tenant_apps ta
|
||||
ON ta.platform_app_id = pa.id
|
||||
AND ta.status = 'ACTIVE' AND ta.deleted_at IS NULL
|
||||
INNER JOIN qipai_tenants t
|
||||
ON t.id = ta.tenant_id
|
||||
AND t.status = 'ACTIVE' AND t.deleted_at IS NULL
|
||||
WHERE pa.appid = ? AND pa.status = 'ACTIVE' AND pa.deleted_at IS NULL
|
||||
${tenantFilter}
|
||||
ORDER BY ta.is_default DESC, ta.tenant_id ASC
|
||||
LIMIT 2`,
|
||||
tenantId ? [appId, tenantId] : [appId]
|
||||
);
|
||||
if (!tenantId && rows.length > 1) throw new Error('TENANT_SELECTION_REQUIRED');
|
||||
const row = rows[0];
|
||||
return row ? {
|
||||
tenantId: String(row.tenantId),
|
||||
platformAppId: String(row.platformAppId),
|
||||
appId: row.appId
|
||||
} : null;
|
||||
}
|
||||
|
||||
async loginWithWechat(input: {
|
||||
context: LoginContext;
|
||||
openid: string;
|
||||
unionid?: string;
|
||||
sessionId: string;
|
||||
expiresAt: Date;
|
||||
ip: string;
|
||||
userAgent: string;
|
||||
}): Promise<AuthSession> {
|
||||
const connection = await this.pool.getConnection();
|
||||
try {
|
||||
await connection.beginTransaction();
|
||||
let user = await this.findUserByIdentity(connection, input.context, input.openid);
|
||||
if (!user) {
|
||||
const [created] = await connection.execute<ResultSetHeader>(
|
||||
`INSERT INTO qipai_users (tenant_id, user_type, status)
|
||||
VALUES (?, 'CUSTOMER', 'ACTIVE')`,
|
||||
[input.context.tenantId]
|
||||
);
|
||||
const userId = String(created.insertId);
|
||||
await connection.execute(
|
||||
`INSERT INTO qipai_user_identities
|
||||
(tenant_id, platform_app_id, user_id, openid, unionid)
|
||||
VALUES (?, ?, ?, ?, ?)`,
|
||||
[
|
||||
input.context.tenantId,
|
||||
input.context.platformAppId,
|
||||
userId,
|
||||
input.openid,
|
||||
input.unionid ?? null
|
||||
]
|
||||
);
|
||||
user = await this.findUserById(connection, input.context.tenantId, userId);
|
||||
} else if (input.unionid) {
|
||||
await connection.execute(
|
||||
`UPDATE qipai_user_identities SET unionid = COALESCE(unionid, ?)
|
||||
WHERE tenant_id = ? AND platform_app_id = ? AND user_id = ?`,
|
||||
[input.unionid, input.context.tenantId, input.context.platformAppId, user.id]
|
||||
);
|
||||
}
|
||||
if (!user || user.status !== 'ACTIVE') throw new Error('USER_DISABLED');
|
||||
await connection.execute(
|
||||
`INSERT INTO qipai_auth_sessions
|
||||
(id, tenant_id, platform_app_id, user_id, role_version, expires_at, ip, user_agent)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
[
|
||||
input.sessionId,
|
||||
input.context.tenantId,
|
||||
input.context.platformAppId,
|
||||
user.id,
|
||||
user.roleVersion,
|
||||
input.expiresAt,
|
||||
input.ip,
|
||||
input.userAgent.slice(0, 255)
|
||||
]
|
||||
);
|
||||
await connection.execute(
|
||||
`UPDATE qipai_users SET last_login_at = UTC_TIMESTAMP(3)
|
||||
WHERE tenant_id = ? AND id = ?`,
|
||||
[input.context.tenantId, user.id]
|
||||
);
|
||||
await connection.commit();
|
||||
return {
|
||||
id: input.sessionId,
|
||||
tenantId: input.context.tenantId,
|
||||
platformAppId: input.context.platformAppId,
|
||||
user,
|
||||
expiresAt: input.expiresAt
|
||||
};
|
||||
} catch (error) {
|
||||
await connection.rollback();
|
||||
throw error;
|
||||
} finally {
|
||||
connection.release();
|
||||
}
|
||||
}
|
||||
|
||||
async validateSession(sessionId: string, tenantId: string, userId: string): Promise<AuthSession | null> {
|
||||
const [rows] = await this.pool.execute<SessionRow[]>(
|
||||
`SELECT s.id AS sessionId, s.tenant_id AS tenantId,
|
||||
s.platform_app_id AS platformAppId, s.expires_at AS expiresAt,
|
||||
u.id, u.user_type AS userType, u.status,
|
||||
u.role_version AS roleVersion, u.nickname,
|
||||
u.avatar_url AS avatarUrl, u.phone
|
||||
FROM qipai_auth_sessions s
|
||||
INNER JOIN qipai_users u
|
||||
ON u.id = s.user_id AND u.tenant_id = s.tenant_id AND u.deleted_at IS NULL
|
||||
WHERE s.id = ? AND s.tenant_id = ? AND s.user_id = ?
|
||||
AND s.status = 'ACTIVE' AND s.revoked_at IS NULL
|
||||
AND s.expires_at > UTC_TIMESTAMP(3)
|
||||
AND u.status = 'ACTIVE'
|
||||
AND u.role_version = s.role_version
|
||||
LIMIT 1`,
|
||||
[sessionId, tenantId, userId]
|
||||
);
|
||||
const row = rows[0];
|
||||
if (!row) return null;
|
||||
await this.pool.execute(
|
||||
'UPDATE qipai_auth_sessions SET last_seen_at = UTC_TIMESTAMP(3) WHERE id = ?',
|
||||
[sessionId]
|
||||
);
|
||||
return {
|
||||
id: row.sessionId,
|
||||
tenantId: String(row.tenantId),
|
||||
platformAppId: String(row.platformAppId),
|
||||
expiresAt: row.expiresAt,
|
||||
user: mapUser(row)
|
||||
};
|
||||
}
|
||||
|
||||
async revokeSession(sessionId: string, reason = 'LOGOUT'): Promise<boolean> {
|
||||
const [result] = await this.pool.execute<ResultSetHeader>(
|
||||
`UPDATE qipai_auth_sessions
|
||||
SET status = 'REVOKED', revoked_at = UTC_TIMESTAMP(3), revoke_reason = ?
|
||||
WHERE id = ? AND status = 'ACTIVE'`,
|
||||
[reason, sessionId]
|
||||
);
|
||||
return result.affectedRows === 1;
|
||||
}
|
||||
|
||||
private async findUserByIdentity(
|
||||
connection: PoolConnection,
|
||||
context: LoginContext,
|
||||
openid: string
|
||||
): Promise<AuthUser | null> {
|
||||
const [rows] = await connection.execute<UserRow[]>(
|
||||
`SELECT u.id, u.tenant_id AS tenantId, u.user_type AS userType, u.status,
|
||||
u.role_version AS roleVersion, u.nickname,
|
||||
u.avatar_url AS avatarUrl, u.phone
|
||||
FROM qipai_user_identities i
|
||||
INNER JOIN qipai_users u
|
||||
ON u.id = i.user_id AND u.tenant_id = i.tenant_id AND u.deleted_at IS NULL
|
||||
WHERE i.tenant_id = ? AND i.platform_app_id = ?
|
||||
AND i.openid = ? AND i.deleted_at IS NULL
|
||||
LIMIT 1 FOR UPDATE`,
|
||||
[context.tenantId, context.platformAppId, openid]
|
||||
);
|
||||
return rows[0] ? mapUser(rows[0]) : null;
|
||||
}
|
||||
|
||||
private async findUserById(
|
||||
connection: PoolConnection,
|
||||
tenantId: string,
|
||||
userId: string
|
||||
): Promise<AuthUser | null> {
|
||||
const [rows] = await connection.execute<UserRow[]>(
|
||||
`SELECT id, tenant_id AS tenantId, user_type AS userType, status,
|
||||
role_version AS roleVersion, nickname, avatar_url AS avatarUrl, phone
|
||||
FROM qipai_users WHERE tenant_id = ? AND id = ? AND deleted_at IS NULL`,
|
||||
[tenantId, userId]
|
||||
);
|
||||
return rows[0] ? mapUser(rows[0]) : null;
|
||||
}
|
||||
}
|
||||
|
||||
function mapUser(row: UserRow): AuthUser {
|
||||
return {
|
||||
id: String(row.id),
|
||||
tenantId: String(row.tenantId),
|
||||
userType: row.userType,
|
||||
status: row.status,
|
||||
roleVersion: row.roleVersion,
|
||||
nickname: row.nickname,
|
||||
avatarUrl: row.avatarUrl,
|
||||
phone: row.phone
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { createHmac, timingSafeEqual } from 'node:crypto';
|
||||
import { z } from 'zod';
|
||||
|
||||
const claimsSchema = z.object({
|
||||
iss: z.literal('qipai-api'),
|
||||
aud: z.literal('qipai-miniapp'),
|
||||
sub: z.string().regex(/^[1-9]\d*$/),
|
||||
sid: z.string().uuid(),
|
||||
tid: z.string().regex(/^[1-9]\d*$/),
|
||||
aid: z.string().regex(/^[1-9]\d*$/),
|
||||
rv: z.number().int().positive(),
|
||||
iat: z.number().int(),
|
||||
exp: z.number().int()
|
||||
});
|
||||
|
||||
export type AccessTokenClaims = z.infer<typeof claimsSchema>;
|
||||
|
||||
function encode(value: string): string {
|
||||
return Buffer.from(value).toString('base64url');
|
||||
}
|
||||
|
||||
export function signAccessToken(
|
||||
claims: Omit<AccessTokenClaims, 'iss' | 'aud' | 'iat' | 'exp'>,
|
||||
secret: string,
|
||||
ttlSeconds: number,
|
||||
nowSeconds = Math.floor(Date.now() / 1000)
|
||||
): string {
|
||||
const header = encode(JSON.stringify({ alg: 'HS256', typ: 'JWT' }));
|
||||
const payload = encode(JSON.stringify({
|
||||
iss: 'qipai-api',
|
||||
aud: 'qipai-miniapp',
|
||||
...claims,
|
||||
iat: nowSeconds,
|
||||
exp: nowSeconds + ttlSeconds
|
||||
}));
|
||||
const signature = createHmac('sha256', secret).update(`${header}.${payload}`).digest('base64url');
|
||||
return `${header}.${payload}.${signature}`;
|
||||
}
|
||||
|
||||
export function verifyAccessToken(
|
||||
token: string,
|
||||
secret: string,
|
||||
nowSeconds = Math.floor(Date.now() / 1000)
|
||||
): AccessTokenClaims {
|
||||
const parts = token.split('.');
|
||||
if (parts.length !== 3) throw new Error('Invalid access token.');
|
||||
const [header, payload, signature] = parts;
|
||||
const expected = createHmac('sha256', secret).update(`${header}.${payload}`).digest();
|
||||
const actual = Buffer.from(signature, 'base64url');
|
||||
if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) {
|
||||
throw new Error('Invalid access token signature.');
|
||||
}
|
||||
const parsedHeader = JSON.parse(Buffer.from(header, 'base64url').toString('utf8'));
|
||||
if (parsedHeader.alg !== 'HS256' || parsedHeader.typ !== 'JWT') {
|
||||
throw new Error('Unsupported access token.');
|
||||
}
|
||||
const claims = claimsSchema.parse(
|
||||
JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'))
|
||||
);
|
||||
if (claims.exp <= nowSeconds) throw new Error('Access token expired.');
|
||||
return claims;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
export interface WechatCodeSession {
|
||||
openid: string;
|
||||
unionid?: string;
|
||||
}
|
||||
|
||||
export interface WechatCodeExchange {
|
||||
exchange(appId: string, code: string): Promise<WechatCodeSession>;
|
||||
}
|
||||
|
||||
export class WechatApiError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = 'WechatApiError';
|
||||
}
|
||||
}
|
||||
|
||||
export class WechatHttpClient implements WechatCodeExchange {
|
||||
constructor(
|
||||
private readonly appSecrets: Readonly<Record<string, string>>,
|
||||
private readonly fetcher: typeof fetch = fetch
|
||||
) {}
|
||||
|
||||
async exchange(appId: string, code: string): Promise<WechatCodeSession> {
|
||||
const secret = this.appSecrets[appId];
|
||||
if (!secret) throw new WechatApiError(`No WeChat secret configured for AppID ${appId}.`);
|
||||
const url = new URL('https://api.weixin.qq.com/sns/jscode2session');
|
||||
url.searchParams.set('appid', appId);
|
||||
url.searchParams.set('secret', secret);
|
||||
url.searchParams.set('js_code', code);
|
||||
url.searchParams.set('grant_type', 'authorization_code');
|
||||
const response = await this.fetcher(url);
|
||||
if (!response.ok) throw new WechatApiError(`WeChat HTTP ${response.status}.`);
|
||||
const payload = await response.json() as {
|
||||
openid?: string;
|
||||
unionid?: string;
|
||||
errcode?: number;
|
||||
errmsg?: string;
|
||||
};
|
||||
if (!payload.openid || payload.errcode) {
|
||||
throw new WechatApiError(`WeChat code exchange failed: ${payload.errcode ?? 'UNKNOWN'}.`);
|
||||
}
|
||||
return { openid: payload.openid, unionid: payload.unionid };
|
||||
}
|
||||
}
|
||||
|
||||
export function parseWechatAppSecrets(value: string): Readonly<Record<string, string>> {
|
||||
if (!value.trim()) return {};
|
||||
const parsed = JSON.parse(value) as unknown;
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||
throw new Error('QIPAI_WECHAT_APP_SECRETS must be a JSON object.');
|
||||
}
|
||||
return Object.fromEntries(
|
||||
Object.entries(parsed).map(([appId, secret]) => {
|
||||
if (typeof secret !== 'string' || secret.length < 8) {
|
||||
throw new Error(`Invalid WeChat secret for AppID ${appId}.`);
|
||||
}
|
||||
return [appId, secret];
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -12,6 +12,10 @@ const configSchema = z.object({
|
||||
QIPAI_MYSQL_USER: z.string().min(1).default('qipai_app'),
|
||||
QIPAI_MYSQL_PASSWORD: z.string().default(''),
|
||||
QIPAI_MYSQL_CONNECTION_LIMIT: z.coerce.number().int().min(1).max(50).default(10),
|
||||
QIPAI_JWT_SECRET: z.string().min(32).default('development-only-change-this-jwt-secret'),
|
||||
QIPAI_ACCESS_TOKEN_TTL_SECONDS: z.coerce.number().int().min(60).max(86400).default(900),
|
||||
QIPAI_SESSION_TTL_SECONDS: z.coerce.number().int().min(300).max(2592000).default(604800),
|
||||
QIPAI_WECHAT_APP_SECRETS: z.string().default('{}'),
|
||||
QIPAI_MQTT_URL: z.string().url().default('mqtt://101.42.38.246:1883'),
|
||||
QIPAI_MQTT_USERNAME: z.string().default(''),
|
||||
QIPAI_MQTT_PASSWORD: z.string().default('')
|
||||
@@ -21,6 +25,12 @@ export type AppConfig = ReturnType<typeof loadConfig>;
|
||||
|
||||
export function loadConfig(env: NodeJS.ProcessEnv = process.env) {
|
||||
const parsed = configSchema.parse(env);
|
||||
if (
|
||||
parsed.NODE_ENV === 'production'
|
||||
&& parsed.QIPAI_JWT_SECRET === 'development-only-change-this-jwt-secret'
|
||||
) {
|
||||
throw new Error('QIPAI_JWT_SECRET must be explicitly configured in production.');
|
||||
}
|
||||
|
||||
return {
|
||||
nodeEnv: parsed.NODE_ENV,
|
||||
@@ -37,6 +47,12 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env) {
|
||||
passwordConfigured: parsed.QIPAI_MYSQL_PASSWORD.length > 0,
|
||||
connectionLimit: parsed.QIPAI_MYSQL_CONNECTION_LIMIT
|
||||
},
|
||||
auth: {
|
||||
jwtSecret: parsed.QIPAI_JWT_SECRET,
|
||||
accessTokenTtlSeconds: parsed.QIPAI_ACCESS_TOKEN_TTL_SECONDS,
|
||||
sessionTtlSeconds: parsed.QIPAI_SESSION_TTL_SECONDS,
|
||||
wechatAppSecretsJson: parsed.QIPAI_WECHAT_APP_SECRETS
|
||||
},
|
||||
mqtt: {
|
||||
url: parsed.QIPAI_MQTT_URL,
|
||||
usernameConfigured: parsed.QIPAI_MQTT_USERNAME.length > 0,
|
||||
|
||||
@@ -23,14 +23,17 @@ const migrationFiles: Record<MigrationDirection, readonly string[]> = {
|
||||
up: [
|
||||
'database/migrations/2026061601_m01b_core_schema.up.sql',
|
||||
'database/migrations/2026061802_m01c_async_tasks.up.sql',
|
||||
'database/migrations/2026061803_m02a_tenant_apps.up.sql'
|
||||
'database/migrations/2026061803_m02a_tenant_apps.up.sql',
|
||||
'database/migrations/2026061804_m02b_wechat_auth.up.sql'
|
||||
],
|
||||
verify: [
|
||||
'database/migrations/2026061601_m01b_core_schema.verify.sql',
|
||||
'database/migrations/2026061802_m01c_async_tasks.verify.sql',
|
||||
'database/migrations/2026061803_m02a_tenant_apps.verify.sql'
|
||||
'database/migrations/2026061803_m02a_tenant_apps.verify.sql',
|
||||
'database/migrations/2026061804_m02b_wechat_auth.verify.sql'
|
||||
],
|
||||
down: [
|
||||
'database/migrations/2026061804_m02b_wechat_auth.down.sql',
|
||||
'database/migrations/2026061803_m02a_tenant_apps.down.sql',
|
||||
'database/migrations/2026061802_m01c_async_tasks.down.sql',
|
||||
'database/migrations/2026061601_m01b_core_schema.down.sql'
|
||||
@@ -149,7 +152,7 @@ export async function executeMigrationPlan(
|
||||
for (const [index, statement] of plan.statements.entries()) {
|
||||
const [result] = await pool.query(statement);
|
||||
if (plan.direction === 'verify') {
|
||||
const minimumRows = [10, 26, 1, 2, 5, 1, 3, 5, 1][index] ?? 1;
|
||||
const minimumRows = [10, 26, 1, 2, 5, 1, 3, 5, 1, 3, 7, 1][index] ?? 1;
|
||||
if (!Array.isArray(result) || result.length < minimumRows) {
|
||||
throw new Error(
|
||||
`Migration verification statement ${index + 1} returned fewer than ${minimumRows} rows.`
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import { z } from 'zod';
|
||||
import type { AuthRepository } from '../auth/auth-repository.js';
|
||||
import { signAccessToken, verifyAccessToken } from '../auth/jwt.js';
|
||||
import { WechatApiError, type WechatCodeExchange } from '../auth/wechat-client.js';
|
||||
|
||||
const headersSchema = z.object({
|
||||
'x-wechat-appid': z.string().trim().min(6).max(64),
|
||||
'tenant-id': z.string().regex(/^[1-9]\d{0,19}$/).optional()
|
||||
});
|
||||
const loginBodySchema = z.object({ code: z.string().trim().min(4).max(128) });
|
||||
|
||||
export interface AuthRouteOptions {
|
||||
repository: Pick<AuthRepository, 'resolveLoginContext' | 'loginWithWechat' | 'validateSession' | 'revokeSession'>;
|
||||
wechat: WechatCodeExchange;
|
||||
jwtSecret: string;
|
||||
accessTokenTtlSeconds: number;
|
||||
sessionTtlSeconds: number;
|
||||
}
|
||||
|
||||
export async function registerAuthRoutes(app: FastifyInstance, options: AuthRouteOptions): Promise<void> {
|
||||
app.post('/app-api/auth/wechat-login', async (request, reply) => {
|
||||
const headers = headersSchema.safeParse(request.headers);
|
||||
const body = loginBodySchema.safeParse(request.body);
|
||||
if (!headers.success || !body.success) {
|
||||
return reply.status(400).send({
|
||||
code: 'INVALID_LOGIN_REQUEST',
|
||||
message: 'AppID, optional tenant-id and wx.login code are required.',
|
||||
traceId: request.traceId
|
||||
});
|
||||
}
|
||||
try {
|
||||
const context = await options.repository.resolveLoginContext(
|
||||
headers.data['x-wechat-appid'],
|
||||
headers.data['tenant-id']
|
||||
);
|
||||
if (!context) {
|
||||
return reply.status(404).send({
|
||||
code: 'APP_TENANT_NOT_FOUND',
|
||||
message: 'The application and tenant binding is not active.',
|
||||
traceId: request.traceId
|
||||
});
|
||||
}
|
||||
const identity = await options.wechat.exchange(context.appId, body.data.code);
|
||||
const sessionId = randomUUID();
|
||||
const expiresAt = new Date(Date.now() + options.sessionTtlSeconds * 1000);
|
||||
const session = await options.repository.loginWithWechat({
|
||||
context,
|
||||
...identity,
|
||||
sessionId,
|
||||
expiresAt,
|
||||
ip: request.ip,
|
||||
userAgent: request.headers['user-agent'] ?? ''
|
||||
});
|
||||
const accessToken = signAccessToken({
|
||||
sub: session.user.id,
|
||||
sid: session.id,
|
||||
tid: session.tenantId,
|
||||
aid: session.platformAppId,
|
||||
rv: session.user.roleVersion
|
||||
}, options.jwtSecret, options.accessTokenTtlSeconds);
|
||||
return {
|
||||
code: 0,
|
||||
data: {
|
||||
accessToken,
|
||||
expiresIn: options.accessTokenTtlSeconds,
|
||||
user: publicUser(session.user)
|
||||
},
|
||||
traceId: request.traceId
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof WechatApiError) {
|
||||
return reply.status(401).send({
|
||||
code: 'WECHAT_LOGIN_FAILED',
|
||||
message: 'WeChat login code is invalid or expired.',
|
||||
traceId: request.traceId
|
||||
});
|
||||
}
|
||||
if (error instanceof Error && error.message === 'TENANT_SELECTION_REQUIRED') {
|
||||
return reply.status(409).send({
|
||||
code: 'TENANT_SELECTION_REQUIRED',
|
||||
message: 'tenant-id is required for an application bound to multiple tenants.',
|
||||
traceId: request.traceId
|
||||
});
|
||||
}
|
||||
if (error instanceof Error && error.message === 'USER_DISABLED') {
|
||||
return reply.status(403).send({
|
||||
code: 'USER_DISABLED',
|
||||
message: 'The user account is disabled.',
|
||||
traceId: request.traceId
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/app-api/auth/me', async (request, reply) => {
|
||||
const auth = await authenticate(request.headers.authorization, options);
|
||||
if (!auth) return unauthorized(reply, request.traceId);
|
||||
return { code: 0, data: { user: publicUser(auth.user) }, traceId: request.traceId };
|
||||
});
|
||||
|
||||
app.post('/app-api/auth/logout', async (request, reply) => {
|
||||
const auth = await authenticate(request.headers.authorization, options);
|
||||
if (!auth) return unauthorized(reply, request.traceId);
|
||||
await options.repository.revokeSession(auth.sessionId);
|
||||
return { code: 0, data: { revoked: true }, traceId: request.traceId };
|
||||
});
|
||||
}
|
||||
|
||||
async function authenticate(authorization: string | undefined, options: AuthRouteOptions) {
|
||||
if (!authorization?.startsWith('Bearer ')) return null;
|
||||
try {
|
||||
const claims = verifyAccessToken(authorization.slice(7), options.jwtSecret);
|
||||
const session = await options.repository.validateSession(claims.sid, claims.tid, claims.sub);
|
||||
if (!session || session.platformAppId !== claims.aid || session.user.roleVersion !== claims.rv) {
|
||||
return null;
|
||||
}
|
||||
return { sessionId: claims.sid, user: session.user };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function unauthorized(reply: { status(code: number): { send(payload: unknown): unknown } }, traceId: string) {
|
||||
return reply.status(401).send({
|
||||
code: 'AUTH_SESSION_INVALID',
|
||||
message: 'The access token or server-side session is invalid.',
|
||||
traceId
|
||||
});
|
||||
}
|
||||
|
||||
function publicUser(user: {
|
||||
id: string;
|
||||
tenantId: string;
|
||||
userType: string;
|
||||
nickname: string;
|
||||
avatarUrl: string;
|
||||
phone: string;
|
||||
}) {
|
||||
return {
|
||||
id: user.id,
|
||||
tenantId: user.tenantId,
|
||||
userType: user.userType,
|
||||
nickname: user.nickname,
|
||||
avatarUrl: user.avatarUrl,
|
||||
phone: user.phone
|
||||
};
|
||||
}
|
||||
+10
-1
@@ -2,12 +2,21 @@ import { buildApp } from './app.js';
|
||||
import { loadConfig } from './config.js';
|
||||
import { closeMySqlPool, createMySqlPool } from './db/mysql.js';
|
||||
import { PlatformConfigRepository } from './tenancy/platform-config-repository.js';
|
||||
import { AuthRepository } from './auth/auth-repository.js';
|
||||
import { parseWechatAppSecrets, WechatHttpClient } from './auth/wechat-client.js';
|
||||
|
||||
const config = loadConfig();
|
||||
const pool = createMySqlPool(config);
|
||||
const app = await buildApp({
|
||||
config,
|
||||
platformConfigRepository: new PlatformConfigRepository(pool)
|
||||
platformConfigRepository: new PlatformConfigRepository(pool),
|
||||
auth: {
|
||||
repository: new AuthRepository(pool),
|
||||
wechat: new WechatHttpClient(parseWechatAppSecrets(config.auth.wechatAppSecretsJson)),
|
||||
jwtSecret: config.auth.jwtSecret,
|
||||
accessTokenTtlSeconds: config.auth.accessTokenTtlSeconds,
|
||||
sessionTtlSeconds: config.auth.sessionTtlSeconds
|
||||
}
|
||||
});
|
||||
app.addHook('onClose', async () => {
|
||||
await closeMySqlPool(pool);
|
||||
|
||||
Reference in New Issue
Block a user