Reputation: 151
How to implement role based authorization / access control in nodejs using expressjs and passport also how to design Role Middleware perfectly ?
I have two types of login Admin and User
which is best, creating two model and router in the name of admin and user?
1.Checking user isAdmin
or not
2.
// To authtenticate the User by JWT Startegy
module.exports = (userType, passport) => {
let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt');
opts.secretOrKey = config.secret;
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
if (userType == 'admin') {
Admin.getAdminById(jwt_payload.data._id, (err, user) => {
if (err) return done(err, false);
if (user) return done(null, user);
return done(null, false);
});
}
if (userType == 'users') {
User.getUserById(jwt_payload.data._id, (err, user) => {
if (err) return done(err, false);
if (user) return done(null, user);
return done(null, false);
});
}
}));
}
Upvotes: 0
Views: 1413
Reputation: 2815
Why do you want to have 2 places to get user data?
Have users and assign roles to them.
The easiest access control system is: guest, logged in, admin.
So in table users
add a role
column with values: user, admin.
And now you write middlewares:
const isLogged = function (req, res, next) {
if (req.user)
return next ();
res.send ('unauth')
}
const isAdmin = function (req, res, next) {
if (req.user.role == 'admin')
return next ();
res.send ('only admin')
}
And usage:
app.get('/', (req, res)=>{})
app.get('/profile',isLogged, (req, res)=>{})
app.get('/admin',isLogged, isAdmin, (req, res)=>{})
For more advanced needs try find some ACL modules
Upvotes: 3