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