2015-04-25 20:58:39 +08:00
|
|
|
import mixin from 'flarum/utils/mixin';
|
|
|
|
import evented from 'flarum/utils/evented';
|
|
|
|
|
|
|
|
export default class Session extends mixin(class {}, evented) {
|
|
|
|
constructor() {
|
|
|
|
super();
|
|
|
|
this.user = m.prop();
|
|
|
|
this.token = m.prop();
|
|
|
|
}
|
|
|
|
|
|
|
|
login(identification, password) {
|
|
|
|
var deferred = m.deferred();
|
|
|
|
var self = this;
|
|
|
|
m.request({
|
|
|
|
method: 'POST',
|
2015-07-07 13:59:21 +08:00
|
|
|
url: app.forum.attribute('baseUrl')+'/login',
|
2015-04-25 20:58:39 +08:00
|
|
|
data: {identification, password},
|
|
|
|
background: true
|
|
|
|
}).then(function(response) {
|
|
|
|
self.token(response.token);
|
|
|
|
m.startComputation();
|
|
|
|
app.store.find('users', response.userId).then(function(user) {
|
|
|
|
self.user(user);
|
|
|
|
deferred.resolve(user);
|
|
|
|
self.trigger('loggedIn', user);
|
|
|
|
m.endComputation();
|
|
|
|
});
|
|
|
|
}, function(response) {
|
|
|
|
deferred.reject(response);
|
|
|
|
});
|
|
|
|
return deferred.promise;
|
|
|
|
}
|
|
|
|
|
|
|
|
logout() {
|
2015-07-07 13:59:21 +08:00
|
|
|
window.location = app.forum.attribute('baseUrl')+'/logout?token='+this.token();
|
2015-04-25 20:58:39 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
authorize(xhr) {
|
|
|
|
xhr.setRequestHeader('Authorization', 'Token '+this.token());
|
|
|
|
}
|
|
|
|
}
|