diff --git a/src/server/middleware/workspace.ts b/src/server/middleware/workspace.ts new file mode 100644 index 0000000..634d928 --- /dev/null +++ b/src/server/middleware/workspace.ts @@ -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(); + }; +} diff --git a/src/server/router/workspace.ts b/src/server/router/workspace.ts index 3e42450..1311dfe 100644 --- a/src/server/router/workspace.ts +++ b/src/server/router/workspace.ts @@ -1,11 +1,8 @@ import { Router } from 'express'; import { auth } from '../middleware/auth'; -import { body, param, query, validate } from '../middleware/validate'; -import { - addWorkspaceWebsite, - checkIsWorkspaceUser, - getWorkspaceWebsites, -} from '../model/workspace'; +import { body, query, validate } from '../middleware/validate'; +import { workspacePermission } from '../middleware/workspace'; +import { addWorkspaceWebsite, getWorkspaceWebsites } from '../model/workspace'; export const workspaceRouter = Router(); @@ -19,16 +16,10 @@ workspaceRouter.get( .withMessage('workspaceId should be UUID') ), auth(), + workspacePermission(), async (req, res) => { - const userId = req.user!.id; 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); res.json({ websites }); @@ -47,16 +38,10 @@ workspaceRouter.post( body('domain').isURL().withMessage('domain should be URL') ), auth(), + workspacePermission(), async (req, res) => { - const userId = req.user!.id; 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); res.json({ website });