我使用ember simple auth使用ember制作自定义auth系统,一切正常,期待一个问题,无法将数据从authenticate promise回调传递给登录控制器。
以下代码:
//the login goes here
authenticate: function(options) {
return new Ember.RSVP.Promise(function(resolve, reject) {
Ember.$.ajax({
type: "POST",
url: apis.login,
data: JSON.stringify({
username: options.identification,
password: options.password
})
}).then(function(response) {
// check the login status to check the status
if (response.status === "success") {
//pass the response in resolve callback
Ember.run(function() {
resolve(response);
});
} else {
//login failed, pass the response in reject callback
Ember.run(function() {
reject(response);
});
}
}, function(xhr, status, error) {
Ember.run(function() {
reject(xhr.responseJSON || xhr.responseText);
});
});
});
},
和控制器代码
actions: {
// display an error when authentication fails
authenticate: function() {
var _this = this;
var credentials = this.getProperties('identification', 'password');
this.get('session').authenticate('authenticator:custom', credentials).then(
function(message) {
//the issus happens here, the message here is undefined
console.log(message);
_this.get('session').set('username', message.username);
}, function(message) {
// but the reject callback works fine, the message is the right one
console.log(message);
_this.set('errorMessage', message.msg);
_this.set('identification', '');
_this.set('password', '');
});
}
}
有人可以帮助我吗?
答案 0 :(得分:1)
会话的authenticate
解析后没有任何价值,因为@damienc指出。但是,您可以通过会话的secure
属性访问身份验证器解析的所有内容,例如this.get('session.secure.token')
。因此,您只需将代码更改为
actions: {
authenticate: function() {
var _this = this;
var credentials = this.getProperties('identification', 'password');
this.get('session').authenticate('authenticator:custom', credentials).then(
function() {
//the issus happens here, the message here is undefined
console.log(_this.get('session.secure.whatever'));
_this.get('session').set('username', message.username);
}, function(error) {
// but the reject callback works fine, the message is the right one
console.log(error);
_this.set('errorMessage', error.msg);
_this.set('identification', '');
_this.set('password', '');
});
}
}
答案 1 :(得分:0)
Session
将身份验证委派给Authenticator
(authenticate
,restore
...),但始终会解决返回无值的问题。
这意味着在您的Controller
示例中,已解析的承诺将永远不会有任何参数。
this.get('session')
.authenticate('authenticator:custom', credentials)
.then(function(/* there are parameters here, see session implementation */) {
_this.get('session').set('username', message.username);
}, function(message) {
/* */
});
这清楚地检查Session
源代码:https://github.com/simplabs/ember-simple-auth/blob/master/packages/ember-simple-auth/lib/simple-auth/session.js#L158
您可以使用自定义Session
对象并覆盖authenticate
方法,让它返回您需要的值。