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

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

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