Skip to content

Instantly share code, notes, and snippets.

@jordanell
Last active April 30, 2019 20:34
Show Gist options
  • Save jordanell/91360ba8c14a1bec5992a39d0c37dcbb to your computer and use it in GitHub Desktop.
Save jordanell/91360ba8c14a1bec5992a39d0c37dcbb to your computer and use it in GitHub Desktop.
Express authorization middleware
import { isEmpty } from 'lodash';
import {
ForbiddenError,
NotFoundError,
} from 'src/errors';
import models from 'src/models';
const defaultBlacklist = [];
export default (model, operation) => {
// Ensure the model exists
if (!models[model]) {
throw new NotFoundError(`authorizeModel: Model not found: ${model}`);
}
// Ensure authorizers exist for this model
let authorizer = models[model].authorizer;
if (!authorizer) {
throw new NotFoundError(`Missing authorizer for model: ${model}`);
}
// Ensure this authorizer operation exists
authorizer = authorizer[operation];
if (!authorizer) {
throw new NotFoundError(`Missing authorizer: ${model}[${operation}]`);
}
return async (req, res, next) => {
const isAuthorized = await authorizer(req.currentUser, req.instance);
return isAuthorized
? next()
: next(new ForbiddenError());
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment