feat(M04-D): 完成最小权限订单分享
This commit is contained in:
@@ -0,0 +1,120 @@
|
||||
import type { FastifyInstance, FastifyReply } 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 {
|
||||
OrderShareError, type OrderShareRepository
|
||||
} from '../orders/order-share-repository.js';
|
||||
|
||||
const orderParams = z.object({ orderId: z.string().regex(/^[1-9]\d{0,19}$/) });
|
||||
const revokeParams = orderParams.extend({ shareId: z.string().regex(/^[1-9]\d{0,19}$/) });
|
||||
const tokenParams = z.object({ token: z.string().min(40).max(64) });
|
||||
const createSchema = z.object({
|
||||
permissions: z.array(z.enum(['VIEW_ROOM', 'OPEN_DOOR', 'RENEW'])).min(1).max(3)
|
||||
.optional(),
|
||||
ttlMinutes: z.number().int().min(5).max(1440).optional()
|
||||
}).strict();
|
||||
const resolveSchema = z.object({
|
||||
permission: z.enum(['VIEW_ROOM', 'OPEN_DOOR', 'RENEW'])
|
||||
}).strict();
|
||||
|
||||
export interface OrderShareRouteOptions {
|
||||
repository: Pick<OrderShareRepository, 'create' | 'revoke' | 'resolve'>;
|
||||
authRepository: Pick<AuthRepository, 'validateSession'>;
|
||||
accessControl: { getAccessProfile(tenantId: string, userId: string): Promise<AccessProfile> };
|
||||
jwtSecret: string;
|
||||
}
|
||||
|
||||
export async function registerOrderShareRoutes(
|
||||
app: FastifyInstance, options: OrderShareRouteOptions
|
||||
) {
|
||||
app.post('/app-api/orders/:orderId/shares', async (request, reply) => {
|
||||
const auth = await authenticate(request.headers.authorization, options);
|
||||
const params = orderParams.safeParse(request.params);
|
||||
const body = createSchema.safeParse(request.body ?? {});
|
||||
if (!auth) return unauthorized(reply, request.traceId);
|
||||
if (!params.success || !body.success) return invalid(reply, request.traceId);
|
||||
return handle(reply, request.traceId, async () => reply.status(201).send({
|
||||
code: 0,
|
||||
data: await options.repository.create({
|
||||
tenantId: auth.tenantId, userId: auth.userId, orderId: params.data.orderId,
|
||||
access: auth.access, permissions: body.data.permissions,
|
||||
ttlMinutes: body.data.ttlMinutes, traceId: request.traceId,
|
||||
ip: request.ip, userAgent: request.headers['user-agent'] ?? ''
|
||||
}),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
|
||||
app.delete('/app-api/orders/:orderId/shares/:shareId', async (request, reply) => {
|
||||
const auth = await authenticate(request.headers.authorization, options);
|
||||
const params = revokeParams.safeParse(request.params);
|
||||
if (!auth) return unauthorized(reply, request.traceId);
|
||||
if (!params.success) return invalid(reply, request.traceId);
|
||||
return handle(reply, request.traceId, async () => ({
|
||||
code: 0,
|
||||
data: await options.repository.revoke({
|
||||
tenantId: auth.tenantId, userId: auth.userId,
|
||||
orderId: params.data.orderId, shareId: params.data.shareId,
|
||||
access: auth.access, traceId: request.traceId, ip: request.ip,
|
||||
userAgent: request.headers['user-agent'] ?? ''
|
||||
}),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
|
||||
app.post('/app-api/order-shares/:token/resolve', async (request, reply) => {
|
||||
const params = tokenParams.safeParse(request.params);
|
||||
const body = resolveSchema.safeParse(request.body);
|
||||
if (!params.success || !body.success) return invalid(reply, request.traceId);
|
||||
return handle(reply, request.traceId, async () => ({
|
||||
code: 0,
|
||||
data: await options.repository.resolve(params.data.token, body.data.permission, {
|
||||
traceId: request.traceId, ip: request.ip,
|
||||
userAgent: request.headers['user-agent'] ?? ''
|
||||
}),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
async function authenticate(
|
||||
authorization: string | undefined, options: OrderShareRouteOptions
|
||||
) {
|
||||
const result = await authenticateAccessToken(
|
||||
authorization, options.authRepository, options.jwtSecret
|
||||
);
|
||||
if (!result) return null;
|
||||
const tenantId = result.session.tenantId;
|
||||
const userId = result.session.user.id;
|
||||
return {
|
||||
tenantId, userId,
|
||||
access: await options.accessControl.getAccessProfile(tenantId, userId)
|
||||
};
|
||||
}
|
||||
|
||||
async function handle(reply: FastifyReply, traceId: string, work: () => Promise<unknown>) {
|
||||
try {
|
||||
return await work();
|
||||
} catch (error) {
|
||||
if (!(error instanceof OrderShareError)) throw error;
|
||||
const status = error.code === 'ORDER_NOT_FOUND' || error.code === 'ORDER_SHARE_NOT_FOUND'
|
||||
? 404 : error.code === 'ORDER_SHARE_PERMISSION_DENIED' ? 403 : 400;
|
||||
return reply.status(status).send({
|
||||
code: error.code, message: 'The order share is not available.', traceId
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function unauthorized(reply: FastifyReply, traceId: string) {
|
||||
return reply.status(401).send({
|
||||
code: 'AUTH_SESSION_INVALID', message: 'Authentication required.', traceId
|
||||
});
|
||||
}
|
||||
|
||||
function invalid(reply: FastifyReply, traceId: string) {
|
||||
return reply.status(400).send({
|
||||
code: 'INVALID_ORDER_SHARE_REQUEST', message: 'The share request is invalid.', traceId
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user