Ivan - Update remember logic using local storage [skip ci]

This commit is contained in:
ivan 2016-07-20 01:31:07 -03:00
parent 0caa5cb4f9
commit b3cd09ba00
9 changed files with 135 additions and 95 deletions

View File

@ -1,6 +1,7 @@
import React from 'react'; import React from 'react';
import {render} from 'react-dom' import {render} from 'react-dom'
import Router from 'react-router'; import Router from 'react-router';
import UserStore from 'stores/user-store';
import routes from './Routes'; import routes from './Routes';
@ -13,4 +14,9 @@ if (noFixtures === 'disabled') {
require('lib-app/fixtures-loader'); require('lib-app/fixtures-loader');
} }
render(routes, document.getElementById('app')); let onSessionInit = function () {
render(routes, document.getElementById('app'));
};
UserStore.initSession().then(onSessionInit, onSessionInit);

View File

@ -14,12 +14,12 @@ const DashboardLayout = React.createClass({
}, },
render() { render() {
return ( return (UserStore.isLoggedIn()) ? (
<div> <div>
<div><DashboardMenu location={this.props.location} /></div> <div><DashboardMenu location={this.props.location} /></div>
<div>{this.props.children}</div> <div>{this.props.children}</div>
</div> </div>
); ) : null;
} }
}); });

View File

@ -27,12 +27,24 @@ module.exports = [
}, },
{ {
path: 'user/logout', path: 'user/logout',
time: 1000, time: 100,
response: function () { response: function () {
return { return {
status: 'success', status: 'success',
data: {} data: {}
}; };
} }
},
{
path: 'user/check-session',
time: 100,
response: function () {
return {
status: 'success',
data: {
sessionActive: true
}
};
}
} }
]; ];

View File

@ -9,14 +9,17 @@ function processData (data) {
} }
module.exports = { module.exports = {
call: function ({path, data, onSuccess, onFail}) { call: function ({path, data}) {
return new Promise(function (resolve, reject) {
APIUtils.post(root + path, processData(data)).then(function (result) { APIUtils.post(root + path, processData(data)).then(function (result) {
console.log(result); console.log(result);
if (result.status === 'success') { if (result.status === 'success') {
onSuccess && onSuccess(result); resolve(result);
} else { } else if (reject) {
onFail && onFail(result); reject(result);
} }
}); });
});
} }
}; };

View File

@ -0,0 +1,10 @@
export default {
getCurrentDate() {
let date = new Date();
let yyyy = date.getFullYear().toString();
let mm = (date.getMonth()+1).toString(); // getMonth() is zero-based
let dd = date.getDate().toString();
return (yyyy + (mm[1]?mm:"0"+mm[0]) + (dd[1]?dd:"0"+dd[0])) * 1;
}
}

View File

@ -1,54 +0,0 @@
import LocalStorage from 'localStorage';
class LocalStore {
constructor() {
this.storage = LocalStorage;
}
initialize() {
if (this.isRememberDataExpired()) {
this.clearRememberData();
}
if (!this.getItem('language')) {
this.setItem('language', 'english');
}
}
storeRememberData({token, userId, expiration}) {
this.setItem('rememberData-token', token);
this.setItem('rememberData-userId', userId);
this.setItem('rememberData-expiration', expiration);
}
isRememberDataExpired() {
let rememberData = this.getRememberData();
return rememberData.expiration < 2016;
}
getRememberData() {
return {
token: this.getItem('rememberData-token'),
userId: parseInt(this.getItem('rememberData-userId')),
expiration: parseInt(this.getItem('rememberData-expiration'))
};
}
clearRememberData() {
this.setItem('rememberData-token', null);
this.setItem('rememberData-userId', null);
this.setItem('rememberData-expiration', null);
}
getItem(key) {
return this.storage.getItem(key);
}
setItem(key, value) {
return this.storage.setItem(key, value);
}
}
export default new LocalStore();

View File

