如何使用本地护照JS将用户重定向到Express JS的不同页面?

时间:2019-02-21 00:41:28

标签: node.js express passport.js passport-local

我正在一个有三个公司(即compA,CompB,compC)的项目中工作。 每个公司都有自己的用户。 这是我的用户架构,可以将用户与特定公司关联

<script>

export default {
 name: "Login",
 data: function(){
   return {
     isLoggedIn: this.$authentication // remove the attribute
   }
 },
 watch: {
  'isLoggedIn.authenticated': function (){  // now access the attribute
    console.log('its working');  
  }
 },
}
</script>

我唯一关心的是如何根据用户所关联的公司将用户重定向到特定页面。

现在我正在使用此代码作为登录名,连续登录后,它会转到“添加”页面。有什么办法可以将特定登录用户重定向到特定页面?

    const UserSchema = new Schema({
        name:{
            type: String,
            required: true
        },
        company:{
            type: String,
            required: true
        },
        password:{
            type: String,
            required: true
        },
        role:{
            type: String
        }, 
        date:{
            type: Date,
            default: Date.now
        }   
    })

const User = mongoose.model('users', UserSchema)

2 个答案:

答案 0 :(得分:0)

我认为您的问题有两种方式。

  1. 不使用护照,并在site_config.js中写入重定向网址
site_config['url_base_on_company'] = {'a'=>'www.a.com','b':'www.b.com'};
const site_config = require('site_config');
User.findOne({where,'attributes': ['id','company']}.then(user=>{
    if(!user){
    // redirect relogin page
    //return
    }
    //session
    redirect(site_config[user['company']]);
});
  1. 使用护照,并在您的/ideas/add页面中,要求site_config并重定向。但这对数据库不利。在第一个想法中,您只能访问一次db,但是第二个想法应该访问两次。当然,session(像redis这样保存在内存中)可能比db更好地获得user'company。

答案 1 :(得分:0)

验证码就像

 passport.authenticate('local',function (err, user, info) { 
     if(err){
      res.redirect('/login')
     } else{
      if (! user) {
        res.redirect('/login')
      } else{
        req.login(user, function(err){
          if(err){
            res.redirect('/login')
          }else{

                 if(user.company == 'company1'){
                   res.redirect('url for company1')
                    }
                if(user.company == 'company2'){
                   res.redirect('url for company2')
                    }

          }
        })
      }
     }
  })(req, res);