2018-06-07 05:49:44 +00:00
|
|
|
import isString from 'lodash/isString';
|
|
|
|
import jwtDecode from 'jwt-decode';
|
2018-06-06 06:42:34 +00:00
|
|
|
|
2018-06-06 06:00:01 +00:00
|
|
|
export default class User {
|
|
|
|
/**
|
2018-06-07 05:49:44 +00:00
|
|
|
* Get a new user model from the JWT.
|
2018-06-06 06:00:01 +00:00
|
|
|
*
|
2018-06-07 05:49:44 +00:00
|
|
|
* @return {User | null}
|
2018-06-06 06:00:01 +00:00
|
|
|
*/
|
2018-06-07 05:49:44 +00:00
|
|
|
static fromToken(token) {
|
|
|
|
if (!isString(token)) {
|
2018-06-16 21:05:39 +00:00
|
|
|
token = this.getToken();
|
2018-06-07 05:49:44 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if (!isString(token) || token.length < 1) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2018-06-16 21:05:39 +00:00
|
|
|
try {
|
|
|
|
const data = jwtDecode(token);
|
|
|
|
if (data.user) {
|
|
|
|
return new User(data.user);
|
|
|
|
}
|
|
|
|
} catch (ex) {}
|
2018-06-07 05:49:44 +00:00
|
|
|
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Return the JWT for the authenticated user.
|
|
|
|
*
|
|
|
|
* @returns {string | null}
|
|
|
|
*/
|
2018-06-16 21:05:39 +00:00
|
|
|
static getToken() {
|
2018-06-07 05:49:44 +00:00
|
|
|
return localStorage.getItem('token');
|
2018-05-28 22:37:09 +00:00
|
|
|
}
|
|
|
|
|
2018-06-06 06:00:01 +00:00
|
|
|
/**
|
|
|
|
* Create a new user model.
|
|
|
|
*
|
|
|
|
* @param {Boolean} admin
|
|
|
|
* @param {String} username
|
|
|
|
* @param {String} email
|
|
|
|
* @param {String} first_name
|
|
|
|
* @param {String} last_name
|
|
|
|
* @param {String} language
|
|
|
|
*/
|
|
|
|
constructor({
|
|
|
|
admin,
|
|
|
|
username,
|
|
|
|
email,
|
|
|
|
first_name,
|
|
|
|
last_name,
|
|
|
|
language,
|
|
|
|
}) {
|
|
|
|
this.admin = admin;
|
|
|
|
this.username = username;
|
|
|
|
this.email = email;
|
|
|
|
this.name = `${first_name} ${last_name}`;
|
|
|
|
this.first_name = first_name;
|
|
|
|
this.last_name = last_name;
|
|
|
|
this.language = language;
|
2018-05-28 22:37:09 +00:00
|
|
|
}
|
2018-06-16 21:05:39 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Returns the JWT belonging to the current user.
|
|
|
|
*/
|
|
|
|
getJWT() {
|
|
|
|
return jwtDecode(User.getToken());
|
|
|
|
}
|
2018-05-28 22:37:09 +00:00
|
|
|
}
|