使用Ember Simple Auth访问用户的帐户信息

Pet*_*own 5 ember.js ember-simple-auth

我在我的应用程序中使用了ember-simple-auth并且运行良好,但我希望能够在UI中显示当前用户的属性(例如电子邮件或名称).在过去,我使用了一个应用程序初始化程序来执行此操作,并且基本上使用currentUser注入所有控制器,但这需要在初始化应用程序时知道当前用户.由于我正在使用OAuth,因此在加载应用程序时不知道用户.

有没有办法从当前登录的用户获取属性?

Pet*_*own 7

事实证明,我使用的ember-simple-auth版本已经过时,需要升级到0.3.x(从0.2.x开始).从那里,我能够添加一个自定义验证器,我几乎直接从项目的示例文件中提取.请注意,我在Ember 1.6.0 beta 2上.

使用下面的代码,我可以使用this.get('session.currentUser')或使用模板访问路径和控制器中的currentUser {{session.currentUser}}.

我必须对API进行的唯一更改包括user_id使用OAuth响应.

从上一个答案更新为支持0.4.0

然后我将我的初始化程序更新为以下内容:

App.initializer({
  name: 'authentication',

  initialize: function(container, application) {
    Ember.SimpleAuth.Authenticators.OAuth2.reopen({
      serverTokenEndpoint: '/api/oauth/token'
    });

    Ember.SimpleAuth.Session.reopen({
      currentUser: function() {
        var userId = this.get('user_id');
        if (!Ember.isEmpty(userId)) {
          return container.lookup('store:main').find('current-user', userId);
        }
      }.property('user_id')
    });

    Ember.SimpleAuth.setup(container, application, {
      authorizerFactory: 'ember-simple-auth-authorizer:oauth2-bearer',
      routeAfterAuthentication: 'main.dashboard'
    });
  }
});
Run Code Online (Sandbox Code Playgroud)

我的登录控制器现在看起来像这样:

export default Ember.Controller.extend(Ember.SimpleAuth.LoginControllerMixin, {
  authenticatorFactory: 'ember-simple-auth-authenticator:oauth2-password-grant'
});
Run Code Online (Sandbox Code Playgroud)

  • 我发现从currentUser返回promise的一个微妙问题,当像session.get("currentUser")=== task.get("user")进行比较时,它将失败(即使一旦promise已经解决).也许我打算使用特定于余烬的平等检查?因为这个虽然我已经切换到在会话中使用观察者,当用户加载时设置currentUser即https://gist.github.com/opsb/d3754a4541a120c92cad (2认同)