在 Meteor 中模拟用户

Impersonate user in Meteor

我已经在我的 Meteor 应用程序中构建了模拟方法,以便以另一个用户身份登录,基于以下文章:https://dweldon.silvrback.com/impersonating-a-user。我还有 Intercom 集成(聊天小部件和用户跟踪)。我希望能够在客户端禁用该 Intercom 小部件,以避免在我作为另一个用户(模拟)登录时从 Intercom 应用程序进行任何跟踪。当我为任何用户触发该模拟方法时,我正在考虑在用户配置文件上创建模拟布尔值 属性,并将其更新为 true。问题是,我不知道如何在模拟方法完成后将其设置为 false。根据文章,您可以在手动刷新浏览器时停止模拟。你能帮我找到最好的方法吗?

我们可以分两部分解决这个问题:

当我们开始模拟用户时,请跟踪谁在模拟谁。让我们首先扩展教程中的 impersonate 方法:

Meteor.methods({
  impersonate: function(userId) {
    check(userId, String);

    if (!Meteor.users.findOne(userId))
      throw new Meteor.Error(404, 'User not found');
    if (!Meteor.user().isAdmin)
      throw new Meteor.Error(403, 'Permission denied');

    Meteor.users.update(this.userId, { $set: { 'profile.impersonating': userId }});
    this.setUserId(userId);

  }
});

接下来我们需要监听新的登录(这应该在浏览器刷新时发生)

Meteor.onLogin(() => {
  Meteor.call('clearImpersonation', (err, result) => {
    if (err) console.log('Error clearing impersonation: ',err);
  });
});

Meteor.methods({
  clearImpersonation(){
    const user = Meteor.users.findOne(this.userId);
    if (user && user.profile && user.profile.impersonating) Meteor.users.update(user._id,{ $unset: 'profile.impersonating' });
    return;
  }
});

现在,在您的 UI 中,您可以通过检查是否存在 Meteor.user().profile.impersonating

来禁用对讲机