framework/js/lib/Session.js
Toby Zerner 26a821e3e2 Improve client XHR error handling
The default XHR error handler produce an alert which is appropriate to the response status code. It can be overridden per-request (by specifying the `errorHandler` option) so that the alert can be suppressed or displayed in a different position (e.g. inside a modal).

ref #118
2015-10-20 12:48:26 +10:30

64 lines
1.4 KiB
JavaScript

/**
* The `Session` class defines the current user session. It stores a reference
* to the current authenticated user, and provides methods to log in/out.
*/
export default class Session {
constructor(token, user) {
/**
* The current authenticated user.
*
* @type {User|null}
* @public
*/
this.user = user;
/**
* The token that was used for authentication.
*
* @type {String|null}
* @public
*/
this.token = token;
}
/**
* Attempt to log in a user.
*
* @param {String} identification The username/email.
* @param {String} password
* @param {Object} [options]
* @return {Promise}
* @public
*/
login(identification, password, options = {}) {
return app.request(Object.assign({
method: 'POST',
url: app.forum.attribute('baseUrl') + '/login',
data: {identification, password}
}, options))
.then(() => window.location.reload());
}
/**
* Log the user out.
*
* @public
*/
logout() {
window.location = app.forum.attribute('baseUrl') + '/logout?token=' + this.token;
}
/**
* Apply an authorization header with the current token to the given
* XMLHttpRequest object.
*
* @param {XMLHttpRequest} xhr
* @public
*/
authorize(xhr) {
if (this.token) {
xhr.setRequestHeader('Authorization', 'Token ' + this.token);
}
}
}