feat(M03-D): 完成场景码NFC与受控WiFi
This commit is contained in:
@@ -0,0 +1,170 @@
|
||||
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 type { ManagementActor } from '../auth/user-management-repository.js';
|
||||
import {
|
||||
StoreAccessError,
|
||||
type StoreAccessRepository
|
||||
} from '../stores/access-repository.js';
|
||||
|
||||
const idSchema = z.object({ id: z.string().regex(/^[1-9]\d{0,19}$/) });
|
||||
const storeIdSchema = z.object({ storeId: z.string().regex(/^[1-9]\d{0,19}$/) });
|
||||
const sceneSchema = z.object({
|
||||
targetType: z.enum(['STORE', 'ROOM']),
|
||||
storeId: z.string().regex(/^[1-9]\d{0,19}$/),
|
||||
roomId: z.string().regex(/^[1-9]\d{0,19}$/).optional()
|
||||
}).refine((value) => value.targetType === 'STORE' || value.roomId !== undefined);
|
||||
const resolveSchema = z.object({
|
||||
code: z.string().trim().min(12).max(32),
|
||||
sourceType: z.enum(['QRCODE', 'NFC']).default('QRCODE')
|
||||
});
|
||||
|
||||
export interface StoreAccessRouteOptions {
|
||||
repository: Pick<StoreAccessRepository,
|
||||
'regenerateScene' | 'revokeScene' | 'resolveScene' | 'sceneStats' | 'getWifi'>;
|
||||
authRepository: Pick<AuthRepository, 'validateSession'>;
|
||||
accessControl: { getAccessProfile(tenantId: string, userId: string): Promise<AccessProfile> };
|
||||
jwtSecret: string;
|
||||
}
|
||||
|
||||
export async function registerStoreAccessRoutes(
|
||||
app: FastifyInstance, options: StoreAccessRouteOptions
|
||||
) {
|
||||
app.post('/admin-api/scene-codes/regenerate', async (request, reply) => {
|
||||
const actor = await requireManager(request, reply, options);
|
||||
const body = sceneSchema.safeParse(request.body);
|
||||
if (!actor || !body.success) return actor ? invalid(reply, request.traceId) : undefined;
|
||||
return handle(reply, request.traceId, async () => reply.status(201).send({
|
||||
code: 0,
|
||||
data: await options.repository.regenerateScene(actor, body.data),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
app.post('/admin-api/scene-codes/:id/revoke', async (request, reply) => {
|
||||
const actor = await requireManager(request, reply, options);
|
||||
const params = idSchema.safeParse(request.params);
|
||||
const query = storeIdSchema.safeParse(request.query);
|
||||
if (!actor || !params.success || !query.success) {
|
||||
return actor ? invalid(reply, request.traceId) : undefined;
|
||||
}
|
||||
return handle(reply, request.traceId, async () => ({
|
||||
code: 0,
|
||||
data: await options.repository.revokeScene(actor, params.data.id, query.data.storeId),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
app.get('/admin-api/stores/:storeId/scene-code-stats', async (request, reply) => {
|
||||
const actor = await requireManager(request, reply, options);
|
||||
const params = storeIdSchema.safeParse(request.params);
|
||||
if (!actor || !params.success) return actor ? invalid(reply, request.traceId) : undefined;
|
||||
return handle(reply, request.traceId, async () => ({
|
||||
code: 0,
|
||||
data: await options.repository.sceneStats(actor, params.data.storeId),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
app.post('/app-api/scenes/resolve', async (request, reply) => {
|
||||
const body = resolveSchema.safeParse(request.body);
|
||||
if (!body.success) return invalid(reply, request.traceId);
|
||||
return handle(reply, request.traceId, async () => ({
|
||||
code: 0,
|
||||
data: await options.repository.resolveScene({
|
||||
...body.data,
|
||||
traceId: request.traceId,
|
||||
ip: request.ip,
|
||||
userAgent: request.headers['user-agent'] ?? ''
|
||||
}),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
app.get('/app-api/stores/:storeId/wifi', async (request, reply) => {
|
||||
const auth = await authenticateAccessToken(
|
||||
request.headers.authorization, options.authRepository, options.jwtSecret
|
||||
);
|
||||
const params = storeIdSchema.safeParse(request.params);
|
||||
if (!auth) {
|
||||
return reply.status(401).send({
|
||||
code: 'AUTH_SESSION_INVALID', message: 'Authentication required.',
|
||||
traceId: request.traceId
|
||||
});
|
||||
}
|
||||
if (!params.success) return invalid(reply, request.traceId);
|
||||
const access = await options.accessControl.getAccessProfile(
|
||||
auth.session.tenantId, auth.session.user.id
|
||||
);
|
||||
return handle(reply, request.traceId, async () => ({
|
||||
code: 0,
|
||||
data: await options.repository.getWifi({
|
||||
tenantId: auth.session.tenantId,
|
||||
userId: auth.session.user.id,
|
||||
access,
|
||||
storeId: params.data.storeId,
|
||||
traceId: request.traceId,
|
||||
ip: request.ip,
|
||||
userAgent: request.headers['user-agent'] ?? ''
|
||||
}),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
async function requireManager(
|
||||
request: FastifyRequest, reply: FastifyReply, options: StoreAccessRouteOptions
|
||||
): 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: 'Authentication required.',
|
||||
traceId: request.traceId
|
||||
});
|
||||
return null;
|
||||
}
|
||||
const access = await options.accessControl.getAccessProfile(
|
||||
auth.session.tenantId, auth.session.user.id
|
||||
);
|
||||
if (!access.capabilities.some((item) =>
|
||||
item === 'store.operation.write' || item === 'tenant.manage'
|
||||
) && !access.roles.includes('PLATFORM_ADMIN')) {
|
||||
reply.status(403).send({
|
||||
code: 'SCENE_MANAGEMENT_FORBIDDEN',
|
||||
message: 'Store 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 handle(reply: FastifyReply, traceId: string, work: () => Promise<unknown>) {
|
||||
try {
|
||||
return await work();
|
||||
} catch (error) {
|
||||
if (!(error instanceof StoreAccessError)) throw error;
|
||||
const forbidden = error.code.endsWith('_FORBIDDEN');
|
||||
const notFound = error.code.endsWith('_NOT_FOUND') || error.code === 'SCENE_CODE_INVALID';
|
||||
return reply.status(forbidden ? 403 : notFound ? 404 : 400).send({
|
||||
code: error.code,
|
||||
message: 'The scene or Wi-Fi request is invalid or not allowed.',
|
||||
traceId
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function invalid(reply: FastifyReply, traceId: string) {
|
||||
return reply.status(400).send({
|
||||
code: 'INVALID_STORE_ACCESS_REQUEST',
|
||||
message: 'The scene or Wi-Fi request is invalid.',
|
||||
traceId
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user