passportjs 中如何在 req.user 上定义 getCompany?

How is getCompany defined on req.user in passportjs?

我只是在这里浏览模型代码。我在路由文件中看到以下某些内容(可以找到代码行 HERE):

router.get('/departments/', function(req, res){
  // Add JS that is specific only to current page
  res.locals.custom_java_script.push('/js/departments.js');

  var company_for_template,
    model = req.app.get('db_model');

  req.user.getCompany({
    scope : ['with_active_users', 'order_by_active_users'],
  })
  .then(function(company){
    company_for_template = company;
    return company.getDepartments({
      scope : ['with_simple_users', 'with_boss'],
      order : [[ model.Department.default_order_field() ]],
    });
  })
  .then(function(departments){
    res.render('departments_overview', {
      title             : 'Departments settings',
      departments       : departments,
      allowance_options : generate_all_department_allowances(),
      company           : company_for_template,
    });
  });
});

我不明白的是一行代码 I.E. req.user.getCompany。附加到 user 对象的 getCompany 方法在哪里。我有点模糊的理解。我将在下面列出我的理解。

所以基本上我相信 passport.js 附加了用户对象,但是 getCompany 附加到用户对象的位置和方式究竟是什么?

我唯一的部分线索是这个答案 HERE I.E. the deserializeUser, when i see that i only see the below (code can be found HERE,在 repo 上。):

passport.deserializeUser(function(id, done) {

    model.User.find({where : {id : id}}).then(function(user){
      return user.reload_with_session_details();
    })
    .then(function(user){
      done(null, user);
    })
    .catch(function(error){
      console.error('Failed to fetch session user '+id+' with error: '+error);

      done(null, false, { message : 'Failed to fetch session user' });
    });
  });

从这里开始,我有点迷失了线索。非常感谢任何有关 getCompany 方法附加位置和方式的建议。

timeoff-management 库使用 Sequelize 作为 User 模型,如果您查看此处 https://github.com/timeoff-management/timeoff-management-application/blob/master/lib/model/db/user.js#L561User 模型与Company 型号。

当在两个模型之间定义关联时,Sequelize 将创建几个在实例上可用的 mixins。

使用 as 选项,这些混合将在 User 实例上生成。 (还会生成一些复数形式,但我无法确认。)

userInstance.getCompany()
userInstance.countCompany()
userInstance.hasCompany()
userInstance.setCompany()
userInstance.addCompany()
userInstance.removeCompany()
userInstance.createCompany()

有关 Sequelize mixins 的更多详细信息,请在此处查看 https://sequelize.org/v6/manual/assocs.html#special-methods-mixins-added-to-instances