2023-09-05 01:24:20 +08:00
|
|
|
import { Handler } from 'express';
|
2023-09-06 14:14:12 +08:00
|
|
|
import { getWorkspaceUser } from '../model/workspace';
|
2023-09-26 14:45:28 +08:00
|
|
|
import { ROLES } from '../utils/const';
|
2023-09-05 01:24:20 +08:00
|
|
|
|
2023-09-26 14:45:28 +08:00
|
|
|
export function workspacePermission(roles: ROLES[] = []): Handler {
|
2023-09-05 01:24:20 +08:00
|
|
|
return async (req, res, next) => {
|
2023-09-05 15:32:16 +08:00
|
|
|
const workspaceId =
|
|
|
|
req.body.workspaceId ?? req.query.workspaceId ?? req.params.workspaceId;
|
2023-09-05 01:24:20 +08:00
|
|
|
|
|
|
|
if (!workspaceId) {
|
|
|
|
throw new Error('Cannot find workspace id');
|
|
|
|
}
|
|
|
|
|
|
|
|
const userId = req.user!.id;
|
|
|
|
|
|
|
|
if (!userId) {
|
|
|
|
throw new Error('This middleware should be use after auth()');
|
|
|
|
}
|
|
|
|
|
2023-09-06 14:14:12 +08:00
|
|
|
const info = await getWorkspaceUser(workspaceId, userId);
|
2023-09-05 01:24:20 +08:00
|
|
|
|
2023-09-06 14:14:12 +08:00
|
|
|
if (!info) {
|
2023-09-05 01:24:20 +08:00
|
|
|
throw new Error('Is not workspace user');
|
|
|
|
}
|
|
|
|
|
2023-09-06 14:14:12 +08:00
|
|
|
if (Array.isArray(roles) && roles.length > 0) {
|
2023-09-26 14:45:28 +08:00
|
|
|
if (!roles.includes(info.role as ROLES)) {
|
2023-09-06 14:14:12 +08:00
|
|
|
throw new Error(
|
|
|
|
`Workspace roles not has this permission, need ${roles}`
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-05 01:24:20 +08:00
|
|
|
next();
|
|
|
|
};
|
|
|
|
}
|