2016-02-13 20:58:47 +05:30
|
|
|
import { PropTypes } from 'react';
|
|
|
|
|
|
|
|
const KEY_USER = 'user';
|
|
|
|
|
|
|
|
export default class User {
|
|
|
|
/**
|
|
|
|
* @param {Object|string|undefined} data plain object or jwt token or empty to load from storage
|
|
|
|
*
|
|
|
|
* @return {User}
|
|
|
|
*/
|
|
|
|
constructor(data) {
|
|
|
|
if (!data) {
|
|
|
|
return this.load();
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO: strict value types validation
|
|
|
|
|
|
|
|
const defaults = {
|
|
|
|
id: null,
|
|
|
|
token: '',
|
|
|
|
username: '',
|
|
|
|
email: '',
|
|
|
|
avatar: '',
|
2016-02-26 23:43:41 +05:30
|
|
|
goal: null, // the goal with wich user entered site
|
2016-02-13 20:58:47 +05:30
|
|
|
isGuest: true,
|
2016-02-28 16:54:47 +05:30
|
|
|
isActive: true,
|
2016-03-10 03:40:28 +05:30
|
|
|
shouldChangePassword: false // TODO: нужно ещё пробросить причину необходимости смены
|
2016-02-13 20:58:47 +05:30
|
|
|
};
|
|
|
|
|
|
|
|
const user = Object.keys(defaults).reduce((user, key) => {
|
|
|
|
if (data.hasOwnProperty(key)) {
|
|
|
|
user[key] = data[key];
|
|
|
|
}
|
|
|
|
|
|
|
|
return user;
|
|
|
|
}, defaults);
|
|
|
|
|
|
|
|
localStorage.setItem(KEY_USER, JSON.stringify(user));
|
|
|
|
|
|
|
|
return user;
|
|
|
|
}
|
|
|
|
|
|
|
|
load() {
|
|
|
|
try {
|
|
|
|
return new User(JSON.parse(localStorage.getItem(KEY_USER)));
|
|
|
|
} catch (error) {
|
|
|
|
return new User({isGuest: true});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export const userShape = PropTypes.shape({
|
|
|
|
id: PropTypes.number,
|
|
|
|
token: PropTypes.string,
|
|
|
|
username: PropTypes.string,
|
|
|
|
email: PropTypes.string,
|
|
|
|
avatar: PropTypes.string,
|
|
|
|
isGuest: PropTypes.bool.isRequired,
|
|
|
|
isActive: PropTypes.bool.isRequired
|
|
|
|
});
|