NodeJS ExpressJS PassportJS - for administrative pages only

Im using NodeJS, ExpressJS, Mongoose, passportJS and connect-provide-login. User authentication works fine.

.... var passport = require('passport') , LocalStrategy = require('passport-local').Strategy , ensureLoggedIn = require('connect-ensure-login').ensureLoggedIn; var app = express(); ... app.use(passport.initialize()); app.use(passport.session()); ... passport.use(new LocalStrategy({usernameField: 'email', passwordField: 'password'}, function(email, password, done) { User.findOne({ 'email': email, 'password': password }, {'_id': 1, 'email':1}, function(err, user) { if (err) { return done(err); } if (!user) { return done(null, false, { message: 'Incorrect username.' }); } return done(null, user); }); })); passport.serializeUser(function(user, done) { done(null, user); }); passport.deserializeUser(function(user, done) { done(null, user); }); app.post('/login', passport.authenticate('local', { successReturnToOrRedirect: '/home', failureRedirect: '/login' })); app.get('/logout', function(req, res){ req.logout(); res.redirect('/'); }); 

Now I want to add restrictions on some routes so that they are accessible only to the administrator. How can i do this? e.g. /admin/*

 var schema = new mongoose.Schema({ name: String, email: String, password: String, isAdmin: { type: Boolean, default: false } }); mongoose.model('User', schema); 

Any hint? Thanks

+4
source share
2 answers

You can connect special middleware to the route /admin/* , which will check the status of the administrator before sending a request to any of the more specific routes /admin/ :

 var ensureLoggedIn = require('connect-ensure-login').ensureLoggedIn; ... var requiresAdmin = function() { return [ ensureLoggedIn('/login'), function(req, res, next) { if (req.user && req.user.isAdmin === true) next(); else res.send(401, 'Unauthorized'); } ] }; app.all('/admin/*', requiresAdmin()); app.get('/admin/', ...); 
+11
source
 //Add following function to your app.js above **app.use(app.router)** call; //This function will be called every time when the server receive request. app.use(function (req, res, next) { if (req.isAuthenticated || req.isAuthenticated()) { var currentUrl = req.originalUrl || req.url; //Check wheather req.user has access to the above URL //If req.user don't have access then redirect the user // to home page or login page res.redirect('HOME PAGE URL'); } next(); }); 

I have not tried it, but I think it will work.

-1
source

Source: https://habr.com/ru/post/1487211/


All Articles