简体   繁体   中英

User groups with Passport, Node.js

Looking for some pointers here.

I want to create a page with a login form as the landing page and when you log in you will be taken to your own dashboard. However if you log in with an as a user with admin rights they will be taken to an admin dashboard.

What is the best way to achieve that? Just have some middleware that checks if they are an admin?

Thanks Miles

login.js file :

var findUser = function(req, res, next) {
    var user = User.find({email:req.body.email},function(err,user){
     if (!user) {
        res.locals.error = 'No such account exists.'
        return res.render('frontend/login')
    }
    next()
    });
}

var authenticate = function(req, res, next) {

  passport.authenticate('local', function(err, user, info) {
            if (err || !user) {
                console.log('ATUH ERROR');
                            console.log(err , user,info)
                res.locals.error = 'Invalid login credentials provided.'
                return res.render('frontend/login')
            }
            req.logIn(user, function(err2) {
                if (err2) {
                    console.log('LOGIN TIME ERROR')
                    res.locals.error = 'Internal system error while logging in.'
                    return res.render('frontend/login')
                }
                console.log('user redirect');
                if(user.role=='user'){
                  res.redirect('/user/dashboard');
                }

                if(user.role=='admin'){
                  res.redirect('/admin/dashboard');
                }

            })
  })(req, res, next)
}


module.exports = [findUser, authenticate]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM