feat(M02-B): 实现微信登录与可撤销会话
This commit is contained in:
@@ -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];
|
||||
})
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user