scaffolds RenderFields, moves Init into Routes

This commit is contained in:
James
2020-01-19 15:04:31 -05:00
parent a1494e62b0
commit b6231925bc
26 changed files with 350 additions and 235 deletions

View File

@@ -1,23 +0,0 @@
const HttpStatus = require('http-status');
/**
* authorize a request by comparing the current user with one or more roles
* @param roles
* @returns {Function}
*/
const checkRoleMiddleware = (...roles) => {
return (req, res, next) => {
if (!req.user) {
res.status(HttpStatus.UNAUTHORIZED)
.send('Not Authorized');
} else if (!roles.some(role => role === req.user.role)) {
res.status(HttpStatus.FORBIDDEN)
.send('Role not authorized.');
} else {
next();
}
};
};
module.exports = checkRoleMiddleware;

View File

@@ -13,9 +13,13 @@ export const loadPolicy = (policy) => {
passport.authenticate(['jwt', 'anonymous'], { session: false }),
(req, res, next) => {
if (policy) {
policy(req, res, next);
} else {
requireAuth(req, res);
if (!policy(req.user)) {
return res.status(HttpStatus.FORBIDDEN)
.send('Role not authorized.');
}
return next();
}
requireAuth(req, res);
}];
};

View File

@@ -17,8 +17,8 @@ export default User => ({
const error = new APIError('Authentication error', httpStatus.UNAUTHORIZED);
return next(error);
}
passport.authenticate('local')(req, res, () => {
res.json({ email: user.email, role: user.role, createdAt: user.createdAt });
return passport.authenticate('local')(req, res, () => {
return res.json({ email: user.email, role: user.role, createdAt: user.createdAt });
});
});
},
@@ -35,7 +35,7 @@ export default User => ({
User.findByUsername(email, (err, user) => {
if (err || !user) return res.status(401).json({ message: 'Auth Failed' });
user.authenticate(password, (authErr, model, passwordError) => {
return user.authenticate(password, (authErr, model, passwordError) => {
if (authErr || passwordError) return res.status(401).json({ message: 'Auth Failed' });
const opts = {};
@@ -73,6 +73,6 @@ export default User => ({
next(error);
}
next();
return next();
},
});

View File

@@ -2,7 +2,6 @@ import express from 'express';
import passport from 'passport';
import authRequestHandlers from './requestHandlers';
import authValidate from './validate';
import checkRoleMiddleware from './checkRoleMiddleware';
import passwordResetRoutes from './passwordResets/routes';
const router = express.Router();
@@ -17,12 +16,6 @@ const authRoutes = (userConfig, User) => {
.route('/me')
.post(passport.authenticate(userConfig.auth.strategy, { session: false }), auth.me);
userConfig.roles.forEach((role) => {
router
.route(`/role/${role}`)
.get(passport.authenticate(userConfig.auth.strategy, { session: false }), checkRoleMiddleware(role), auth.me);
});
if (userConfig.auth.passwordResets) {
router.use('', passwordResetRoutes(userConfig.email, User));
}