Skip to content

Commit

Permalink
Auth middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
hagopj13 committed Oct 30, 2019
1 parent 9ba47b3 commit 6685442
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 3 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ It comes with many built-in features, such as authentication using JWT, request
- Latest ECMAScript features
- [Express](http://expressjs.com)
- [MongoDB](https://www.mongodb.com) object data modeling using [Mongoose](https://mongoosejs.com)
- Authentication using [passport](http://www.passportjs.org)
- Authentication using [passport](http://www.passportjs.org) and role-based authorization
- Request data validation using [Joi](https://github.com/hapijs/joi)
- Advanced production process management using [PM2](https://pm2.keymetrics.io)
- Dependency management with [Yarn](https://yarnpkg.com)
Expand Down
5 changes: 5 additions & 0 deletions src/config/roles.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
const roles = ['user', 'admin'];

const roleRights = new Map();
roleRights.set(roles[0], []);
roleRights.set(roles[1], ['getUsers', 'manageUsers']);

module.exports = {
roles,
roleRights,
};
2 changes: 1 addition & 1 deletion src/controllers/auth.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const { authService, userService } = require('../services');

const register = catchAsync(async (req, res) => {
const user = await userService.createUser(req.body);
const tokens = await authService.generateAuthTokens('5db5d97e287ebe4e58de5f28');
const tokens = await authService.generateAuthTokens(user.id);
const response = {
user: user.transform(),
tokens,
Expand Down
31 changes: 31 additions & 0 deletions src/middlewares/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const passport = require('passport');
const httpStatus = require('http-status');
const AppError = require('../utils/AppError');
const { roleRights } = require('../config/roles');

const verifyCallback = (req, resolve, reject, requiredRights) => async (err, user, info) => {
if (err || info || !user) {
return reject(new AppError(httpStatus.UNAUTHORIZED, 'Please authenticate'));
}
req.user = user;

if (requiredRights.length) {
const userRights = roleRights.get(user.role);
const hasRequiredRights = requiredRights.every(requiredRight => userRights.includes(requiredRight));
if (!hasRequiredRights && req.params.userId !== user.id) {
return reject(new AppError(httpStatus.FORBIDDEN, 'Forbidden'));
}
}

resolve();
};

const auth = (...requiredRights) => async (req, res, next) => {
return new Promise((resolve, reject) => {
passport.authenticate('jwt', { session: false }, verifyCallback(req, resolve, reject, requiredRights))(req, res, next);
})
.then(() => next())
.catch(err => next(err));
};

module.exports = auth;
3 changes: 2 additions & 1 deletion src/routes/v1/user.route.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
const express = require('express');
const auth = require('../../middlewares/auth');
const validate = require('../../middlewares/validate');
const userValidation = require('../../validations/user.validation');
const userController = require('../../controllers/user.controller');

const router = express.Router();

router.route('/').post(validate(userValidation.createUser), userController.createUser);
router.route('/').post(auth('manageUsers'), validate(userValidation.createUser), userController.createUser);

module.exports = router;

0 comments on commit 6685442

Please sign in to comment.