mirror of
https://github.com/sasjs/server.git
synced 2026-01-05 05:40:06 +00:00
feat: add authorize middleware for validating permissions
This commit is contained in:
34
api/src/middlewares/authorize.ts
Normal file
34
api/src/middlewares/authorize.ts
Normal file
@@ -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)
|
||||
}
|
||||
Reference in New Issue
Block a user