@ -1,8 +1,13 @@
import SessionStorage from 'sessionstorage'; import LocalStorage from 'localStorage';
import date from 'lib-app/date';
class SessionStore { class SessionStore {
constructor() { constructor() {
this.storage = SessionStorage; this.storage = LocalStorage;
if (!this.getItem('language')) {
this.setItem('language', 'english');
}
} }
createSession(userId, token) { createSession(userId, token) {
@ -18,7 +23,7 @@ class SessionStore {
} }
isLoggedIn() { isLoggedIn() {
return !!this.getItem('userId'); return !!this.getItem('token');
} }
closeSession() { closeSession() {
@ -26,6 +31,33 @@ class SessionStore {
this.removeItem('token'); this.removeItem('token');
} }
storeRememberData({token, userId, expiration}) {
this.setItem('rememberData-token', token);
this.setItem('rememberData-userId', userId);
this.setItem('rememberData-expiration', expiration);
}
isRememberDataExpired() {
let rememberData = this.getRememberData();
return rememberData.expiration < date.getCurrentDate();
}
getRememberData() {
return {
token: this.getItem('rememberData-token'),
userId: this.getItem('rememberData-userId'),
expiration: this.getItem('rememberData-expiration')
};
}
clearRememberData() {
this.removeItem('rememberData-token');
this.removeItem('rememberData-userId');
this.removeItem('rememberData-expiration');
}
getItem(key) { getItem(key) {
return this.storage.getItem(key); return this.storage.getItem(key);
} }
@ -35,7 +67,7 @@ class SessionStore {
} }
removeItem(key) { removeItem(key) {
return this.storage.removeItem(key); this.storage.removeItem(key);
} }
} }

View File

@ -1,7 +1,6 @@
const Reflux = require('reflux'); const Reflux = require('reflux');
const API = require('lib-app/api-call'); const API = require('lib-app/api-call');
const sessionStore = require('lib-app/session-store'); const sessionStore = require('lib-app/session-store');
const localStore = require('lib-app/local-store');
const UserActions = require('actions/user-actions'); const UserActions = require('actions/user-actions');
const CommonActions = require('actions/common-actions'); const CommonActions = require('actions/common-actions');
@ -14,29 +13,43 @@ const UserStore = Reflux.createStore({
this.listenTo(UserActions.checkLoginStatus, this.checkLoginStatus); this.listenTo(UserActions.checkLoginStatus, this.checkLoginStatus);
this.listenTo(UserActions.login, this.loginUser); this.listenTo(UserActions.login, this.loginUser);
this.listenTo(UserActions.logout, this.logoutUser); this.listenTo(UserActions.logout, this.logoutUser);
},
if (!this.isLoggedIn()) { initSession() {
this.loginIfRememberExists(); return API.call({
path: 'user/check-session',
data: {}
}).then(this.tryLoginIfSessionIsInactive);
},
tryLoginIfSessionIsInactive(result) {
if (!result.data.sessionActive) {
if (sessionStore.isRememberDataExpired()) {
return this.logoutUser();
} else {
return this.loginWithRememberData();
}
} }
}, },
loginUser(loginData) { loginUser(loginData) {
API.call({ let onSuccessLogin = (loginData.remember) ? this.handleLoginSuccessWithRemember : this.handleLoginSuccess;
let onFailedLogin = (loginData.isAutomatic) ? null : this.handleLoginFail;
return API.call({
path: 'user/login', path: 'user/login',
data: loginData, data: loginData
onSuccess: (loginData.remember) ? this.handleLoginSuccessWithRemember : this.handleLoginSuccess, }).then(onSuccessLogin, onFailedLogin);
onFail: (loginData.isAutomatic) ? null : this.handleLoginFail
});
}, },
logoutUser() { logoutUser() {
API.call({ return API.call({
path: 'user/logout', path: 'user/logout'
onSuccess: function () { }).then(() => {
sessionStore.closeSession(); sessionStore.closeSession();
sessionStore.clearRememberData();
CommonActions.loggedOut(); CommonActions.loggedOut();
this.trigger('LOGOUT'); this.trigger('LOGOUT');
}.bind(this)
}); });
}, },
@ -44,20 +57,18 @@ const UserStore = Reflux.createStore({
return sessionStore.isLoggedIn(); return sessionStore.isLoggedIn();
}, },
loginIfRememberExists() { loginWithRememberData() {
let rememberData = localStore.getRememberData(); let rememberData = sessionStore.getRememberData();
if (!localStore.isRememberDataExpired()) { return this.loginUser({
UserActions.login({
userId: rememberData.userId, userId: rememberData.userId,
rememberToken: rememberData.token, rememberToken: rememberData.token,
isAutomatic: true isAutomatic: true
}); });
}
}, },
handleLoginSuccessWithRemember(result) { handleLoginSuccessWithRemember(result) {
localStore.storeRememberData({ sessionStore.storeRememberData({
token: result.data.rememberToken, token: result.data.rememberToken,
userId: result.data.userId, userId: result.data.userId,
expiration: result.data.rememberExpiration expiration: result.data.rememberExpiration

View File

@ -0,0 +1,20 @@
<?php
class CheckSessionController extends Controller {
const PATH = '/check-session';
public function validations() {
return [
'permission' => 'any',
'requestData' => []
];
}
public function handler() {
$session = Session::getInstance();
Response::respondSuccess([
'sessionActive' => $session->sessionExists()
]);
}
}