feat: add workspace middleware

This commit is contained in:
moonrailgun 2023-09-05 01:24:20 +08:00
parent bd7a5776c3
commit af96679e0b
2 changed files with 31 additions and 20 deletions

View File

@ -0,0 +1,26 @@
import { Handler } from 'express';
import { checkIsWorkspaceUser } from '../model/workspace';
export function workspacePermission(): Handler {
return async (req, res, next) => {
const workspaceId = req.body.workspaceId ?? req.query.workspaceId;
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()');
}
const isWorkspaceUser = await checkIsWorkspaceUser(workspaceId, userId);
if (!isWorkspaceUser) {
throw new Error('Is not workspace user');
}
next();
};
}

View File

@ -1,11 +1,8 @@
import { Router } from 'express'; import { Router } from 'express';
import { auth } from '../middleware/auth'; import { auth } from '../middleware/auth';
import { body, param, query, validate } from '../middleware/validate'; import { body, query, validate } from '../middleware/validate';
import { import { workspacePermission } from '../middleware/workspace';
addWorkspaceWebsite, import { addWorkspaceWebsite, getWorkspaceWebsites } from '../model/workspace';
checkIsWorkspaceUser,
getWorkspaceWebsites,
} from '../model/workspace';
export const workspaceRouter = Router(); export const workspaceRouter = Router();
@ -19,16 +16,10 @@ workspaceRouter.get(
.withMessage('workspaceId should be UUID') .withMessage('workspaceId should be UUID')
), ),
auth(), auth(),
workspacePermission(),
async (req, res) => { async (req, res) => {
const userId = req.user!.id;
const workspaceId = req.query.workspaceId as string; const workspaceId = req.query.workspaceId as string;
const isWorkspaceUser = await checkIsWorkspaceUser(workspaceId, userId);
if (!isWorkspaceUser) {
throw new Error('Is not workspace user');
}
const websites = await getWorkspaceWebsites(workspaceId); const websites = await getWorkspaceWebsites(workspaceId);
res.json({ websites }); res.json({ websites });
@ -47,16 +38,10 @@ workspaceRouter.post(
body('domain').isURL().withMessage('domain should be URL') body('domain').isURL().withMessage('domain should be URL')
), ),
auth(), auth(),
workspacePermission(),
async (req, res) => { async (req, res) => {
const userId = req.user!.id;
const { workspaceId, name, domain } = req.body; const { workspaceId, name, domain } = req.body;
const isWorkspaceUser = await checkIsWorkspaceUser(workspaceId, userId);
if (!isWorkspaceUser) {
throw new Error('Is not workspace user');
}
const website = await addWorkspaceWebsite(workspaceId, name, domain); const website = await addWorkspaceWebsite(workspaceId, name, domain);
res.json({ website }); res.json({ website });