framework/js/lib/Session.js

82 lines
1.9 KiB
JavaScript
Raw Normal View History

2015-04-25 20:58:39 +08:00
import mixin from 'flarum/utils/mixin';
import evented from 'flarum/utils/evented';
/**
* The `Session` class defines the current user session. It stores a reference
* to the current authenticated user, and provides methods to log in/out.
*
* @extends evented
*/
2015-04-25 20:58:39 +08:00
export default class Session extends mixin(class {}, evented) {
constructor(token, user) {
2015-04-25 20:58:39 +08:00
super();
/**
* The current authenticated user.
*
* @type {User|null}
* @public
*/
this.user = user;
/**
* The token that was used for authentication.
*
* @type {String|null}
*/
this.token = token;
2015-04-25 20:58:39 +08:00
}
/**
* Attempt to log in a user.
*
* @param {String} identification The username/email.
* @param {String} password
* @return {Promise}
*/
2015-04-25 20:58:39 +08:00
login(identification, password) {
const deferred = m.deferred();
app.request({
2015-04-25 20:58:39 +08:00
method: 'POST',
url: app.forum.attribute('baseUrl') + '/login',
data: {identification, password}
}).then(
// FIXME: reload the page on success. Somehow serialize what the user's
// intention was, and then perform that intention after the page reloads.
response => {
this.token = response.token;
app.store.find('users', response.userId).then(user => {
this.user = user;
this.trigger('loggedIn', user);
deferred.resolve(user);
});
},
response => {
deferred.reject(response);
}
);
2015-04-25 20:58:39 +08:00
return deferred.promise;
}
/**
* Log the user out.
*/
2015-04-25 20:58:39 +08:00
logout() {
window.location = app.forum.attribute('baseUrl') + '/logout?token=' + this.token;
2015-04-25 20:58:39 +08:00
}
/**
* Apply an authorization header with the current token to the given
* XMLHttpRequest object.
*
* @param {XMLHttpRequest} xhr
*/
2015-04-25 20:58:39 +08:00
authorize(xhr) {
xhr.setRequestHeader('Authorization', 'Token ' + this.token);
2015-04-25 20:58:39 +08:00
}
}