提交 7815cca2 authored 作者: vipcxj's avatar vipcxj

安产品id和用户id分离浏览器本地数据

上级 0f68f6ce
...@@ -7,8 +7,8 @@ const data = { ...@@ -7,8 +7,8 @@ const data = {
export async function initApp(app) { export async function initApp(app) {
data.app = app; data.app = app;
await histories.init(); await histories.init();
await histories.createHistory('domain', 10); await histories.createHistory('domain', null, 10);
await histories.createHistory('module', 50); await histories.createHistory('module', null, 50);
return data.app; return data.app;
} }
......
import { routerRedux } from 'dva/router'; import { routerRedux } from 'dva/router';
import { fetchDomains, switchDomain, getInfo, currentDomain } from '../services/domain'; import { fetchDomains, switchDomain, getInfo, currentDomain } from '../services/domain';
import { getDomain, histories, setDomain } from '../utils/auth'; import { getDomain, getUser, histories, setDomain } from '../utils/auth';
import config from '../utils/config'; import config from '../utils/config';
export default { export default {
...@@ -36,7 +36,8 @@ export default { ...@@ -36,7 +36,8 @@ export default {
const { path, name } = yield call(currentDomain); const { path, name } = yield call(currentDomain);
yield call(setDomain, name, path); yield call(setDomain, name, path);
yield put({ type: 'queryInit', payload: path }); yield put({ type: 'queryInit', payload: path });
const latest = yield call(histories.getLatest, 'module'); const user = yield call(getUser);
const latest = yield call(histories.getLatest, 'module', user && user.id);
if (latest && config.fastNavigationPage) { if (latest && config.fastNavigationPage) {
yield put(routerRedux.push('/fastNav')); yield put(routerRedux.push('/fastNav'));
} else { } else {
......
...@@ -10,11 +10,11 @@ import config from '../utils/config'; ...@@ -10,11 +10,11 @@ import config from '../utils/config';
import { getStore } from '../index'; import { getStore } from '../index';
const successAuthed = async (tokenId, userName, remember) => { const successAuthed = async (tokenId, userName, remember) => {
await histories.pushHistory('userName', remember ? userName : ''); await histories.pushHistory('userName', null, remember ? userName : '');
await setToken(tokenId); await setToken(tokenId);
const uInfo = await userInfo(); const uInfo = await userInfo();
await setUser(uInfo.id, uInfo.name); await setUser(uInfo.id, uInfo.name);
const path = await histories.getLatest('domain'); const path = await histories.getLatest('domain', uInfo.id);
if (!path) { if (!path) {
getStore().dispatch(routerRedux.push('/domain')); getStore().dispatch(routerRedux.push('/domain'));
} else { } else {
...@@ -22,7 +22,7 @@ const successAuthed = async (tokenId, userName, remember) => { ...@@ -22,7 +22,7 @@ const successAuthed = async (tokenId, userName, remember) => {
const domain = await currentDomain(); const domain = await currentDomain();
if (domain) { if (domain) {
await setDomain(domain.name, path); await setDomain(domain.name, path);
const latest = await histories.getLatest('module'); const latest = await histories.getLatest('module', uInfo.id);
if (latest && config.fastNavigationPage) { if (latest && config.fastNavigationPage) {
getStore().dispatch(routerRedux.push('/fastNav')); getStore().dispatch(routerRedux.push('/fastNav'));
} else { } else {
...@@ -91,7 +91,7 @@ export default { ...@@ -91,7 +91,7 @@ export default {
yield put({ type: 'setStatus', payload: 'login' }); yield put({ type: 'setStatus', payload: 'login' });
yield put({ type: 'setUCACode', payload: '' }); yield put({ type: 'setUCACode', payload: '' });
yield put({ type: 'setAuthRequires', payload: [] }); yield put({ type: 'setAuthRequires', payload: [] });
const userName = yield call(histories.getLatest, 'userName'); const userName = yield call(histories.getLatest, 'userName', null);
yield put({ type: 'setUserName', payload: userName || '' }); yield put({ type: 'setUserName', payload: userName || '' });
}, },
*login({ payload: userName }, { call, put }) { *login({ payload: userName }, { call, put }) {
......
...@@ -4,7 +4,7 @@ import { Router4Compat as Router } from 'react-router-4-compat'; ...@@ -4,7 +4,7 @@ import { Router4Compat as Router } from 'react-router-4-compat';
import isString from 'lodash/isString'; import isString from 'lodash/isString';
import get from 'lodash/get'; import get from 'lodash/get';
import config from './utils/config'; import config from './utils/config';
import { isAuthed, hasDomain, histories } from './utils/auth'; import { getUser, isAuthed, hasDomain, histories } from './utils/auth';
import { processError } from './utils/error'; import { processError } from './utils/error';
import App from './routes/app'; import App from './routes/app';
import { getMenus, getModuleInfo, getModuleLayout } from './data/modules'; import { getMenus, getModuleInfo, getModuleLayout } from './data/modules';
...@@ -108,13 +108,16 @@ const createRoutes = async (app, modules, groups, basePath) => { ...@@ -108,13 +108,16 @@ const createRoutes = async (app, modules, groups, basePath) => {
const onEnter = route.onEnter; const onEnter = route.onEnter;
route.onEnter = (nextState, replace, cb) => { route.onEnter = (nextState, replace, cb) => {
if (get(nextState, 'location.pathname') === route.fullPath) { if (get(nextState, 'location.pathname') === route.fullPath) {
histories.pushHistory('module', { getUser()
.then(u => u && u.id)
.then(uid => histories.pushHistory('module', uid, {
name, name,
showName, showName,
icon, icon,
description, description,
path: route.fullPath, path: route.fullPath,
}).then(() => new Promise((resolve, reject) => { }))
.then(() => new Promise((resolve, reject) => {
onEnter(nextState, replace, (err, res) => { onEnter(nextState, replace, (err, res) => {
if (err) { if (err) {
reject(err); reject(err);
...@@ -122,7 +125,9 @@ const createRoutes = async (app, modules, groups, basePath) => { ...@@ -122,7 +125,9 @@ const createRoutes = async (app, modules, groups, basePath) => {
resolve(res); resolve(res);
} }
}); });
})).then(() => cb()).catch(err => cb(err)); }))
.then(() => cb())
.catch(err => cb(err));
} else { } else {
return onEnter(nextState, replace, cb); return onEnter(nextState, replace, cb);
} }
...@@ -130,13 +135,17 @@ const createRoutes = async (app, modules, groups, basePath) => { ...@@ -130,13 +135,17 @@ const createRoutes = async (app, modules, groups, basePath) => {
} else { } else {
route.onEnter = (nextState, replace, cb) => { route.onEnter = (nextState, replace, cb) => {
if (get(nextState, 'location.pathname') === route.fullPath) { if (get(nextState, 'location.pathname') === route.fullPath) {
histories.pushHistory('module', { getUser()
.then(u => u && u.id)
.then(uid => histories.pushHistory('module', uid, {
name, name,
showName, showName,
icon, icon,
description, description,
path: route.fullPath, path: route.fullPath,
}).then(() => cb()).catch(err => cb(err)); }))
.then(() => cb())
.catch(err => cb(err));
} else { } else {
cb(); cb();
} }
...@@ -160,14 +169,18 @@ function RouterConfig({ history, app }) { ...@@ -160,14 +169,18 @@ function RouterConfig({ history, app }) {
component: App, component: App,
indexRoute: { indexRoute: {
onEnter: (nextState, replace, cb) => { onEnter: (nextState, replace, cb) => {
histories.getLatest('module').then((latest) => { getUser()
.then(u => u && u.id)
.then(uid => histories.getLatest('module', uid))
.then((latest) => {
if (latest && config.fastNavigationPage) { if (latest && config.fastNavigationPage) {
replace('/fastNav'); replace('/fastNav');
} else { } else {
replace('/main'); replace('/main');
} }
cb(); cb();
}).catch((err) => { })
.catch((err) => {
cb(err); cb(err);
}); });
}, },
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
import request from '../utils/request'; import request from '../utils/request';
import post from '../utils/post'; import post from '../utils/post';
import config from '../utils/config'; import config from '../utils/config';
import { getDomain, histories } from '../utils/auth'; import { getDomain, getUser, histories } from '../utils/auth';
export async function fetchDomains(basePath, withRoot = false) { export async function fetchDomains(basePath, withRoot = false) {
if (!basePath) { if (!basePath) {
...@@ -36,7 +36,8 @@ export async function getInfo(dmPath) { ...@@ -36,7 +36,8 @@ export async function getInfo(dmPath) {
export async function switchDomain(path) { export async function switchDomain(path) {
await post(`${config.apiContextPath}/api/domain/user/path`, { dmPath: path }); await post(`${config.apiContextPath}/api/domain/user/path`, { dmPath: path });
histories.pushHistory('domain', path); const user = await getUser();
histories.pushHistory('domain', user && user.id, path);
} }
export async function currentDomain() { export async function currentDomain() {
......
...@@ -2,54 +2,137 @@ ...@@ -2,54 +2,137 @@
/** /**
* Created by yaohx_169 on 2017/6/8. * Created by yaohx_169 on 2017/6/8.
*/ */
import { cookie } from './config'; import config, { cookie } from './config';
import { getCookie, setCookie, delCookie } from './helper'; import { getCookie, setCookie, delCookie } from './helper';
import db from './db'; import db from './db';
const getSubValue = (key, subKey) => {
const value = getCookie(key);
if (!value) {
return null;
}
try {
const json = JSON.parse(value);
return json[subKey];
} catch (e) {
delCookie(key);
throw new Error(`损坏的${key} cookie!`);
}
};
const setSubValue = (key, subKey, value) => {
const v = getCookie(key);
if (v) {
try {
const json = JSON.parse(v);
json[subKey] = value;
setCookie(key, JSON.stringify(json));
} catch (e) {
delCookie(key);
throw new Error(`损坏的${key} cookie!`);
}
} else {
setCookie(key, JSON.stringify({
[subKey]: value,
}));
}
};
const delSubValue = (key, subKey) => {
const value = getCookie(key);
if (value) {
try {
const json = JSON.parse(value);
delete json[subKey];
setCookie(key, JSON.stringify(json));
} catch (e) {
delCookie(key);
throw new Error(`损坏的${key} cookie!`);
}
}
};
const getProductValue = (key) => {
return getSubValue(key, config.productId);
};
const setProductValue = (key, value) => {
setSubValue(key, config.productId, value);
};
const delProductValue = (key) => {
delSubValue(key, config.productId);
};
const getUserValue = (key) => {
const uid = getProductValue(cookie.userId);
if (uid) {
return getSubValue(key, `${config.productId}/${uid}`);
} else {
return null;
}
};
const setUserValue = (key, value) => {
const uid = getProductValue(cookie.userId);
if (uid) {
setSubValue(key, `${config.productId}/${uid}`, value);
}
};
const delUserValue = (key) => {
const uid = getProductValue(cookie.userId);
if (uid) {
delSubValue(key, `${config.productId}/${uid}`);
}
};
export async function getToken() { export async function getToken() {
return getCookie(cookie.token); return getProductValue(cookie.token);
} }
export async function setToken(token) { export async function setToken(token) {
setCookie(cookie.token, token); setProductValue(cookie.token, token);
} }
export async function delToken() { export async function delToken() {
delCookie(cookie.token); delProductValue(cookie.token);
} }
export async function getUser() { export async function getUser() {
return { const id = getProductValue(cookie.userId);
id: getCookie(cookie.userId), return id ? {
name: getCookie(cookie.userName), id,
}; name: getProductValue(cookie.userName),
} : null;
} }
export async function setUser(id, name) { export async function setUser(id, name) {
setCookie(cookie.userId, id); setProductValue(cookie.userId, id);
setCookie(cookie.userName, name); setProductValue(cookie.userName, name);
} }
export async function delUser() { export async function delUser() {
delCookie(cookie.userId); delProductValue(cookie.userId);
delCookie(cookie.userName); delProductValue(cookie.userName);
} }
export async function getDomain() { export async function getDomain() {
return { const path = getUserValue(cookie.domainPath);
name: getCookie(cookie.domainName), return path ? {
path: getCookie(cookie.domainPath), name: getUserValue(cookie.domainName),
}; path,
} : null;
} }
export async function setDomain(name, path) { export async function setDomain(name, path) {
setCookie(cookie.domainName, name); setUserValue(cookie.domainName, name);
setCookie(cookie.domainPath, path); setUserValue(cookie.domainPath, path);
} }
export async function delDomain() { export async function delDomain() {
delCookie(cookie.domainName); delUserValue(cookie.domainName);
delCookie(cookie.domainPath); delUserValue(cookie.domainPath);
} }
export async function isAuthed() { export async function isAuthed() {
...@@ -85,6 +168,24 @@ const normHistory = size => (history) => { ...@@ -85,6 +168,24 @@ const normHistory = size => (history) => {
return history; return history;
}; };
const normData = key => (history) => {
if (!key) {
return history;
}
if (!history[key]) {
history[key] = {};
}
if (!history[key].data) {
history[key].data = [];
history[key].start = 0;
history[key].top = 0;
history[key].empty = true;
}
return history;
};
const selectData = key => history => (key ? history[key] : history);
const next = (i, size) => { const next = (i, size) => {
if (i < 0 || i >= size) { if (i < 0 || i >= size) {
throw new Error(`out of range: ${i} in ${size}`); throw new Error(`out of range: ${i} in ${size}`);
...@@ -108,54 +209,62 @@ const prev = (i, size) => { ...@@ -108,54 +209,62 @@ const prev = (i, size) => {
}; };
export const histories = { export const histories = {
async getLatest(name) { async getLatest(name, uid) {
return db(`history.${name}`)(normHistory(), (history) => { return db([config.productId, 'history', name])(normHistory(), normData(uid), (history) => {
if (history.empty) { const target = selectData(uid)(history);
if (target.empty) {
return null; return null;
} }
return history.data[prev(history.top, history.size)]; return target.data[prev(target.top, history.size)];
}); });
}, },
async createHistory(name, size) { async createHistory(name, uid, size) {
return db(`history.${name}`).write(normHistory(size)); return db([config.productId, 'history', name]).write(normHistory(size), normData(uid));
}, },
async destroyHistory(name) { async destroyHistory(name, uid) {
return db(`history.${name}`).delete(); const path = [config.productId, 'history', name];
if (uid) {
path.push(uid);
}
return db(path).delete();
}, },
async getHistory(name, size) { async getHistory(name, uid, size) {
return db(`history.${name}`)(normHistory(size), (h) => { return db([config.productId, 'history', name])(normHistory(size), normData(uid), (h) => {
if (h.empty) { const target = selectData(uid)(h);
if (target.empty) {
return []; return [];
} else if (h.top > h.start) { } else if (target.top > target.start) {
return h.data.slice(h.start, h.top); return target.data.slice(target.start, target.top);
} else { } else {
return [...h.data.slice(h.start, h.size), ...h.data.slice(0, h.top)]; return [...target.data.slice(target.start, h.size), ...target.data.slice(0, target.top)];
} }
}); });
}, },
async pushHistory(name, value, size) { async pushHistory(name, uid, value, size) {
return db(`history.${name}`).write(normHistory(size), (history) => { return db([config.productId, 'history', name]).write(normHistory(size), normData(uid), (history) => {
history.data[history.top] = value; const target = selectData(uid)(history);
const nextPos = next(history.top, history.size); target.data[target.top] = value;
if (!history.empty && history.start === history.top) { const nextPos = next(target.top, history.size);
history.top = history.start = nextPos; if (!target.empty && target.start === target.top) {
target.top = target.start = nextPos;
} else { } else {
history.top = nextPos; target.top = nextPos;
} }
if (history.empty) { if (target.empty) {
history.empty = false; target.empty = false;
} }
return history; return history;
}); });
}, },
async popHistory(name) { async popHistory(name, uid) {
return db(`history.${name}`).write(normHistory(), (history) => { return db([config.productId, 'history', name]).write(normHistory(), normData(uid), (history) => {
if (history.empty) { const target = selectData(uid)(history);
if (target.empty) {
return; return;
} }
history.top = prev(history.top, history.size); target.top = prev(target.top, history.size);
if (history.top === history.start) { if (target.top === target.start) {
history.empty = true; target.empty = true;
} }
return history; return history;
}); });
......
/* eslint-disable no-param-reassign */ /* eslint-disable no-param-reassign */
/** @module utils/db */ /** @module utils/db */
import set from 'lodash/fp/set'; import set from 'lodash/set';
import unset from 'lodash/fp/unset'; import unset from 'lodash/unset';
import flow from 'lodash/fp/flow'; import flow from 'lodash/fp/flow';
import getOr from 'lodash/fp/getOr'; import getOr from 'lodash/fp/getOr';
import LocalStorage from 'lowdb/adapters/LocalStorage'; import LocalStorage from 'lowdb/adapters/LocalStorage';
...@@ -114,11 +114,11 @@ const CreateDB = () => { ...@@ -114,11 +114,11 @@ const CreateDB = () => {
getValue.write = (...args) => { getValue.write = (...args) => {
const result = getValue(...args); const result = getValue(...args);
set(path, result, db.getState()); set(db.getState(), path, result);
return db.write(); return db.write();
}; };
getValue.delete = (flush = true) => { getValue.delete = (flush = true) => {
unset(path, db.getState()); unset(db.getState(), path);
return flush ? db.write() : db.getState(); return flush ? db.write() : db.getState();
}; };
......
/* eslint-disable no-param-reassign */
import moment from 'moment'; import moment from 'moment';
import pickBy from 'lodash/pickBy'; import pickBy from 'lodash/pickBy';
import negate from 'lodash/negate'; import negate from 'lodash/negate';
...@@ -8,18 +9,29 @@ import config from './config'; ...@@ -8,18 +9,29 @@ import config from './config';
const { contextPath, pubKey } = config; const { contextPath, pubKey } = config;
const toKey = (key) => {
let ret = key.replace(/(_{2,})/g, '$1_');
ret = ret.replace(/-/g, '__');
if (!/^\w+$/.test(ret)) {
throw new Error(`Invalid cookie key: ${key}.`);
}
return ret;
};
export function setCookie(name, value, options = {}) { export function setCookie(name, value, options = {}) {
const { path, domain, expires } = options; const { path, domain, expires } = options;
name = toKey(name);
if (name) { if (name) {
const expireSet = expires ? ` expires=${moment().add(expires, 'ms').toDate().toUTCString()};` : ''; const expireSet = expires ? ` expires=${moment().add(expires, 'ms').toDate().toUTCString()};` : '';
const domainSet = domain ? ` domain=${domain};` : ''; const domainSet = domain ? ` domain=${domain};` : '';
const pathSet = path ? ` path=${path};` : ' path=/'; const pathSet = path ? ` path=${path};` : ' path=/;';
const valueSet = value ? `${name}=${encodeURIComponent(value)};` : ''; const valueSet = value ? `${name}=${encodeURIComponent(value)};` : '';
document.cookie = `${valueSet}${expireSet}${domainSet};${pathSet}`; // eslint-disable-line document.cookie = `${valueSet}${expireSet}${domainSet}${pathSet}`; // eslint-disable-line
} }
} }
export function getCookie(name) { export function getCookie(name) {
name = toKey(name);
const reg = new RegExp(`(^|)${name}=([^;]*)(;|$)`, 'g'); const reg = new RegExp(`(^|)${name}=([^;]*)(;|$)`, 'g');
const arr = document.cookie.match(reg); // eslint-disable-line const arr = document.cookie.match(reg); // eslint-disable-line
if (arr) { if (arr) {
...@@ -35,6 +47,7 @@ export function getCookie(name) { ...@@ -35,6 +47,7 @@ export function getCookie(name) {
export function delCookie(name, { domain, path } = {}) { export function delCookie(name, { domain, path } = {}) {
if (getCookie(name)) { if (getCookie(name)) {
name = toKey(name);
const domainSet = domain ? ` domain=${domain};` : ''; const domainSet = domain ? ` domain=${domain};` : '';
const pathSet = path ? ` path=${path};` : ' path=/'; const pathSet = path ? ` path=${path};` : ' path=/';
document.cookie = `${name}=; expires=Thu, 01-Jan-70 00:00:01 GMT;${pathSet}${domainSet}`; // eslint-disable-line document.cookie = `${name}=; expires=Thu, 01-Jan-70 00:00:01 GMT;${pathSet}${domainSet}`; // eslint-disable-line
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论