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

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

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