nfp_sites/api/access/middleware.mjs

32 lines
875 B
JavaScript
Raw Normal View History

2019-09-14 19:03:38 +00:00
import orgAccess from './index.mjs'
2019-02-19 11:34:52 +00:00
export function accessChecks(opts = { }) {
const access = opts.access || orgAccess
return (ctx, next) => {
ctx.state.is = access.is.bind(access, ctx)
ctx.state.atLeast = access.atLeast.bind(access, ctx)
ctx.state.ensure = access.ensure.bind(access, ctx)
return next()
}
}
export function restrict(level = orgAccess.Normal) {
return async (ctx, next) => {
if (!ctx.headers.authorization) {
return ctx.throw(403, 'Authentication token was not found (did you forget to login?)')
}
2019-02-22 14:53:43 +00:00
if (!ctx.state.user || !ctx.state.user.email || !ctx.state.user.level) {
2019-02-19 11:34:52 +00:00
return ctx.throw(403, 'You must be authenticated to access this resource')
}
if (!ctx.state.atLeast(level)) {
return ctx.throw(403, 'You do not have enough access to access this resource')
}
return next()
}
}