提交 f9fe1fe7 authored 作者: vipcxj's avatar vipcxj

improve: 为了尽可能兼容app的api,token,domain,user的存取改为异步

上级 d3077135
...@@ -2,5 +2,6 @@ ...@@ -2,5 +2,6 @@
<profile version="1.0"> <profile version="1.0">
<option name="myName" value="Project Default" /> <option name="myName" value="Project Default" />
<inspection_tool class="Eslint" enabled="true" level="ERROR" enabled_by_default="true" /> <inspection_tool class="Eslint" enabled="true" level="ERROR" enabled_by_default="true" />
<inspection_tool class="JSUnusedGlobalSymbols" enabled="false" level="WARNING" enabled_by_default="false" />
</profile> </profile>
</component> </component>
\ No newline at end of file
const proxy = { const proxy = {
"target": "http://192.168.1.121:8180", "target": "http://192.168.1.200:8090",
"changeOrigin": true, "changeOrigin": true,
"pathRewrite": { "pathRewrite": {
"^/api": "/big-machine/restful-services" "^/api": "/big-machine/restful-services"
...@@ -7,7 +7,7 @@ const proxy = { ...@@ -7,7 +7,7 @@ const proxy = {
}; };
const resource_proxy = { const resource_proxy = {
"target": "http://192.168.1.121:8180", "target": "http://192.168.1.200:8090",
"changeOrigin": true, "changeOrigin": true,
"pathRewrite": { "pathRewrite": {
"^/": "/big-machine/" "^/": "/big-machine/"
......
import { routerRedux } from 'dva/router'; import { routerRedux } from 'dva/router';
import { fetchDomains, switchDomain, currentDomain } from '../services/domain'; import { fetchDomains, switchDomain, currentDomain } from '../services/domain';
import { setCookie, fullPath } from '../utils/helper'; import { fullPath } from '../utils/helper';
import { cookie } from '../utils/config'; import { getDomain, setDomain } from '../utils/auth';
export default { export default {
namespace: 'domain', namespace: 'domain',
state: { state: {
init: undefined,
list: [], list: [],
}, },
...@@ -17,21 +18,30 @@ export default { ...@@ -17,21 +18,30 @@ export default {
}, },
effects: { effects: {
*fetch(action, { put, call }) { *fetch(ignored, { put, call }) {
const domain = yield call(getDomain);
const init = domain ? domain.path : undefined;
const list = yield call(fetchDomains, '/', true); const list = yield call(fetchDomains, '/', true);
yield put({ type: 'querySuccess', payload: list }); yield put({ type: 'queryInit', payload: init });
yield put({ type: 'queryList', payload: list });
}, },
*switch({ payload: domainPath }, { put, call }) { *switch({ payload: domainPath }, { put, call }) {
yield call(switchDomain, domainPath); yield call(switchDomain, domainPath);
const { path, name } = yield call(currentDomain); const { path, name } = yield call(currentDomain);
setCookie(cookie.domainPath, path); yield call(setDomain, name, path);
setCookie(cookie.domainName, name); yield put({ type: 'queryInit', payload: path });
yield put(routerRedux.push(fullPath('/main'))); yield put(routerRedux.push(fullPath('/main')));
}, },
}, },
reducers: { reducers: {
querySuccess(state, { payload: list }) { queryInit(state, { payload: init }) {
return {
...state,
init,
};
},
queryList(state, { payload: list }) {
return { return {
...state, ...state,
list, list,
......
import { routerRedux } from 'dva/router'; import { routerRedux } from 'dva/router';
import { login, userInfo } from '../services/login'; import { login, userInfo } from '../services/login';
import { setCookie, fullPath } from '../utils/helper'; import { fullPath } from '../utils/helper';
import { cookie } from '../utils/config'; import { setToken, setUser } from '../utils/auth';
import { errors } from '../utils/error'; import { errors } from '../utils/error';
export default { export default {
...@@ -19,10 +19,9 @@ export default { ...@@ -19,10 +19,9 @@ export default {
if (requirements.length > 0) { if (requirements.length > 0) {
throw errors.unsupportedAuthType(requirements); throw errors.unsupportedAuthType(requirements);
} }
setCookie(cookie.token, tokenId); yield call(setToken, tokenId);
const uInfo = yield call(userInfo); const uInfo = yield call(userInfo);
setCookie(cookie.userId, uInfo.id); yield call(setUser, uInfo.id, uInfo.name);
setCookie(cookie.userName, uInfo.name);
yield put(routerRedux.push(fullPath('/domain'))); yield put(routerRedux.push(fullPath('/domain')));
}, },
}, },
......
...@@ -2,9 +2,9 @@ import { routerRedux } from 'dva/router'; ...@@ -2,9 +2,9 @@ import { routerRedux } from 'dva/router';
import { isString } from 'lodash'; import { isString } from 'lodash';
import { logout } from '../../services/main'; import { logout } from '../../services/main';
import { fetchDomains, switchDomain, currentDomain } from '../../services/domain'; import { fetchDomains, switchDomain, currentDomain } from '../../services/domain';
import { cookie } from '../../utils/config';
import { getMenus, getModuleInfo } from '../../data/modules'; import { getMenus, getModuleInfo } from '../../data/modules';
import { setCookie, delCookie, fullPath, getCookie } from '../../utils/helper'; import { fullPath } from '../../utils/helper';
import { delToken, getDomain, setDomain, delDomain, getUser, delUser } from '../../utils/auth';
const createMenu = async (configure) => { const createMenu = async (configure) => {
const menu = { const menu = {
...@@ -69,55 +69,6 @@ const createMenus = async (menusConfigure) => { ...@@ -69,55 +69,6 @@ const createMenus = async (menusConfigure) => {
return menus; return menus;
}; };
// const createMenus = () => {
// const menus = [];
// const makePath = (_menus, path) => {
// if (path.length === 0) {
// return null;
// }
// const [cur, ...rest] = path;
// const find = _menus.filter(menu => menu.name === `${cur}`).pop();
// if (find) {
// if (rest.length === 0) {
// return find;
// } else {
// return makePath(find.children, rest);
// }
// } else {
// let container = _menus;
// for (const id of path) {
// const m = getModule(id);
// const menu = {
// name: `${m.id}`,
// text: m.name,
// children: [],
// };
// container.push(menu);
// container = menu.children;
// }
// }
// };
// const makeIcon = (menu) => {
// const children = menu.children;
// if (children.length === 0) {
// menu.icon = 'file'; // eslint-disable-line no-param-reassign
// } else {
// menu.icon = 'folder'; // eslint-disable-line no-param-reassign
// for (const child of children) {
// makeIcon(child);
// }
// }
// };
// foreachModule((module) => {
// const path = getPath(module.id);
// makePath(menus, path);
// });
// for (const menu of menus) {
// makeIcon(menu);
// }
// return menus;
// };
export default { export default {
namespace: 'main', namespace: 'main',
...@@ -135,47 +86,46 @@ export default { ...@@ -135,47 +86,46 @@ export default {
}, },
effects: { effects: {
*fetchDomain(action, { put, call }) { *fetchDomain(ignored, { put, call }) {
let domain = getCookie(cookie.domainName); const domain = getDomain();
let domainName;
if (!domain) { if (!domain) {
const { path, name } = yield call(currentDomain); const { path, name } = yield call(currentDomain);
setCookie(cookie.domainPath, path); yield call(setDomain, name, path);
setCookie(cookie.domainName, name); domainName = name;
domain = name; } else {
domainName = domain.name;
} }
yield put({ type: 'switchDomainSuccess', payload: domain }); yield put({ type: 'switchDomainSuccess', payload: domainName });
}, },
*fetchDomains(action, { put, call }) { *fetchDomains(ignored, { put, call }) {
const list = yield call(fetchDomains, '/', true); const list = yield call(fetchDomains, '/', true);
yield put({ type: 'queryDomainsSuccess', payload: list }); yield put({ type: 'queryDomainsSuccess', payload: list });
}, },
*switchDomain({ payload: domainId }, { put, call }) { *switchDomain({ payload: domainId }, { put, call }) {
yield call(switchDomain, domainId); yield call(switchDomain, domainId);
const { path, name } = yield call(currentDomain); const { path, name } = yield call(currentDomain);
setCookie(cookie.domainPath, path); yield call(setDomain, name, path);
setCookie(cookie.domainName, name);
yield put({ type: 'switchDomainSuccess', payload: name }); yield put({ type: 'switchDomainSuccess', payload: name });
yield put(routerRedux.push(fullPath('/main'))); yield put(routerRedux.push(fullPath('/main')));
}, },
*fetchUser(action, { put }) { *fetchUser(ignored, { put, call }) {
const user = getCookie(cookie.userName); const user = yield call(getUser);
if (!user) { if (!user) {
yield put(routerRedux.push(fullPath('/login'))); yield put(routerRedux.push(fullPath('/login')));
} }
yield put({ type: 'queryUserSuccess', payload: user }); yield put({ type: 'queryUserSuccess', payload: user.name });
}, },
*fetchModules(action, { put, call }) { *fetchModules(ignored, { put, call }) {
const configures = yield call(getMenus); const configures = yield call(getMenus);
const menus = yield call(createMenus, configures); const menus = yield call(createMenus, configures);
yield put({ type: 'queryMenusSuccess', payload: menus }); yield put({ type: 'queryMenusSuccess', payload: menus });
}, },
*logout(action, { put, call }) { *logout(ignored, { put, call }) {
yield call(logout); yield call(logout);
delCookie(cookie.domainName); yield call(delToken);
delCookie(cookie.userName); yield call(delUser);
delCookie(cookie.domainPath); yield call(delDomain);
delCookie(cookie.userId);
delCookie(cookie.token);
yield put(routerRedux.push(fullPath('/login'))); yield put(routerRedux.push(fullPath('/login')));
}, },
}, },
......
...@@ -18,21 +18,21 @@ const registerModel = (app, model) => { ...@@ -18,21 +18,21 @@ const registerModel = (app, model) => {
} }
}; };
const maybeLogin = (nextState, replace) => { const maybeLogin = async (replace) => {
if (!isAuthed()) { if (!(await isAuthed())) {
return replace(fullPath('/login')); return replace(fullPath('/login'));
} }
}; };
const maybeSwitch = (nextState, replace) => { const maybeSwitch = async (replace) => {
if (!hasDomain()) { if (!(await hasDomain())) {
return replace(fullPath('/domain')); return replace(fullPath('/domain'));
} }
}; };
const authenticated = (nextState, replace) => { const authenticated = async (replace) => {
maybeLogin(nextState, replace); await maybeLogin(replace);
maybeSwitch(nextState, replace); await maybeSwitch(replace);
}; };
const createRoute = async (app, { name, showName, modules, children }) => { const createRoute = async (app, { name, showName, modules, children }) => {
...@@ -109,7 +109,7 @@ function RouterConfig({ history, app }) { ...@@ -109,7 +109,7 @@ function RouterConfig({ history, app }) {
childRoutes: [ childRoutes: [
{ {
path: 'login', path: 'login',
getComponent(nextState, cb) { getComponent(ignored, cb) {
require.ensure([], (require) => { require.ensure([], (require) => {
registerModel(app, require('./models/login')); registerModel(app, require('./models/login'));
cb(null, require('./routes/login')); cb(null, require('./routes/login'));
...@@ -118,8 +118,10 @@ function RouterConfig({ history, app }) { ...@@ -118,8 +118,10 @@ function RouterConfig({ history, app }) {
}, },
{ {
path: 'domain', path: 'domain',
onEnter: maybeLogin, onEnter: (ignored, replace, cb) => {
getComponent(nextState, cb) { maybeLogin(replace).then(() => cb()).catch(err => cb(err));
},
getComponent(ignored, cb) {
require.ensure([], (require) => { require.ensure([], (require) => {
registerModel(app, require('./models/domain')); registerModel(app, require('./models/domain'));
cb(null, require('./routes/domain')); cb(null, require('./routes/domain'));
...@@ -128,8 +130,10 @@ function RouterConfig({ history, app }) { ...@@ -128,8 +130,10 @@ function RouterConfig({ history, app }) {
}, },
{ {
path: 'main', path: 'main',
onEnter: authenticated, onEnter: (ignored, replace, cb) => {
getComponent(nextState, cb) { authenticated(replace).then(() => cb()).catch(err => cb(err));
},
getComponent(ignored, cb) {
require.ensure([], (require) => { require.ensure([], (require) => {
registerModel(app, require('./models/main')); registerModel(app, require('./models/main'));
cb(null, require('./routes/main')); cb(null, require('./routes/main'));
...@@ -149,25 +153,6 @@ function RouterConfig({ history, app }) { ...@@ -149,25 +153,6 @@ function RouterConfig({ history, app }) {
.catch((err) => { .catch((err) => {
cb(err, null); cb(err, null);
}); });
// fetchModules()
// .then(() => {
// const lvl0 = [];
// foreachModule((module) => {
// if (!module.parent) {
// lvl0.push(module);
// }
// });
// createModuleRoutes(app, lvl0)
// .then((result) => {
// cb(null, result);
// })
// .catch((err) => {
// cb(err, null);
// });
// })
// .catch((err) => {
// cb(err, null);
// });
}, },
}, },
], ],
......
...@@ -2,12 +2,9 @@ import React from 'react'; ...@@ -2,12 +2,9 @@ import React from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { Form, Select, Button } from 'antd'; import { Form, Select, Button } from 'antd';
import { connect } from 'dva'; import { connect } from 'dva';
import { cookie } from '../../utils/config';
import { getCookie } from '../../utils/helper';
import styles from './index.less'; import styles from './index.less';
const FormItem = Form.Item; const FormItem = Form.Item;
const Option = Select.Option;
class Domain extends React.Component { class Domain extends React.Component {
...@@ -34,7 +31,7 @@ class Domain extends React.Component { ...@@ -34,7 +31,7 @@ class Domain extends React.Component {
render() { render() {
const { form, domain, loading } = this.props; const { form, domain, loading } = this.props;
const currentDomain = getCookie(cookie.domainPath); const currentDomain = domain.init;
const selectOptions = {}; const selectOptions = {};
const decoratorOptions = { const decoratorOptions = {
rules: [ rules: [
...@@ -55,7 +52,7 @@ class Domain extends React.Component { ...@@ -55,7 +52,7 @@ class Domain extends React.Component {
form.getFieldDecorator('domain', decoratorOptions)( form.getFieldDecorator('domain', decoratorOptions)(
<Select {...selectOptions}> <Select {...selectOptions}>
{domain.list.map(({ path, name }) => { {domain.list.map(({ path, name }) => {
return <Option value={path} key={path}>{name}</Option>; return <Select.Option value={path} key={path}>{name}</Select.Option>;
})} })}
</Select>, </Select>,
) )
......
/* eslint-disable no-param-reassign */ /* eslint-disable no-param-reassign */
import request from '../utils/request'; import request from '../utils/request';
import post from '../utils/post'; import post from '../utils/post';
import config, { cookie } from '../utils/config'; import config from '../utils/config';
import { getCookie } from '../utils/helper'; import { getDomain } from '../utils/auth';
export async function fetchDomains(basePath, withRoot = false) { export async function fetchDomains(basePath, withRoot = false) {
if (!basePath) { if (!basePath) {
basePath = getCookie(cookie.domainPath); const domain = await getDomain();
if (!domain) {
throw new Error('Not set domain yet!');
}
basePath = domain.path;
} }
const rootDomainInfo = withRoot ? await request(`${config.apiContextPath}/api/domain/user/info`, { dmPath: basePath }) : null; const rootDomainInfo = withRoot ? await request(`${config.apiContextPath}/api/domain/user/info`, { dmPath: basePath }) : null;
const childrenDomainInfoList = await request(`${config.apiContextPath}/api/domain/user/children-info`, { dmPath: basePath }); const childrenDomainInfoList = await request(`${config.apiContextPath}/api/domain/user/children-info`, { dmPath: basePath });
......
...@@ -2,26 +2,58 @@ ...@@ -2,26 +2,58 @@
* Created by yaohx_169 on 2017/6/8. * Created by yaohx_169 on 2017/6/8.
*/ */
import { cookie } from './config'; import { cookie } from './config';
import { getCookie, locationOrigin, currentPath } from './helper'; import { getCookie, setCookie, delCookie } from './helper';
export function isAuthed() { export async function getToken() {
return !!getCookie(cookie.token); return getCookie(cookie.token);
} }
export function hasDomain() { export async function setToken(token) {
return !!getCookie(cookie.domainPath); setCookie(cookie.token, token);
} }
export function redirectLogin() { export async function delToken() {
localStorage.clear(); // eslint-disable-line delCookie(cookie.token);
if (currentPath() !== '/login') {
location.href = `${locationOrigin(true)}/login?from=${currentPath()}`; // eslint-disable-line
}
} }
export function authenticated() { export async function getUser() {
const token = getCookie(cookie.token); return {
if (!token) { id: getCookie(cookie.userId),
redirectLogin(); name: getCookie(cookie.userName),
} };
}
export async function setUser(id, name) {
setCookie(cookie.userId, id);
setCookie(cookie.userName, name);
}
export async function delUser() {
delCookie(cookie.userId);
delCookie(cookie.userName);
}
export async function getDomain() {
return {
name: getCookie(cookie.domainName),
path: getCookie(cookie.domainPath),
};
}
export async function setDomain(name, path) {
setCookie(cookie.domainName, name);
setCookie(cookie.domainPath, path);
}
export async function delDomain() {
delCookie(cookie.domainName);
delCookie(cookie.domainPath);
}
export async function isAuthed() {
return getToken().then(result => !!result);
}
export async function hasDomain() {
return getDomain().then(result => !!result);
} }
import fetch from 'dva/fetch'; import fetch from 'dva/fetch';
import _ from 'lodash'; import _ from 'lodash';
import { getCookie, encrypt } from './helper'; import { encrypt } from './helper';
import { cookie } from './config';
import { errors } from './error'; import { errors } from './error';
import { getToken } from './auth';
import { checkStatus, normParams, parseObject } from './http-helper'; import { checkStatus, normParams, parseObject } from './http-helper';
const defaultOptions = { const defaultOptions = {
...@@ -18,10 +18,10 @@ const defaultOptions = { ...@@ -18,10 +18,10 @@ const defaultOptions = {
* @param {object} [options] The options we want to pass to "fetch" * @param {object} [options] The options we want to pass to "fetch"
* @return {object} An object containing either "data" or "err" * @return {object} An object containing either "data" or "err"
*/ */
export default function doDelete(url, params = {}, options = {}, auth = true) { export default async function doDelete(url, params = {}, options = {}, auth = true) {
let token; let token;
if (auth) { if (auth) {
token = getCookie(cookie.token); token = await getToken();
if (!token) { if (!token) {
return Promise.reject(errors.tokenMissing()); return Promise.reject(errors.tokenMissing());
} }
......
...@@ -8,7 +8,7 @@ const { contextPath, pubKey } = config; ...@@ -8,7 +8,7 @@ const { contextPath, pubKey } = config;
export function setCookie(name, value, options = {}) { export function setCookie(name, value, options = {}) {
const { path, domain, expires } = options; const { path, domain, expires } = options;
if (name) { if (name) {
const expireSet = expires ? ` expires=${moment().add(expires).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};` : ''; const pathSet = path ? ` path=${path};` : '';
const valueSet = value ? `${name}=${encodeURIComponent(value)};` : ''; const valueSet = value ? `${name}=${encodeURIComponent(value)};` : '';
......
/* eslint-disable no-param-reassign */ /* eslint-disable no-param-reassign */
import fetch from 'dva/fetch'; import fetch from 'dva/fetch';
import _ from 'lodash'; import _ from 'lodash';
import { getCookie, encrypt } from './helper'; import { encrypt } from './helper';
import { checkStatus, normParams, parseObject } from './http-helper'; import { checkStatus, normParams, parseObject } from './http-helper';
import { cookie } from './config'; import { getToken } from './auth';
import { errors } from './error'; import { errors } from './error';
const defaultOptions = { const defaultOptions = {
...@@ -13,12 +13,12 @@ const defaultOptions = { ...@@ -13,12 +13,12 @@ const defaultOptions = {
}; };
export default function post(url, data, params = {}, options = {}, auth = true) { export default async function post(url, data, params = {}, options = {}, auth = true) {
if (!data) { if (!data) {
data = {}; data = {};
} }
if (auth) { if (auth) {
const token = getCookie(cookie.token); const token = await getToken();
if (!token) { if (!token) {
return Promise.reject(errors.tokenMissing()); return Promise.reject(errors.tokenMissing());
} }
......
import fetch from 'dva/fetch'; import fetch from 'dva/fetch';
import _ from 'lodash'; import _ from 'lodash';
import { getCookie, encrypt } from './helper'; import { encrypt } from './helper';
import { cookie } from './config'; import { getToken } from './auth';
import { errors } from './error'; import { errors } from './error';
import { checkStatus, normParams, parseObject } from './http-helper'; import { checkStatus, normParams, parseObject } from './http-helper';
...@@ -18,10 +18,10 @@ const defaultOptions = { ...@@ -18,10 +18,10 @@ const defaultOptions = {
* @param {object} [options] The options we want to pass to "fetch" * @param {object} [options] The options we want to pass to "fetch"
* @return {object} An object containing either "data" or "err" * @return {object} An object containing either "data" or "err"
*/ */
export default function request(url, params = {}, options = {}, auth = true) { export default async function request(url, params = {}, options = {}, auth = true) {
let token; let token;
if (auth) { if (auth) {
token = getCookie(cookie.token); token = await getToken();
if (!token) { if (!token) {
return Promise.reject(errors.tokenMissing()); return Promise.reject(errors.tokenMissing());
} }
......
...@@ -13,19 +13,14 @@ import TableInput from '../src/components/table/input-table'; ...@@ -13,19 +13,14 @@ import TableInput from '../src/components/table/input-table';
import { makeCancelable } from '../src/utils/promise'; import { makeCancelable } from '../src/utils/promise';
import { login } from '../src/services/login'; import { login } from '../src/services/login';
import { switchDomain } from '../src/services/domain'; import { switchDomain } from '../src/services/domain';
import { getModuleConfigure } from '../src/services/modules'; import { setToken, setUser } from '../src/utils/auth';
import { setCookie } from '../src/utils/helper';
import { cookie } from '../src/utils/config';
const loginIt = async (userName, password, domainPath) => { const loginIt = async (userName, password, domainPath) => {
const result = await login({ userName, password }); const result = await login({ userName, password });
const { tokenId, userId } = result; const { tokenId, userId } = result;
setCookie(cookie.token, tokenId); await setToken(tokenId);
setCookie(cookie.userId, userId); await setUser(userId, userName);
setCookie(cookie.userName, userName);
await switchDomain(domainPath); await switchDomain(domainPath);
const config = await getModuleConfigure('test');
console.log(config);
}; };
const wrap = () => Comp => (props) => { const wrap = () => Comp => (props) => {
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论