UNPKG

ice-frontend-react-mobx

Version:
135 lines (111 loc) 3.52 kB
var debug = require('debug')('ice:AuthStore'); import { observable, action, computed } from 'mobx'; // import { api } from '../helpers/Api'; export default class AuthStore { @observable isAuthenticated = false; @observable authStore = {}; @observable userName = ''; @observable user = observable.map({}); constructor (api) { this.api = api; this._loadAuth(); } @action authenticate (user, pass) { return this.api.auth.post(user, pass).then((session) => { if (session.token) { // this.isAuthenticated = true; this.authStore = session; this.userName = user; this.api.token = session.token; // check our user return this._updateSessionUser().then((user) => { debug('Got your user:', user); if (user.active === 'true') { this.isAuthenticated = true; this.user.merge(user); this._saveAuth(); return true; } else { return false; } }); } else { debug('Login failed...'); throw new Error('Login failed, no token provided'); } }); } _getSessionUser () { return this.api.users.getUser(this.authStore.userId); } _updateSessionUser () { return this._getSessionUser().then((user) => { this.user.merge(user); return user; }).catch(() => { this.signout(); }); } @computed get needsPasswordReset () { let needsReset = false; let expiration = this.user.get('passwordExpirationDate') || 0; let created = this.user.get('createdDate') || 0; let email = this.user.get('email') || ''; debug('Expiration: %s, Created: %s', expiration, created); if (created === expiration) { needsReset = true; } else if (expiration < Date.now()) { needsReset = true; } // we can't reset iceadmin password, so ignore expired here. if (expiration === 0 || email === 'iceadmin@vpsi.io' || email === 'admin@vpsi.io') { needsReset = false; } return needsReset; } changePassword (current, password) { let id = this.authStore.userId; return this.api.users.changePassword(id, current, password).then((response) => { debug('Password Updated:', response); this._updateSessionUser(); return response; }); } signout () { localStorage.removeItem('vps-fe-sess'); this.isAuthenticated = false; this.authStore = observable({}); this._saveAuth(); } _saveAuth () { localStorage.removeItem('vps-fe-sess'); this.authStore.userName = this.userName; let session = JSON.stringify(this.authStore); localStorage.setItem('vps-fe-sess', session); } _loadAuth () { debug('Loading auth from loacal storage...'); let session = localStorage.getItem('vps-fe-sess'); if (session) { try { debug('Parsing stored session...'); session = JSON.parse(session); } catch (e) { debug('Error Loading Session from storage.', e); localStorage.removeItem('vps-fe-sess'); session = false; } if (session && session.expiration > Date.now()) { debug('Stored session used:', session); this.isAuthenticated = true; this.authStore = session; this.api.token = session.token; // check our user this._updateSessionUser(); } else { localStorage.removeItem('vps-fe-sess'); debug('Stored session expired or invalid'); } } } }