diff --git a/api/src/middlewares/authenticateToken.ts b/api/src/middlewares/authenticateToken.ts index 90c7027..23d5d0a 100644 --- a/api/src/middlewares/authenticateToken.ts +++ b/api/src/middlewares/authenticateToken.ts @@ -3,6 +3,7 @@ import jwt from 'jsonwebtoken' import { csrfProtection } from '../app' import { fetchLatestAutoExec, ModeType, verifyTokenInDB } from '../utils' import { desktopUser } from './desktop' +import { authorize } from './authorize' export const authenticateAccessToken: RequestHandler = async ( req, @@ -24,7 +25,7 @@ export const authenticateAccessToken: RequestHandler = async ( if (user) { if (user.isActive) { req.user = user - return csrfProtection(req, res, next) + return csrfProtection(req, res, () => authorize(req, res, next)) } else return res.sendStatus(401) } } @@ -34,7 +35,7 @@ export const authenticateAccessToken: RequestHandler = async ( authenticateToken( req, res, - next, + () => authorize(req, res, next), process.env.ACCESS_TOKEN_SECRET as string, 'accessToken' ) diff --git a/api/src/middlewares/authorize.ts b/api/src/middlewares/authorize.ts new file mode 100644 index 0000000..004b7f7 --- /dev/null +++ b/api/src/middlewares/authorize.ts @@ -0,0 +1,34 @@ +import { RequestHandler } from 'express' +import User from '../model/User' +import Permission from '../model/Permission' +import { PermissionSetting } from '../controllers/permission' + +export const authorize: RequestHandler = async (req, res, next) => { + let permission + const user = req.user + if (user) { + // no need to check for permissions when user is admin + if (user.isAdmin) return next() + + const dbUser = await User.findOne({ id: user.userId }) + if (!dbUser) return res.sendStatus(401) + + const uri = req.baseUrl + req.path + + // find permission w.r.t user + permission = await Permission.findOne({ uri, user: dbUser._id }) + + if (permission && permission.setting === PermissionSetting.grant) + return next() + + // find permission w.r.t user's groups + for (const group of dbUser.groups) { + permission = await Permission.findOne({ uri, group }) + if (permission && permission.setting === PermissionSetting.grant) + return next() + } + + return res.sendStatus(401) + } + return res.sendStatus(401) +} diff --git a/api/src/middlewares/index.ts b/api/src/middlewares/index.ts index 7798de3..8e64643 100644 --- a/api/src/middlewares/index.ts +++ b/api/src/middlewares/index.ts @@ -2,3 +2,4 @@ export * from './authenticateToken' export * from './desktop' export * from './verifyAdmin' export * from './verifyAdminIfNeeded' +export * from './authorize'