277 lines
9.2 KiB
TypeScript
277 lines
9.2 KiB
TypeScript
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 IGNORE INTO qipai_roles (tenant_id, code, name) VALUES
|
|
(?, 'CUSTOMER', '顾客'),
|
|
(?, 'CLEANER', '保洁员'),
|
|
(?, 'STAFF', '门店员工'),
|
|
(?, 'STORE_ADMIN', '门店管理员'),
|
|
(?, 'TENANT_ADMIN', '租户管理员'),
|
|
(?, 'PLATFORM_ADMIN', '平台管理员')`,
|
|
Array(6).fill(input.context.tenantId)
|
|
);
|
|
await connection.execute(
|
|
`INSERT IGNORE INTO qipai_user_roles (tenant_id, user_id, role_id)
|
|
SELECT ?, ?, id FROM qipai_roles
|
|
WHERE tenant_id = ? AND code = 'CUSTOMER' AND status = 'ACTIVE'`,
|
|
[input.context.tenantId, user.id, input.context.tenantId]
|
|
);
|
|
await connection.execute(
|
|
`INSERT IGNORE INTO qipai_role_permissions (tenant_id, role_id, permission_id)
|
|
SELECT ?, r.id, p.id FROM qipai_roles r
|
|
INNER JOIN qipai_permissions p ON
|
|
(r.code = 'CUSTOMER' AND p.code IN ('profile.read', 'order.self.read'))
|
|
OR (r.code = 'STORE_ADMIN'
|
|
AND p.code IN ('user.read', 'staff.manage', 'session.reset',
|
|
'store.operation.read', 'store.operation.write'))
|
|
OR (r.code IN ('TENANT_ADMIN', 'PLATFORM_ADMIN')
|
|
AND p.code IN ('user.read', 'staff.manage', 'session.reset', 'tenant.manage'))
|
|
WHERE r.tenant_id = ?`,
|
|
[input.context.tenantId, input.context.tenantId]
|
|
);
|
|
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
|
|
};
|
|
}
|