如何使用 ember-simple-auth 在会话中存储用户 ID?

How to store the user id in session with ember-simple-auth?

我想在会话中存储用户标识。我在自定义身份验证器中有此身份验证方法:

authenticate: (credentials) ->
  _this = this
  new (Ember.RSVP.Promise) (resolve, reject) ->
    Ember.$.ajax(
      url: 'http://localhost:3000/api/v1/sessions'
      type: 'POST'
      data: session:
        email: credentials.identification
        password: credentials.password
    ).then ((response) ->
      _this.set('user_id', response.user_id)
      Ember.run ->
        resolve token: response.token
    ), (xhr, status, error) ->
      response = JSON.parse(xhr.responseText)
      Ember.run ->
        reject response.error

这是咖啡脚本,但它的工作方式与 javascript 相似。如您所愿,我在会话中设置了 'user_id'。

app/initializers/custom-session 中,我有这个 :

import Ember from "ember";
import Session from "simple-auth/session";

export default {
  name: "current-user",
  before: "simple-auth",
  initialize: function(container) {
    Session.reopen({
      setCurrentUser: function() {
        return this.get('user_id')
      }.observes('secure.access_token')
    });
  }
};

user_id 总是 returns undefined。我在网上找了很多解决办法都没有用。

有没有简单的解决方案?

您正在 authenticator (_this.set('user_id', response.user_id)) 而不是 session 上设置 user_iduser_id 应该传递给 authenticator 中的 resolve 方法。这样您的用户 ID 就可以通过 session.

中的 secure.user_id 访问