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,
|
2016-03-12 03:32:52 +05:30
|
|
|
uuid: null,
|
2016-02-13 20:58:47 +05:30
|
|
|
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-12 03:32:52 +05:30
|
|
|
shouldChangePassword: false, // TODO: нужно ещё пробросить причину необходимости смены
|
|
|
|
passwordChangedAt: null
|
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,
|
2016-03-12 03:32:52 +05:30
|
|
|
uuid: PropTypes.string,
|
2016-02-13 20:58:47 +05:30
|
|
|
token: PropTypes.string,
|
|
|
|
username: PropTypes.string,
|
|
|
|
email: PropTypes.string,
|
|
|
|
avatar: PropTypes.string,
|
|
|
|
isGuest: PropTypes.bool.isRequired,
|
2016-03-12 03:32:52 +05:30
|
|
|
isActive: PropTypes.bool.isRequired,
|
|
|
|
passwordChangedAt: PropTypes.number
|
2016-02-13 20:58:47 +05:30
|
|
|
});
|