mirror of
https://github.com/flarum/framework.git
synced 2024-12-01 14:20:47 +08:00
26a821e3e2
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
64 lines
1.4 KiB
JavaScript
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);
|
|
}
|
|
}
|
|
}
|