Ember.js 如何在会话中存储用户
我试图使用django rest framework后端设置ember simple auth,但在将用户保存到会话时遇到了一些问题。我必须能够在我的模板中执行以下操作:Ember.js 如何在会话中存储用户,ember.js,django-rest-framework,ember-simple-auth,Ember.js,Django Rest Framework,Ember Simple Auth,我试图使用django rest framework后端设置ember simple auth,但在将用户保存到会话时遇到了一些问题。我必须能够在我的模板中执行以下操作: <h2>Welcome back, {{session.user}}</h2> 然后我修改了Application.initializer以提供sessionauser属性: Ember.Application.initializer({ name: 'authentication',
<h2>Welcome back, {{session.user}}</h2>
然后我修改了Application.initializer
以提供session
auser
属性:
Ember.Application.initializer({
name: 'authentication',
before: 'simple-auth',
initialize: function(container, application) {
// register the custom authenticator and authorizer so Ember Simple Auth can find them
container.register('authenticator:custom', App.CustomAuthenticator);
container.register('authorizer:custom', App.CustomAuthorizer);
SimpleAuth.Session.reopen({
user: function() {
var username = this.get('username');
if (!Ember.isEmpty(username)) {
return container.lookup('store:main').find('user', {username: username});
}
}.property('username')
});
}
});
但是,当呈现{{session.user.username}
时,它只是一个空字符串。我的问题是:
User
对象,那么如何解析它呢在0.6.4版本中,您现在可以指定自定义会话类,而无需重新打开,请参阅此处的发行说明:。这就是它的工作原理:
App.CustomSession = SimpleAuth.Session.extend({
account: function() {
var accountId = this.get('account_id');
if (!Ember.isEmpty(accountId)) {
return this.container.lookup('store:main').find('account', accountId);
}
}.property('account_id')
});
…
container.register('session:custom', App.CustomSession);
…
window.ENV['simple-auth'] = {
session: 'session:custom',
}
要标记@Marcow的响应,以下是如何在Ember CLI中实现它: index.html:
window.ENV['simple-auth'] = {
authorizer: 'simple-auth-authorizer:devise',
session: 'session:withCurrentUser'
};
初始化者/customize-session.js:
import Session from 'simple-auth/session';
var SessionWithCurrentUser = Session.extend({
currentUser: function() {
var userId = this.get('user_id');
if (!Ember.isEmpty(userId)) {
return this.container.lookup('store:main').find('user', userId);
}
}.property('user_id')
});
export default {
name: 'customize-session',
initialize: function(container) {
container.register('session:withCurrentUser', SessionWithCurrentUser);
}
};
现在,这才是真正的方法。在下一个版本的Ember Simple Auth中,这将变得更容易,因为您可以指定自己的会话类,而不必再重新打开现有会话。好的,那么我如何获得实际的
用户
呢?请查看repo中的示例,它完全符合您的要求:我已经看过了-这就是我的想法来源。然而,在这个例子中,find
被赋予了一个id。在我的例子中,它用于搜索,即.find('user',{username:username})
。这应该是一样的-只会导致对REST API的两个不同请求。唯一不同的是,.find
可能返回一个数组,而示例中带有id的.find
直接返回记录。不过这只是一个假设-没有尝试过。感谢您提供最终实现。我也有同样的情况。非常感谢。这可能对今天有所帮助:
import Session from 'simple-auth/session';
var SessionWithCurrentUser = Session.extend({
currentUser: function() {
var userId = this.get('user_id');
if (!Ember.isEmpty(userId)) {
return this.container.lookup('store:main').find('user', userId);
}
}.property('user_id')
});
export default {
name: 'customize-session',
initialize: function(container) {
container.register('session:withCurrentUser', SessionWithCurrentUser);
}
};