feat(M02-D): 完成用户与员工权限管理

This commit is contained in:
Codex
2026-06-18 14:45:01 +08:00
parent 46acb8422a
commit 5a300a82f6
21 changed files with 894 additions and 40 deletions
+8
View File
@@ -9,11 +9,16 @@ import {
type PlatformConfigResolver
} from './routes/platform-bootstrap.js';
import { registerAuthRoutes, type AuthRouteOptions } from './routes/auth.js';
import {
registerUserManagementRoutes,
type UserManagementRouteOptions
} from './routes/user-management.js';
export interface BuildAppOptions {
config?: AppConfig;
platformConfigRepository?: PlatformConfigResolver;
auth?: AuthRouteOptions;
userManagement?: UserManagementRouteOptions;
}
declare module 'fastify' {
@@ -62,6 +67,9 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
if (options.auth) {
await registerAuthRoutes(app, options.auth);
}
if (options.userManagement) {
await registerUserManagementRoutes(app, options.userManagement);
}
return app;
}
+8 -2
View File
@@ -138,8 +138,14 @@ export class AuthRepository {
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 p.code IN ('profile.read', 'order.self.read')
WHERE r.tenant_id = ? AND r.code = 'CUSTOMER'`,
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(
+25
View File
@@ -0,0 +1,25 @@
import type { AuthRepository, AuthSession } from './auth-repository.js';
import { verifyAccessToken } from './jwt.js';
export interface AuthenticatedRequest {
sessionId: string;
session: AuthSession;
}
export async function authenticateAccessToken(
authorization: string | undefined,
repository: Pick<AuthRepository, 'validateSession'>,
jwtSecret: string
): Promise<AuthenticatedRequest | null> {
if (!authorization?.startsWith('Bearer ')) return null;
try {
const claims = verifyAccessToken(authorization.slice(7), jwtSecret);
const session = await 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, session };
} catch {
return null;
}
}
+9 -4
View File
@@ -33,10 +33,15 @@ export class RbacRepository {
);
await this.pool.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 p.code IN ('profile.read', 'order.self.read')
WHERE r.tenant_id = ? AND r.code = 'CUSTOMER'`,
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 = ?`,
[tenantId, tenantId]
);
}
@@ -0,0 +1,347 @@
import type { PoolConnection, ResultSetHeader, RowDataPacket } from 'mysql2/promise';
import type { MySqlPool } from '../db/mysql.js';
import type { AccessProfile } from './rbac-repository.js';
const assignableRoles = ['CLEANER', 'STAFF', 'STORE_ADMIN', 'TENANT_ADMIN'] as const;
export type AssignableRole = typeof assignableRoles[number];
export interface ManagedUser {
id: string;
userType: string;
status: string;
nickname: string;
maskedPhone: string;
maskedLastIp: string;
note: string;
roles: string[];
storeIds: string[];
registeredAt: Date;
lastLoginAt: Date | null;
}
export interface ManagementActor {
tenantId: string;
userId: string;
access: AccessProfile;
traceId: string;
ip: string;
userAgent: string;
}
export interface UserMutation {
nickname?: string;
phone?: string;
note?: string;
status?: 'ACTIVE' | 'DISABLED';
roles?: AssignableRole[];
storeIds?: string[];
}
interface UserRow extends RowDataPacket {
id: string;
userType: string;
status: string;
nickname: string;
phone: string;
lastIp: string | null;
note: string;
registeredAt: Date;
lastLoginAt: Date | null;
}
interface CountRow extends RowDataPacket { total: number }
interface CodeRow extends RowDataPacket { code: string }
interface IdRow extends RowDataPacket { id: string }
export class UserManagementError extends Error {
constructor(public readonly code: string) {
super(code);
}
}
export class UserManagementRepository {
constructor(private readonly pool: MySqlPool) {}
async listUsers(input: {
actor: ManagementActor;
page: number;
pageSize: number;
status?: 'ACTIVE' | 'DISABLED';
search?: string;
}): Promise<{ items: ManagedUser[]; total: number }> {
const filters = ['u.tenant_id = ?', 'u.deleted_at IS NULL'];
const params: Array<string | number> = [input.actor.tenantId];
if (input.status) {
filters.push('u.status = ?');
params.push(input.status);
}
if (input.search) {
filters.push('(u.nickname LIKE ? OR u.phone LIKE ? OR CAST(u.id AS CHAR) = ?)');
const like = `%${input.search}%`;
params.push(like, like, input.search);
}
const scope = this.scopeClause(input.actor, 'u.id');
filters.push(scope.sql);
params.push(...scope.params);
const [counts] = await this.pool.execute<CountRow[]>(
`SELECT COUNT(DISTINCT u.id) AS total FROM qipai_users u
WHERE ${filters.join(' AND ')}`,
params
);
const [rows] = await this.pool.execute<UserRow[]>(
`SELECT u.id, u.user_type AS userType, u.status, u.nickname, u.phone,
u.created_at AS registeredAt, u.last_login_at AS lastLoginAt,
COALESCE(p.note, '') AS note,
(SELECT s.ip FROM qipai_auth_sessions s
WHERE s.tenant_id = u.tenant_id AND s.user_id = u.id
ORDER BY s.created_at DESC LIMIT 1) AS lastIp
FROM qipai_users u
LEFT JOIN qipai_user_admin_profiles p
ON p.tenant_id = u.tenant_id AND p.user_id = u.id
WHERE ${filters.join(' AND ')}
ORDER BY u.id DESC LIMIT ? OFFSET ?`,
[...params, input.pageSize, (input.page - 1) * input.pageSize]
);
const items = await Promise.all(rows.map(async (row) => ({
id: String(row.id),
userType: row.userType,
status: row.status,
nickname: row.nickname,
maskedPhone: maskPhone(row.phone),
maskedLastIp: maskIp(row.lastIp ?? ''),
note: row.note,
roles: await this.getCodes('role', input.actor.tenantId, String(row.id)),
storeIds: await this.getCodes('store', input.actor.tenantId, String(row.id)),
registeredAt: row.registeredAt,
lastLoginAt: row.lastLoginAt
})));
return { items, total: Number(counts[0]?.total ?? 0) };
}
async createStaff(actor: ManagementActor, input: Required<Pick<UserMutation, 'nickname' | 'phone'>> & UserMutation) {
return this.inTransaction(async (connection) => {
this.assertMutationAllowed(actor, input.roles ?? ['STAFF'], input.storeIds ?? []);
const [created] = await connection.execute<ResultSetHeader>(
`INSERT INTO qipai_users (tenant_id, user_type, status, nickname, phone)
VALUES (?, 'STAFF', 'ACTIVE', ?, ?)`,
[actor.tenantId, input.nickname, input.phone]
);
const userId = String(created.insertId);
await this.applyMutation(connection, actor, userId, {
...input,
roles: input.roles ?? ['STAFF'],
storeIds: input.storeIds ?? []
}, 'STAFF_CREATED');
return { userId };
});
}
async updateUser(actor: ManagementActor, userId: string, input: UserMutation) {
return this.inTransaction(async (connection) => {
await this.lockManageableUser(connection, actor, userId);
this.assertMutationAllowed(actor, input.roles ?? [], input.storeIds ?? []);
await this.applyMutation(connection, actor, userId, input, 'USER_UPDATED');
return { userId };
});
}
async resetSessions(actor: ManagementActor, userId: string) {
return this.inTransaction(async (connection) => {
await this.lockManageableUser(connection, actor, userId);
const [result] = await connection.execute<ResultSetHeader>(
`UPDATE qipai_auth_sessions SET status = 'REVOKED', revoked_at = UTC_TIMESTAMP(3),
revoke_reason = 'ADMIN_RESET'
WHERE tenant_id = ? AND user_id = ? AND status = 'ACTIVE'`,
[actor.tenantId, userId]
);
await connection.execute(
`UPDATE qipai_users SET role_version = role_version + 1
WHERE tenant_id = ? AND id = ?`,
[actor.tenantId, userId]
);
await this.audit(connection, actor, 'USER_SESSIONS_RESET', userId, {
revokedSessions: result.affectedRows
});
return { userId, revokedSessions: result.affectedRows };
});
}
private async applyMutation(
connection: PoolConnection,
actor: ManagementActor,
userId: string,
input: UserMutation,
action: string
) {
if (input.nickname !== undefined || input.phone !== undefined || input.status !== undefined) {
await connection.execute(
`UPDATE qipai_users SET
nickname = COALESCE(?, nickname),
phone = COALESCE(?, phone),
status = COALESCE(?, status),
role_version = role_version + 1
WHERE tenant_id = ? AND id = ? AND deleted_at IS NULL`,
[input.nickname ?? null, input.phone ?? null, input.status ?? null, actor.tenantId, userId]
);
}
if (input.note !== undefined) {
await connection.execute(
`INSERT INTO qipai_user_admin_profiles (tenant_id, user_id, note, updated_by)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE note = VALUES(note), updated_by = VALUES(updated_by)`,
[actor.tenantId, userId, input.note, actor.userId]
);
}
if (input.roles !== undefined) {
await connection.execute(
'DELETE FROM qipai_user_roles WHERE tenant_id = ? AND user_id = ?',
[actor.tenantId, userId]
);
for (const role of input.roles) {
const [result] = await connection.execute<ResultSetHeader>(
`INSERT INTO qipai_user_roles (tenant_id, user_id, role_id)
SELECT ?, ?, id FROM qipai_roles
WHERE tenant_id = ? AND code = ? AND status = 'ACTIVE' AND deleted_at IS NULL`,
[actor.tenantId, userId, actor.tenantId, role]
);
if (result.affectedRows !== 1) throw new UserManagementError('ROLE_NOT_FOUND');
}
await connection.execute(
`UPDATE qipai_users SET role_version = role_version + 1
WHERE tenant_id = ? AND id = ?`,
[actor.tenantId, userId]
);
}
if (input.storeIds !== undefined) {
await connection.execute(
'DELETE FROM qipai_user_store_scopes WHERE tenant_id = ? AND user_id = ?',
[actor.tenantId, userId]
);
for (const storeId of input.storeIds) {
const [result] = await connection.execute<ResultSetHeader>(
`INSERT INTO qipai_user_store_scopes (tenant_id, user_id, store_id, scope_type)
SELECT ?, ?, id, 'STAFF' FROM qipai_stores
WHERE tenant_id = ? AND id = ? AND deleted_at IS NULL`,
[actor.tenantId, userId, actor.tenantId, storeId]
);
if (result.affectedRows !== 1) throw new UserManagementError('STORE_NOT_FOUND');
}
}
if (input.status === 'DISABLED' || input.roles !== undefined || input.storeIds !== undefined) {
await connection.execute(
`UPDATE qipai_auth_sessions SET status = 'REVOKED', revoked_at = UTC_TIMESTAMP(3),
revoke_reason = 'ACCESS_CHANGED'
WHERE tenant_id = ? AND user_id = ? AND status = 'ACTIVE'`,
[actor.tenantId, userId]
);
}
await this.audit(connection, actor, action, userId, {
status: input.status,
roles: input.roles,
storeIds: input.storeIds,
noteChanged: input.note !== undefined
});
}
private assertMutationAllowed(actor: ManagementActor, roles: readonly string[], storeIds: readonly string[]) {
const isTenantAdmin = actor.access.capabilities.includes('tenant.manage')
|| actor.access.roles.includes('PLATFORM_ADMIN');
if (!isTenantAdmin && roles.some((role) => role === 'TENANT_ADMIN' || role === 'PLATFORM_ADMIN')) {
throw new UserManagementError('ROLE_ASSIGNMENT_FORBIDDEN');
}
if (!isTenantAdmin && storeIds.some((storeId) => !actor.access.storeIds.includes(storeId))) {
throw new UserManagementError('STORE_SCOPE_FORBIDDEN');
}
if (roles.some((role) => !assignableRoles.includes(role as AssignableRole))) {
throw new UserManagementError('ROLE_ASSIGNMENT_FORBIDDEN');
}
}
private async lockManageableUser(connection: PoolConnection, actor: ManagementActor, userId: string) {
const scope = this.scopeClause(actor, 'u.id');
const [rows] = await connection.execute<IdRow[]>(
`SELECT u.id FROM qipai_users u
WHERE u.tenant_id = ? AND u.id = ? AND u.deleted_at IS NULL
AND ${scope.sql} FOR UPDATE`,
[actor.tenantId, userId, ...scope.params]
);
if (!rows[0]) throw new UserManagementError('USER_NOT_MANAGEABLE');
if (userId === actor.userId) throw new UserManagementError('SELF_ACCESS_CHANGE_FORBIDDEN');
}
private scopeClause(actor: ManagementActor, userExpression: string) {
if (actor.access.capabilities.includes('tenant.manage') || actor.access.roles.includes('PLATFORM_ADMIN')) {
return { sql: '1 = 1', params: [] as string[] };
}
if (!actor.access.capabilities.includes('staff.manage')) {
return { sql: '1 = 0', params: [] as string[] };
}
if (actor.access.storeIds.length === 0) return { sql: '1 = 0', params: [] as string[] };
return {
sql: `EXISTS (
SELECT 1 FROM qipai_user_store_scopes ms
WHERE ms.tenant_id = u.tenant_id AND ms.user_id = ${userExpression}
AND ms.store_id IN (${actor.access.storeIds.map(() => '?').join(',')})
)`,
params: actor.access.storeIds
};
}
private async getCodes(type: 'role' | 'store', tenantId: string, userId: string): Promise<string[]> {
const sql = type === 'role'
? `SELECT r.code FROM qipai_user_roles ur
INNER JOIN qipai_roles r ON r.id = ur.role_id AND r.tenant_id = ur.tenant_id
WHERE ur.tenant_id = ? AND ur.user_id = ? ORDER BY r.code`
: `SELECT CAST(store_id AS CHAR) AS code FROM qipai_user_store_scopes
WHERE tenant_id = ? AND user_id = ? ORDER BY store_id`;
const [rows] = await this.pool.execute<CodeRow[]>(sql, [tenantId, userId]);
return rows.map((row) => row.code);
}
private async audit(
connection: PoolConnection,
actor: ManagementActor,
action: string,
userId: string,
metadata: object
) {
await connection.execute(
`INSERT INTO qipai_audit_logs
(tenant_id, actor_type, actor_id, action, resource_type, resource_id,
trace_id, ip, user_agent, metadata)
VALUES (?, 'USER', ?, ?, 'USER', ?, ?, ?, ?, ?)`,
[
actor.tenantId, actor.userId, action, userId, actor.traceId,
actor.ip, actor.userAgent.slice(0, 255), JSON.stringify(metadata)
]
);
}
private async inTransaction<T>(work: (connection: PoolConnection) => Promise<T>): Promise<T> {
const connection = await this.pool.getConnection();
try {
await connection.beginTransaction();
const result = await work(connection);
await connection.commit();
return result;
} catch (error) {
await connection.rollback();
throw error;
} finally {
connection.release();
}
}
}
export function maskPhone(phone: string): string {
if (!phone) return '';
if (phone.length < 7) return `${phone.slice(0, 2)}***`;
return `${phone.slice(0, 3)}****${phone.slice(-4)}`;
}
export function maskIp(ip: string): string {
if (!ip) return '';
if (ip.includes(':')) return `${ip.split(':').slice(0, 2).join(':')}:****`;
const parts = ip.split('.');
return parts.length === 4 ? `${parts[0]}.${parts[1]}.*.*` : '***';
}
+13 -3
View File
@@ -25,16 +25,19 @@ const migrationFiles: Record<MigrationDirection, readonly string[]> = {
'database/migrations/2026061802_m01c_async_tasks.up.sql',
'database/migrations/2026061803_m02a_tenant_apps.up.sql',
'database/migrations/2026061804_m02b_wechat_auth.up.sql',
'database/migrations/2026061805_m02c_rbac.up.sql'
'database/migrations/2026061805_m02c_rbac.up.sql',
'database/migrations/2026061806_m02d_user_management.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/2026061804_m02b_wechat_auth.verify.sql',
'database/migrations/2026061805_m02c_rbac.verify.sql'
'database/migrations/2026061805_m02c_rbac.verify.sql',
'database/migrations/2026061806_m02d_user_management.verify.sql'
],
down: [
'database/migrations/2026061806_m02d_user_management.down.sql',
'database/migrations/2026061805_m02c_rbac.down.sql',
'database/migrations/2026061804_m02b_wechat_auth.down.sql',
'database/migrations/2026061803_m02a_tenant_apps.down.sql',
@@ -155,7 +158,14 @@ 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, 3, 7, 1, 5, 3, 7, 1][index] ?? 1;
const minimumRows = [
10, 26, 1,
2, 5, 1,
3, 5, 1,
3, 7, 1,
5, 3, 7, 1,
1, 3, 1
][index] ?? 1;
if (!Array.isArray(result) || result.length < minimumRows) {
throw new Error(
`Migration verification statement ${index + 1} returned fewer than ${minimumRows} rows.`
+10 -19
View File
@@ -2,7 +2,8 @@ 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 { authenticateAccessToken } from '../auth/authenticate.js';
import { signAccessToken } from '../auth/jwt.js';
import { WechatApiError, type WechatCodeExchange } from '../auth/wechat-client.js';
import type { AccessProfile } from '../auth/rbac-repository.js';
@@ -100,40 +101,30 @@ export async function registerAuthRoutes(app: FastifyInstance, options: AuthRout
});
app.get('/app-api/auth/me', async (request, reply) => {
const auth = await authenticate(request.headers.authorization, options);
const auth = await authenticateAccessToken(
request.headers.authorization, options.repository, options.jwtSecret
);
if (!auth) return unauthorized(reply, request.traceId);
const access = options.accessControl
? await options.accessControl.getAccessProfile(auth.user.tenantId, auth.user.id)
? await options.accessControl.getAccessProfile(auth.session.user.tenantId, auth.session.user.id)
: { roles: [], capabilities: [], storeIds: [] };
return {
code: 0,
data: { user: publicUser(auth.user), access },
data: { user: publicUser(auth.session.user), access },
traceId: request.traceId
};
});
app.post('/app-api/auth/logout', async (request, reply) => {
const auth = await authenticate(request.headers.authorization, options);
const auth = await authenticateAccessToken(
request.headers.authorization, options.repository, options.jwtSecret
);
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',
+159
View File
@@ -0,0 +1,159 @@
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
import { z } from 'zod';
import type { AuthRepository } from '../auth/auth-repository.js';
import { authenticateAccessToken } from '../auth/authenticate.js';
import type { AccessProfile } from '../auth/rbac-repository.js';
import {
UserManagementError,
type AssignableRole,
type ManagementActor,
type UserManagementRepository
} from '../auth/user-management-repository.js';
const idSchema = z.object({ id: z.string().regex(/^[1-9]\d{0,19}$/) });
const rolesSchema = z.array(z.enum(['CLEANER', 'STAFF', 'STORE_ADMIN', 'TENANT_ADMIN'])).max(4);
const storesSchema = z.array(z.string().regex(/^[1-9]\d{0,19}$/)).max(100);
const createSchema = z.object({
nickname: z.string().trim().min(1).max(128),
phone: z.string().trim().regex(/^\+?[0-9]{6,20}$/),
note: z.string().trim().max(1000).default(''),
roles: rolesSchema.default(['STAFF']),
storeIds: storesSchema.default([])
});
const updateSchema = z.object({
nickname: z.string().trim().min(1).max(128).optional(),
phone: z.string().trim().regex(/^\+?[0-9]{6,20}$/).optional(),
note: z.string().trim().max(1000).optional(),
status: z.enum(['ACTIVE', 'DISABLED']).optional(),
roles: rolesSchema.optional(),
storeIds: storesSchema.optional()
}).refine((value) => Object.keys(value).length > 0);
const listSchema = z.object({
page: z.coerce.number().int().min(1).default(1),
pageSize: z.coerce.number().int().min(1).max(100).default(20),
status: z.enum(['ACTIVE', 'DISABLED']).optional(),
search: z.string().trim().max(128).optional()
});
export interface UserManagementRouteOptions {
repository: Pick<UserManagementRepository, 'listUsers' | 'createStaff' | 'updateUser' | 'resetSessions'>;
authRepository: Pick<AuthRepository, 'validateSession'>;
accessControl: { getAccessProfile(tenantId: string, userId: string): Promise<AccessProfile> };
jwtSecret: string;
}
export async function registerUserManagementRoutes(
app: FastifyInstance,
options: UserManagementRouteOptions
): Promise<void> {
app.get('/admin-api/users', async (request, reply) => {
const actor = await requireManager(request, reply, options);
if (!actor) return;
const query = listSchema.safeParse(request.query);
if (!query.success) return invalid(reply, request.traceId);
const data = await options.repository.listUsers({ actor, ...query.data });
return { code: 0, data, traceId: request.traceId };
});
app.post('/admin-api/staff', async (request, reply) => {
const actor = await requireManager(request, reply, options);
if (!actor) return;
const body = createSchema.safeParse(request.body);
if (!body.success) return invalid(reply, request.traceId);
return handleMutation(reply, request.traceId, async () => {
const data = await options.repository.createStaff(actor, {
...body.data,
roles: body.data.roles as AssignableRole[]
});
return reply.status(201).send({ code: 0, data, traceId: request.traceId });
});
});
app.patch('/admin-api/users/:id', async (request, reply) => {
const actor = await requireManager(request, reply, options);
if (!actor) return;
const params = idSchema.safeParse(request.params);
const body = updateSchema.safeParse(request.body);
if (!params.success || !body.success) return invalid(reply, request.traceId);
return handleMutation(reply, request.traceId, async () => {
const data = await options.repository.updateUser(actor, params.data.id, {
...body.data,
roles: body.data.roles as AssignableRole[] | undefined
});
return { code: 0, data, traceId: request.traceId };
});
});
app.post('/admin-api/users/:id/reset-sessions', async (request, reply) => {
const actor = await requireManager(request, reply, options);
if (!actor) return;
const params = idSchema.safeParse(request.params);
if (!params.success) return invalid(reply, request.traceId);
return handleMutation(reply, request.traceId, async () => ({
code: 0,
data: await options.repository.resetSessions(actor, params.data.id),
traceId: request.traceId
}));
});
}
async function requireManager(
request: FastifyRequest,
reply: FastifyReply,
options: UserManagementRouteOptions
): Promise<ManagementActor | null> {
const auth = await authenticateAccessToken(
request.headers.authorization,
options.authRepository,
options.jwtSecret
);
if (!auth) {
reply.status(401).send({
code: 'AUTH_SESSION_INVALID', message: 'The access token or session is invalid.',
traceId: request.traceId
});
return null;
}
const access = await options.accessControl.getAccessProfile(
auth.session.tenantId,
auth.session.user.id
);
if (!access.capabilities.some((code) => code === 'staff.manage' || code === 'tenant.manage')
&& !access.roles.includes('PLATFORM_ADMIN')) {
reply.status(403).send({
code: 'STAFF_MANAGEMENT_FORBIDDEN', message: 'Staff management permission is required.',
traceId: request.traceId
});
return null;
}
return {
tenantId: auth.session.tenantId,
userId: auth.session.user.id,
access,
traceId: request.traceId,
ip: request.ip,
userAgent: request.headers['user-agent'] ?? ''
};
}
async function handleMutation(reply: FastifyReply, traceId: string, work: () => Promise<unknown>) {
try {
return await work();
} catch (error) {
if (!(error instanceof UserManagementError)) throw error;
const forbidden = error.code.endsWith('_FORBIDDEN') || error.code === 'USER_NOT_MANAGEABLE';
return reply.status(forbidden ? 403 : 404).send({
code: error.code,
message: 'The requested user, role or store assignment is not allowed.',
traceId
});
}
}
function invalid(reply: FastifyReply, traceId: string) {
return reply.status(400).send({
code: 'INVALID_USER_MANAGEMENT_REQUEST',
message: 'The user management request is invalid.',
traceId
});
}
+11 -2
View File
@@ -5,19 +5,28 @@ import { PlatformConfigRepository } from './tenancy/platform-config-repository.j
import { AuthRepository } from './auth/auth-repository.js';
import { RbacRepository } from './auth/rbac-repository.js';
import { parseWechatAppSecrets, WechatHttpClient } from './auth/wechat-client.js';
import { UserManagementRepository } from './auth/user-management-repository.js';
const config = loadConfig();
const pool = createMySqlPool(config);
const authRepository = new AuthRepository(pool);
const accessControl = new RbacRepository(pool);
const app = await buildApp({
config,
platformConfigRepository: new PlatformConfigRepository(pool),
auth: {
repository: new AuthRepository(pool),
repository: authRepository,
wechat: new WechatHttpClient(parseWechatAppSecrets(config.auth.wechatAppSecretsJson)),
jwtSecret: config.auth.jwtSecret,
accessTokenTtlSeconds: config.auth.accessTokenTtlSeconds,
sessionTtlSeconds: config.auth.sessionTtlSeconds,
accessControl: new RbacRepository(pool)
accessControl
},
userManagement: {
repository: new UserManagementRepository(pool),
authRepository,
accessControl,
jwtSecret: config.auth.jwtSecret
}
});
app.addHook('onClose', async () => {