提交 c9b2978e authored 作者: 吴强's avatar 吴强

init commit

上级
# http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
[Makefile]
indent_style = tab
{
"extends": "umi"
}
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
# production
/dist
# misc
.DS_Store
npm-debug.log*
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.tmp" />
<excludeFolder url="file://$MODULE_DIR$/temp" />
<excludeFolder url="file://$MODULE_DIR$/tmp" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="Eslint" enabled="true" level="ERROR" enabled_by_default="true" />
</profile>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="JavaScriptSettings">
<option name="languageLevel" value="JSX" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/JTWXWebApp.iml" filepath="$PROJECT_DIR$/.idea/JTWXWebApp.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
\ No newline at end of file
export default {
};
const proxy = {
"target": "http://192.168.1.22:8080",
//"target": "http://192.168.1.121:8180",
"changeOrigin": true,
"headers":{
"host":"192.168.1.22:8080"
},
"pathRewrite": {
"^/api": "/bm/api"
}
};
const resource_proxy = {
//"target": "http://192.168.1.121:8180",
"target": "http://192.168.1.22:8080",
"changeOrigin": true,
"headers":{
"host":"192.168.1.22:8080"
},
"pathRewrite": {
"^/resource": "/bm/resource"
}
};
const V4_proxy = {
//"http://106.ihuyi.cn/webservice/sms.php?method=Submit
"target": "http://106.ihuyi.cn/",
"changeOrigin": true,
"headers":{
"host":"106.ihuyi.cn"
},
"pathRewrite": {
"^/V4": ""
}
};
module.exports = {
"ignoreMomentLocale": true,
"hash": true,
"theme": {
"layout-header-height": "48px",
"layout-header-background": "#fff",
"layout-footer-background": "#fff",
"layout-sider-background": '#404040',
'menu-dark-bg': '#404040',
"layout-header-padding": "0",
},
env: {
development: {
extraBabelPlugins: [
'dva-hmr',
["import", {"libraryName": "antd-mobile", "style": true}],
],
devtool: 'cheap-module-eval-source-map',
proxy: {
"/api": proxy,
"/resource": resource_proxy,
"/V4": V4_proxy,
}
},
"production": {
publicPath: "/bm/",
define: {
contextPath: "/bm",
apiContextPath: "/bm"
},
extraBabelPlugins: [
["import", { libraryName: "antd-mobile", style: "css" }]
],
}
}
};
{
"private": true,
"scripts": {
"start": "roadhog dev",
"build": "set ANALYZE=true & roadhog build",
"lint": "eslint --ext .js src test",
"precommit": "npm run lint"
},
"dependencies": {
"antd-mobile": "^2.1.6",
"dva": "^2.1.0",
"dva-react-router-3": "^1.0.2",
"lodash": "^4.17.5",
"lowdb": "^1.0.0",
"prop-types": "^15.6.1",
"react": "^16.2.0",
"react-dom": "^16.2.0",
"react-weui": "^1.1.3",
"urijs": "^1.19.1",
"weui": "^1.1.0"
},
"devDependencies": {
"babel-plugin-dva-hmr": "^0.3.2",
"babel-plugin-import": "^1.6.6",
"eslint": "^4.14.0",
"eslint-config-umi": "^0.1.1",
"eslint-plugin-flowtype": "^2.34.1",
"eslint-plugin-import": "^2.6.0",
"eslint-plugin-jsx-a11y": "^5.1.1",
"eslint-plugin-react": "^7.1.0",
"husky": "^0.12.0",
"redbox-react": "^1.4.3",
"roadhog": "^2.0.0"
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Dva Demo</title>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<div id="root"></div>
<script src="index.js"></script>
</body>
</html>
import React from 'react';
import styles from './CardViewStyles.less';
import {
Badge,
Card,
WhiteSpace,
Flex,
WingBlank,
} from 'antd-mobile';
class MyTopCard extends React.Component{
render(){
return(
<div>
<WhiteSpace size="lg" />
<Card full>
<Card.Header
title={
<div width="30px">
<span style={ {"padding-right":"15px",color:'#38c5b8'}}>总证数</span>
<span >18162</span>
</div>
}
/>
<Card.Body>
<Flex>
<Flex.Item><Badge className={styles.mybadge} text={
<div>
<span style={ {"padding-right":"15px"}}>证均成本</span>
<span >3544940.25</span>
</div>
}/></Flex.Item>
<Flex.Item><Badge text={
<div>
<span style={ {"padding-right":"15px"}}>证均成本</span>
<span >3544940.25</span>
</div>
}/></Flex.Item>
</Flex>
<Flex>
<Flex.Item><Badge text={
<div>
<span style={ {"padding-right":"15px"}}>安置房套数</span>
<span >16955</span>
</div>
}/></Flex.Item>
<Flex.Item><Badge text={
<div>
<span style={ {"padding-right":"15px"}}>面积成本</span>
<span >16955</span>
</div>
}/></Flex.Item>
</Flex>
<Flex>
<Flex.Item><Badge text={
<div>
<span style={ {"padding-right":"15px"}}>产权调换比例</span>
<span >50.35%</span>
</div>
}/></Flex.Item>
<Flex.Item><Badge text={
<div>
<span style={ {"padding-right":"15px"}}>货币补偿比例</span>
<span >3544940.25</span>
</div>
}/></Flex.Item>
</Flex>
<WhiteSpace size="lg" />
</Card.Body>
</Card>
</div>
);
}
}
export default MyTopCard;
:global .am-badge {
position: relative;
display: inline-block;
line-height: 1;
vertical-align: middle;
padding: 4px;
.am-badge-text{
padding: 5px;
background-color: #caf6f0;
color: #000000;
border: solid #fefefe 1px;
}
}
:global .am-badge-not-a-wrapper {
width:140px;
}
:global .am-card-header-extra{
float:right;
flex:0 1 auto;
}
import React from 'react';
import styles from './CardViewTwoStyles.less';
import {
Badge,
Card,
WhiteSpace,
Flex,
WingBlank,
} from 'antd-mobile';
class MyBodyCard extends React.Component{
render(){
const arrayData=this.props.data;
console.info(arrayData);
if(arrayData!==null){
return(
<div className={styles.myDiv}>
{
arrayData.map((item)=>{
return (
<div><WhiteSpace size="lg" />
<Card full>
<Card.Header
title={
<div>
<div className={styles.left}>{item.index}</div>
<div className={styles.center}><span style={ {color:'#38c5b8'}}>{item.JDName}</span></div>
</div>
}
extra={<Badge className={styles.mybadge} text={
<div>
<span style={ {"padding-right":"2px"}}>总证数</span>
<span >{item.xiangMuZongHuShu}</span>
</div>
}
/>}
/>
<Card.Body>
<Flex>
<Flex.Item><Badge className={styles.mybadgetwo} text={
<div>
<span style={ {"padding-right":"15px"}}>已签约总数</span>
<span >{item.yiQianYueHuShu}</span>
</div>
}/></Flex.Item>
<Flex.Item><Badge text={
<div>
<span style={ {"padding-right":"15px"}}>签约比例</span>
<span >3544940.25</span>
</div>
}/></Flex.Item>
</Flex>
<Flex>
<Flex.Item><Badge text={
<div>
<span style={ {"padding-right":"15px"}}>产权调换比例</span>
<span >16955</span>
</div>
}/></Flex.Item>
<Flex.Item><Badge text={
<div>
<span style={ {"padding-right":"15px"}}>货币补偿比例</span>
<span >16955</span>
</div>
}/></Flex.Item>
</Flex>
<WhiteSpace size="lg" />
</Card.Body>
</Card>
</div>
);
})
}
</div>
);
}else{
return(
<div className={styles.myDiv}>
</div>
);
}
}
}
export default MyBodyCard;
.myDiv {
span{
width: auto;
.mybadge {
sup{
background-color: red;
}
}
}
}
.left { float: left;width: 10px;}
.center{margin-left:20px;}
import React from 'react';
const Example = () => {
return (
<div>
Example
</div>
);
};
Example.propTypes = {
};
export default Example;
html, body, :global(#root) {
height: 100%;
}
import dva from 'dva';
import './index.css';
console.log('index.js');
// 1. Initialize
const app = dva();
// 2. Plugins
// app.use({});
// 3. Model
app.model(require('./models/login').default);
app.model(require('./models/Home/home').default);
// 4. Router
app.router(require('./router').default);
// 5. Start
app.start('#root');
import { getData } from '../../utils/DataTemplate';
import {login} from "../../services/login";
import {setToken} from "../../utils/auth";
export default {
namespace: 'home',
state: {
SummaryData:null,
Summary:null,
},
subscriptions: {
setup({ dispatch, history }) { // eslint-disable-line
},
},
effects: {
*getSummaryData({ payload }, { take, put, call, select }) {
const payloads = { userName:'admin',password:'admin', type: 'userName', authType: 'password' };
try{
const result = yield call(login, payloads);
console.info(result);
const { tokenId } = result;
yield call(setToken, tokenId);// 这里的yield ,跟C#中的await一样
}
catch (erroer) {
console.info(erroer);
}
const { pNumber } = payload;
const coordinate = {
containerType: 'module',
containerName: 'QueryJiDiModule',
datasourceName: 'QueryDistrictName',
};
try {
const resultss = yield call(getData, coordinate, { pst: 0, psz: 10 ,params:{pNumber:pNumber}});
console.info('查询的结果');
console.info(resultss);
yield put({ type: 'setSummaryData',payload:{resultss} });
}catch (erroer){
console.info(erroer);
}
},
*getSummary({ payload }, { take, put, call, select }) {
const payloads = { userName:'admin',password:'admin', type: 'userName', authType: 'password' };
try{
const result = yield call(login, payloads);
console.info(result);
const { tokenId } = result;
yield call(setToken, tokenId);// 这里的yield ,跟C#中的await一样
}
catch (erroer) {
console.info(erroer);
}
const { pNumber } = payload;
const coordinate = {
containerType: 'module',
containerName: 'QueryJiDiModule',
datasourceName: 'QueryJiDiName',
};
try {
const resultss = yield call(getData, coordinate, { pst: 0, psz: 10 ,params:{pNumber:pNumber}});
console.info('查询的结果');
console.info(resultss);
yield put({ type: 'setSummary',payload:{resultss} });
}catch (erroer){
console.info(erroer);
}
},
},
reducers: {
setSummaryData(state,{payload}){
return {...state,SummaryData:payload.resultss};
},
setSummary(state,{payload}){
return {...state,Summary:payload.resultss};
},
},
};
export default {
namespace: 'example',
state: {},
subscriptions: {
setup({ dispatch, history }) { // eslint-disable-line
},
},
effects: {
*fetch({ payload }, { call, put }) { // eslint-disable-line
yield put({ type: 'save' });
},
},
reducers: {
save(state, action) {
return { ...state, ...action.payload };
},
},
};
import request from "../utils/request";
import {sendMsg} from "../services/datasource";
export default {
namespace: 'login',
state: {
telnum:null,
RadomNumber:123456,
errormsg: null,
showToptips: false,
},
subscriptions: {
setup({ dispatch, history }) { // eslint-disable-line
},
},
effects: {
*fetch({ payload }, { call, put }) { // eslint-disable-line
yield put({ type: 'save' });
},
*checkNumber({ payload }, { call, put ,select}) { // eslint-disable-line
const { telnum,RadomNumber } = yield select(state => state.login);
const postData=`account=cf_proland&password=proland2015&mobile=${telnum}&content=您的验证码是:${RadomNumber}。请不要把验证码泄露给其他人。`;
console.info(this)
yield call(sendMsg,postData);
},
},
reducers: {
setShowToptips(state,{payload}){
return {...state,showToptips:payload.ShowToptips,errormsg:payload.errormsg};
},
setTelnum(state,{payload}){
return {...state,telnum:payload.telNum};
}
},
};
import React from 'react';
import { BrowserRouter, Route, Switch } from 'dva/router';
import dynamic from 'dva/dynamic';
function RouterConfig({ history, app }) {
const IndexPage = dynamic({
app,
component: () => import('./routes/IndexPage'),
});
const HomePage = dynamic({
app,
component: () => import('./routes/Home/HomePage'),
}) ;
return (
<BrowserRouter>
<div>
<Route path="/" exact component={IndexPage} />
<Route path="/Home" exact component={HomePage} />
</div>
</BrowserRouter>
);
}
export default RouterConfig;
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import MyTopCard from '../../components/CardViewOne';
import {
Cell,
Select,
Page,
Badge,
CellBody,
} from 'react-weui';
//import styles
import 'weui';
import 'react-weui/build/packages/react-weui.css';
import styles from '../IndexPage.css';
import MyBodyCard from "../../components/CardViewTwo";
class HomePage extends React.Component{
componentWillMount() {
const { dispatch } = this.props;
dispatch({ type: 'home/getSummaryData',payload: { pNumber:'浦东新区' }});
}
render(){
return (
<Page>
<span className={styles.myspan}>
<Select data={[
{
value: '杨浦区',
label: '杨浦区'
},
{
value: '浦东新区',
label: '浦东新区'
},
{
value: '徐汇区',
label: '徐汇区'
}
]}/>
</span>
<MyTopCard/>
<MyBodyCard data={this.props.home.SummaryData}/>
</Page>
);
};
}
HomePage.propTypes = {
home: PropTypes.object,
};
// 指定订阅数据,这里关联了 login
function mapStateToProps({ home }) {
return {home};
}
export default connect(mapStateToProps)(HomePage);
.styleDiv {
width: 100%;
height: 70px;
line-Height: 70px;
}
.styleImg {
margin-Left: 10px;
margin-Right: 10px;
}
table.mytable {
width: 100%;
border-collapse: collapse;
border: 1px solid #000;
}
table.mytable td{
border-collapse: collapse;
border: 1px solid #000;
}
h1.myTitle{
text-align: center;
}
span.myspan{
vertical-align:middle;
display:block;
background-color: #38c5b8;
margin:0px;
z-index:1;
}
select {
/*Chrome和Firefox里面的边框是不一样的,所以复写了一下*/
/*很关键:将默认的select选择框样式清除*/
appearance:none;
-moz-appearance:none;
-webkit-appearance:none;
text-align:right ;
/*在选择框的最右侧中间显示小箭头图片*/
background: url(../assets/downselect.png) no-repeat scroll right center transparent;
/*为下拉小箭头留出一点位置,避免被文字覆盖*/
padding-right: 14px;
direction: rtl;
}
select option {
direction: ltr;
}
/*清除ie的默认选择框样式清除,隐藏下拉箭头*/
select::-ms-expand { display: none; }
.card {
box-shadow:
0 4px 8px 0 rgba(0, 0, 0, 0.2),
0 6px 20px 0 rgba(0, 0, 0, 0.19);
margin-top: 10px;
margin-bottom: 10px;
}
.header {
border-bottom:1px solid #e4e4e4;
padding: 0px;
font-size: 14px;
}
.body p {
margin-left:
5px;
}
.myBadge{
background-color:#caf6f0 ;
color:#000000;
}
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import {
ButtonArea,
CellHeader,
Button,
CellBody,
CellFooter,
Form,
FormCell,
Input,
Label,
Toptips,
Page,
Footer,
FooterText,
Icon
} from 'react-weui';
//import styles
import 'weui';
import 'react-weui/build/packages/react-weui.css';
import styles from './IndexPage.css';
class IndexPage extends React.Component{
//手机号判断
telCheck=(event)=>{
const tel=event.target.value;
console.log(tel);
var reg=/^1[34578]\d{9}$/;
if(reg.test(tel)==false){
this.props.dispatch({ type: 'login/setShowToptips', payload: { ShowToptips:true,errormsg:"请输入正确的手机号" } });
window.setTimeout(e=> this.props.dispatch({ type: 'login/setShowToptips', payload: { ShowToptips:false } }), 2000)
}else{
this.props.dispatch({ type: 'login/setTelnum', payload: { telNum:tel } });
}
};
//发送验证码
sendCheckNum = () => {
// 1.检验改手机号是否存在系统中,如果不存在,无法注册
this.props.dispatch({type:'login/checkNumber',payload:{}})
//2.如果手机号存在,发送验证码
const PostUrl = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
};
render(){
return (
<Page>
<h1 className={styles.myTitle}>上海征地房屋补偿</h1>
<Form>
<FormCell>
<CellHeader>
<Label>手机号</Label>
</CellHeader>
<CellBody>
<Icon value="warn" />
<Input type="tel" placeholder="输入手机号码" onBlur={(event)=>this.telCheck(event)}/>
</CellBody>
</FormCell>
<FormCell vcode>
<CellHeader>
<Label>验证码</Label>
</CellHeader>
<CellBody>
<Input type="tel" placeholder=""/>
</CellBody>
<CellFooter>
<Button type="vcode" onClick={this.sendCheckNum}>发送</Button>
</CellFooter>
</FormCell>
</Form>
<ButtonArea>
<Button
//button to display toptips
onClick={ e=> {
if(this.props.login.showToptips) return;
this.props.dispatch({ type: 'login/setShowToptips', payload: { ShowToptips:true,errormsg:"用户名有误" } });
window.setTimeout(e=> this.props.dispatch({ type: 'login/setShowToptips', payload: { ShowToptips:false } }), 2000)
}
}>
注册
</Button>
</ButtonArea>
<Footer>
<FooterText>
Copyright © 2017-2018 www.proland.org.cn
</FooterText>
</Footer>
<Toptips type="warn"
show={this.props.login.showToptips}
>
{this.props.login.errormsg}
</Toptips>
</Page>
);
};
}
IndexPage.propTypes = {
login: PropTypes.object,
};
// 指定订阅数据,这里关联了 login
function mapStateToProps({ login }) {
return {login};
}
export default connect(mapStateToProps)(IndexPage);
import request from '../utils/request';
import config from '../utils/config';
export async function countTasks(filters = []) {
return request(`${config.apiContextPath}/api/bpm/task/all/count`, filters);
}
export async function fetchTasks({ pst, psz, filters }) {
const queryParams = [...filters];
queryParams.push(['pst', pst]);
queryParams.push(['psz', psz]);
return request(`${config.apiContextPath}/api/bpm/task/all/info`, queryParams);
}
import { mapKeys, toPairs, isUndefined, isString, partial } from 'lodash';
import request from '../utils/request';
import post from '../utils/post';
import { normParams } from '../utils/http-helper';
import { split } from '../utils/filter';
import config from '../utils/config';
const parseFilters = filtersIn => (filtersIn || []).filter(({ filter }) => !!filter).map(({ key, filter }) => [
split(key, false).map(value => `f-${value}`).join('|'),
filter,
]);
export const datasourceApi = (coordinate) => {
const { containerType, containerName, datasourceName } = isString(coordinate) ? {
containerType: 'global',
moduleName: coordinate,
} : (coordinate || {});
if (containerType === 'global') {
return {
query: partial(calcGlobalDatasource, datasourceName),
count: partial(countGlobalDatasource, datasourceName),
cursor: partial(cursorGlobalDatasource, datasourceName),
meta: partial(getGlobalDatasourceMeta, datasourceName),
update: partial(updateGlobalDatasource, datasourceName),
create: partial(createGlobalDatasource, datasourceName),
remove: partial(removeGlobalDatasource, datasourceName),
validateUpdate: partial(validateUpdateGlobalDatasource, datasourceName),
validateCreate: partial(validateCreateGlobalDatasource, datasourceName),
validateRemove: partial(validateRemoveGlobalDatasource, datasourceName),
};
} else if (containerType === 'module') {
return {
query: partial(calcModuleDatasource, containerName, datasourceName),
count: partial(countModuleDatasource, containerName, datasourceName),
cursor: partial(cursorModuleDatasource, containerName, datasourceName),
meta: partial(getModuleDatasourceMeta, containerName, datasourceName),
update: partial(updateModuleDatasource, containerName, datasourceName),
create: partial(createModuleDatasource, containerName, datasourceName),
remove: partial(removeModuleDatasource, containerName, datasourceName),
validateUpdate: partial(validateUpdateModuleDatasource, containerName, datasourceName),
validateCreate: partial(validateCreateModuleDatasource, containerName, datasourceName),
validateRemove: partial(validateRemoveModuleDatasource, containerName, datasourceName),
};
} else {
throw new Error(`Unsupported containerType: ${containerType}`);
}
};
const makeQueryParams = ({ pst, psz, filters = [], sortBys = [], sortTypes = [], params = {} }) => {
let stBy = sortBys.join(',');
stBy = stBy || undefined;
let stType = sortTypes.join(',');
stType = stType || undefined;
return [
...toPairs({ pst, psz, stBy, stType }),
...parseFilters(filters),
...normParams(mapKeys(params, (v, k) => `p-${k}`)),
].filter(v => v && !isUndefined((v[1])));
};
const makeParams = (otherParams, { filters = [], sortBys = [], sortTypes = [], params = {} }) => {
return [
...toPairs(otherParams),
...makeQueryParams({ filters, sortBys, sortTypes, params }),
].filter(v => v && !isUndefined((v[1])));
};
export async function calcGlobalDatasource(name, { pst, psz, filters = [], sortBys = [], sortTypes = [], params = {}, dmPath }) {
return request(`${config.apiContextPath}/api/datasource/${name}`, makeParams({ pst, psz, dmPath }, { filters, sortBys, sortTypes, params }));
}
export async function countGlobalDatasource(name, { filters = [], params = {}, dmPath }) {
return request(`${config.apiContextPath}/api/datasource/${name}/count`, makeParams({ dmPath }, { filters, params }));
}
export async function cursorGlobalDatasource(name, key, params = {}, dmPath) {
return request(`${config.apiContextPath}/api/datasource/${name}/cursor`, makeParams({ key, dmPath }, { params }));
}
export async function validateUpdateGlobalDatasource(name, key, params = {}, dmPath) {
return request(`${config.apiContextPath}/api/datasource/${name}/update/validate`, makeParams({ key, dmPath }, { params }));
}
export async function updateGlobalDatasource(name, key, params = {}, dmPath) {
return post(`${config.apiContextPath}/api/datasource/${name}/update`, {
key,
params,
dmPath,
});
}
export async function validateCreateGlobalDatasource(name, params = {}, dmPath) {
return request(`${config.apiContextPath}/api/datasource/${name}/create/validate`, makeParams({ dmPath }, { params }));
}
export async function createGlobalDatasource(name, params = {}, dmPath) {
return post(`${config.apiContextPath}/api/datasource/${name}/create`, {
params,
dmPath,
});
}
export async function validateRemoveGlobalDatasource(name, key, params = {}, dmPath) {
return request(`${config.apiContextPath}/api/datasource/${name}/remove/validate`, makeParams({ key, dmPath }, { params }));
}
export async function removeGlobalDatasource(name, key, params = {}, dmPath) {
return post(`${config.apiContextPath}/api/datasource/${name}/remove`, {
key,
params,
dmPath,
});
}
export async function getGlobalDatasourceMeta(name) {
return request(`${config.apiContextPath}/api/datasource/${name}/meta`);
}
export async function calcModuleDatasource(mdName, dsName, { pst, psz, filters = [], sortBys = [], sortTypes = [], params = {}, dmPath }) {
return request(`${config.apiContextPath}/api/module/user/${mdName}/datasource/${dsName}`, makeParams({ pst, psz, dmPath }, { filters, sortBys, sortTypes, params }));
}
export async function countModuleDatasource(mdName, dsName, { filters = [], params = {}, dmPath }) {
return request(`${config.apiContextPath}/api/module/user/${mdName}/datasource/${dsName}/count`, makeParams({ dmPath }, { filters, params }));
}
export async function cursorModuleDatasource(mdName, dsName, key, params = {}, dmPath) {
return request(`${config.apiContextPath}/api/module/user/${mdName}/datasource/${dsName}/cursor`, makeParams({ key, dmPath }, { params }));
}
export async function validateUpdateModuleDatasource(mdName, dsName, key, params = {}, dmPath) {
return request(`${config.apiContextPath}/api/module/user/${mdName}/datasource/${dsName}/update/validate`, makeParams({ key, dmPath }, { params }));
}
export async function updateModuleDatasource(mdName, dsName, key, params = {}, dmPath) {
return post(`${config.apiContextPath}/api/module/user/${mdName}/datasource/${dsName}/update`, {
key,
params,
dmPath,
});
}
export async function validateCreateModuleDatasource(mdName, dsName, params = {}, dmPath) {
return request(`${config.apiContextPath}/api/module/user/${mdName}/datasource/${dsName}/create/validate`, makeParams({ dmPath }, { params }));
}
export async function createModuleDatasource(mdName, dsName, params = {}, dmPath) {
return post(`${config.apiContextPath}/api/module/user/${mdName}/datasource/${dsName}/create`, {
params,
dmPath,
});
}
export async function validateRemoveModuleDatasource(mdName, dsName, key, params = {}, dmPath) {
return request(`${config.apiContextPath}/api/module/user/${mdName}/datasource/${dsName}/remove/validate`, makeParams({ key, dmPath }, { params }));
}
export async function removeModuleDatasource(mdName, dsName, key, params = {}, dmPath) {
return post(`${config.apiContextPath}/api/module/user/${mdName}/datasource/${dsName}/remove`, {
key,
params,
dmPath,
});
}
export async function getModuleDatasourceMeta(mdName, dsName) {
return request(`${config.apiContextPath}/api/module/user/${mdName}/datasource/${dsName}/meta`);
}
export async function getUserFromV4(params = {}) {
return request(`${config.apiContextPath}/`);
}
export async function sendMsg(data) {
return post(`${config.apiContextPath}/V4/webservice/sms.php`,data,{method:'Submit'});
}
/* eslint-disable no-param-reassign */
import request from '../utils/request';
import post from '../utils/post';
import config from '../utils/config';
import { getDomain, histories } from '../utils/auth';
export async function fetchDomains(basePath, withRoot = false) {
if (!basePath) {
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 });
let infoList;
if (rootDomainInfo && childrenDomainInfoList) {
infoList = [
rootDomainInfo,
...childrenDomainInfoList,
];
} else if (rootDomainInfo) {
infoList = [rootDomainInfo];
} else if (childrenDomainInfoList) {
infoList = childrenDomainInfoList;
} else {
infoList = [];
}
return infoList;
}
export async function switchDomain(path) {
await post(`${config.apiContextPath}/api/domain/user/path`, { dmPath: path });
histories.pushHistory('domain', path);
}
export async function currentDomain() {
return request(`${config.apiContextPath}/api/domain/user/info`);
}
import request from '../utils/request';
export function query() {
return request('/api/users');
}
import request from '../utils/request';
import post from '../utils/post';
import doDelete from '../utils/delete';
import config from '../utils/config';
export const userApi = {
async getAllInterfaceInfoes() {
return request(`${config.apiContextPath}/api/interface/user/info`);
},
async getInterfaceInfo(name) {
return request(`${config.apiContextPath}/api/interface/user/${encodeURIComponent(name)}/info`);
},
async validateState(name, dmPath) {
return request(`${config.apiContextPath}/api/interface/user/${encodeURIComponent(name)}/invoke/validateState`, { dmPath });
},
async invokeInterface(name, params, dmPath) {
return post(`${config.apiContextPath}/api/interface/user/${encodeURIComponent(name)}/invoke`, { params, dmPath });
},
};
export const adminApi = {
async getAllInterfaceInfoes(dmPath) {
return request(`${config.apiContextPath}/api/interface/admin/info`, { dmPath });
},
async getInterfaceInfo(name, dmPath) {
return request(`${config.apiContextPath}/api/interface/admin/${encodeURIComponent(name)}/info`, { dmPath });
},
async getInterfaceConfigure(name, dmPath) {
return request(`${config.apiContextPath}/api/interface/admin/${encodeURIComponent(name)}/configure`, { dmPath });
},
async getInterfacePlainConfigure(name, dmPath) {
return request(`${config.apiContextPath}/api/interface/admin/${encodeURIComponent(name)}/plainConfigure`, { dmPath });
},
async getInterfacePlainConfigures(dmPath) {
return request(`${config.apiContextPath}/api/interface/admin/plainConfigures`, { dmPath });
},
async setInterfaceConfigure(name, configure, dmPath) {
return post(`${config.apiContextPath}/api/interface/admin/${encodeURIComponent(name)}/configure`, { configure, dmPath });
},
async setInterfaceConfigures(configure, dmPath) {
return post(`${config.apiContextPath}/api/interface/admin/configures`, { configure, dmPath });
},
async removeInterfaceConfigure(name, dmPath) {
return doDelete(`${config.apiContextPath}/api/interface/admin/${encodeURIComponent(name)}/configure`, { dmPath });
},
};
import post from '../utils/post';
import request from '../utils/request';
import config from '../utils/config';
export async function login(payload) {
const data = {};
data.type = payload.type;
if (data.type === 'userName') {
data.data = payload.userName;
}
if (payload.authType === 'password') {
data.authRequest = {
type: payload.authType,
parameters: {
cipher: payload.password,
},
};
}
data.tokenInfo = {
productId: config.productId,
deviceId: `122112`,
};
return post(`${config.apiContextPath}/api/auth/login`, data, {}, {}, false);
}
export async function userInfo() {
return request(`${config.apiContextPath}/api/user/info`);
}
export async function logout() {
return post(`${config.apiContextPath}/api/auth/logout`);
}
/* eslint-disable no-param-reassign */
/** @module services/login */
import { getDeviceId } from '../../utils/device';
import post from '../../utils/post';
import request from '../../utils/request';
import { encrypt } from '../../utils/helper';
import { getToken } from '../../utils/auth';
import config from '../../utils/config';
/**
* @typedef {Object} TokenInfo
* @property {number} [life]
* @property {boolean} [persist]
* @property {!string} productId
* @property {!string} deviceId
*/
/**
* @typedef {Object} LoginRequest
* @property {!string} type
* @property {string} [data]
* @property {TokenInfo} [tokenInfo]
* @property {AuthRequest} [authRequest]
*/
/**
* @typedef {Object} AuthRequest
* @property {!string} type
* @property {Object} [parameters]
*/
/**
* @typedef {Object} LoginResponse
* @property {!string} tokenId
* @property {?AuthResponse} authResponse
* @property {!AuthRequirements} remainedAuthRequirements
*/
/**
* @typedef {Object} AuthResponse
* @property {!string} type
* @property {!string} status
* @property {?Object} data
*/
/**
* @typedef {Object} AuthRequirements
* @property {Array.<AuthRequirement>} requirements
*/
/**
* @typedef {Object} AuthRequirement
* @property {Array.<string>} authTypes
*/
/**
* 登录
* @param {!LoginRequest} loginRequest 登录请求
* @returns {Promise.<LoginResponse>}
*/
export async function login(loginRequest) {
if (!loginRequest.tokenInfo) {
loginRequest.tokenInfo = {
productId: config.productId,
deviceId: `${getDeviceId()}`,
};
}
return post(`${config.apiContextPath}/api/auth/login`, loginRequest, {}, {}, false);
}
/**
* 认证
* @param {{tkId: ?string, request: AuthRequest}} authRequest 认证请求
* @return {Promise.<AuthResponse>}
*/
export async function authorize(authRequest) {
if (!authRequest.tkId) {
authRequest.tkId = encrypt(await getToken());
}
return post(`${config.apiContextPath}/api/auth/authorize`, authRequest, {}, {}, false);
}
export async function userInfo() {
return request(`${config.apiContextPath}/api/user/info`);
}
import { addToken } from './utils';
export const validate = async (password, token) => {
const request = {
type: 'password',
parameters: {
cipher: password,
},
};
return addToken(request, token);
};
import { addToken } from './utils';
export const requestCode = async (token) => {
const request = {
type: 'uca',
parameters: {
action: 'request',
},
};
return addToken(request, token);
};
export const validate = async (signed, token) => {
const request = {
type: 'uca',
parameters: {
action: 'validate',
response: signed,
},
};
return addToken(request, token);
};
import { getToken } from '../../utils/auth';
export const addToken = async (request, token) => {
if (token) {
return {
tkId: token,
request,
};
} else {
let tkId;
const localToken = await getToken();
if (localToken) {
// eslint-disable-next-line no-param-reassign
tkId = localToken;
}
if (tkId) {
return {
tkId,
request,
};
} else {
return {
request,
};
}
}
};
import post from '../utils/post';
import config from '../utils/config';
export async function logout() {
return post(`${config.apiContextPath}/api/auth/logout`);
}
import request from '../utils/request';
import config from '../utils/config';
export async function fetchMenus() {
return request(`${config.apiContextPath}/api/configure/user/menus`);
}
export async function fetchModuleInfos() {
return request(`${config.apiContextPath}/api/module/user/info`);
}
export async function fetchModuleLayout(name) {
return request(`${config.apiContextPath}/api/module/user/${name}/layout`);
}
import post from '../utils/post';
import doDelete from '../utils/delete';
import config from '../utils/config';
import request from '../utils/request';
import { getToken } from '../utils/auth';
import { encrypt } from '../utils/helper';
import { errors } from '../utils/error';
export class Operations {
constructor() {
this.operations = [];
}
addCmd = (cmd, ...args) => {
this.operations.push({ cmd, args });
return this;
};
setName = (name) => {
return this.addCmd('setName', name);
};
setRight = (right) => {
return this.addCmd('setRight', right);
};
addTags = (...tags) => {
return this.addCmd('addTags', ...tags);
};
removeTags = (...tags) => {
return this.addCmd('removeTags', ...tags);
};
clearTags = () => {
return this.addCmd('clearTags');
};
setTags = (...tags) => {
return this.addCmd('setTags', ...tags);
};
addOwners = (...owners) => {
return this.addCmd('addOwners', ...owners);
};
removeOwners = (...owners) => {
return this.addCmd('removeOwners', ...owners);
};
clearOwners = () => {
return this.addCmd('clearOwners');
};
setOwners = (...owners) => {
return this.addCmd('setOwners', ...owners);
};
addOwnerGroups = (...groups) => {
return this.addCmd('addOwnerGroups', ...groups);
};
removeOwnerGroups = (...groups) => {
return this.addCmd('removeOwnerGroups', ...groups);
};
clearOwnerGroups = () => {
return this.addCmd('clearOwnerGroups');
};
setOwnerGroups = (...groups) => {
return this.addCmd('setOwnerGroups', ...groups);
};
use = (usage) => {
return this.addCmd('use', usage);
};
unuse = (usage) => {
return this.addCmd('unuse', usage);
};
}
export class Query {
constructor() {
this.pageSize = -1;
}
setAfter = (after) => {
this.after = after;
};
/**
* create_time: 创建时间,
* media_type: 媒体类型,比如application/pdf,
* size: 文件大小,
* name: 文件名称,
* modify_time: 上一次修改时间,
* uri: 资源定位符
*/
setOrder = () => {
const argn = arguments.length;
if (argn > 0) {
this.orders = [];
let lastOrder;
for (let i = 0; i < argn; ++i) {
if (lastOrder !== undefined && (typeof arguments[i] === 'boolean')) {
this.orders.push({
target: lastOrder,
asc: arguments[i],
});
lastOrder = undefined;
} else if (lastOrder !== undefined) {
this.orders.push({
target: lastOrder,
asc: true,
});
lastOrder = arguments[i];
} else {
lastOrder = arguments[i];
}
}
if (lastOrder !== undefined) {
this.orders.push({
target: lastOrder,
asc: true,
});
}
}
};
setPageSize = (size) => {
this.pageSize = size >= 0 ? size : -1;
};
setCondition = (condition) => {
this.condition = condition;
};
setStores = (...stores) => {
this.stores = stores;
};
static tag = (...tags) => {
if (tags.length === 0) {
throw new Error('At least one tag!');
}
if (tags.length === 1) {
return {
type: 'tag',
value: tags[0],
};
} else {
return Query.and(...tags.map(tag => Query.tag(tag)));
}
};
static usage = (...usage) => {
if (usage.length === 0) {
throw new Error('At least one usage!');
}
if (usage.length === 1) {
return {
type: 'usage',
value: usage[0],
};
} else {
return Query.and(...usage.map(tag => Query.usage(tag)));
}
};
static and = (...conditions) => {
return {
type: 'and',
conditions,
};
};
static or = (...conditions) => {
return {
type: 'or',
conditions,
};
};
}
export const createOperations = () => {
return new Operations();
};
export async function editResource(uri, operations) {
return post(`${config.apiContextPath}/api/resource/user/${encodeURIComponent(uri)}/meta`, { operations: operations.operations });
}
export async function deleteResource(uri) {
return doDelete(await rsLink(uri));
}
export async function countResource(query) {
return post(`${config.apiContextPath}/api/resource/user/count`, query);
}
export async function queryResource(query) {
return post(`${config.apiContextPath}/api/resource/user/query`, query);
}
export async function getResourceInfo(uri) {
return request(`${config.apiContextPath}/api/resource/user/${encodeURIComponent(uri)}/meta`);
}
export async function rsLink(uri, download = false) {
const token = await getToken();
if (!token) {
throw errors.tokenMissing();
}
return `${config.apiContextPath}/resource/${encrypt(token)}/${encodeURIComponent(uri)}${download ? '?dl=true' : ''}`;
}
import { browserHistory } from 'dva-react-router-3/router';
import resolvePathname from 'resolve-pathname';
import { isString } from 'lodash';
import config from '../utils/config';
const { contextPath } = config;
const makePath = (base, path, withContext = true) => {
if (path.startsWith('/')) {
return withContext ? `${contextPath}${path}` : path;
}
const basePath = base.endsWith('/') ? base : `${base}/`;
return resolvePathname(path, basePath);
};
const processPath = (base, path, withContext = true) => {
if (isString(path)) {
return makePath(base, path, withContext);
}
return {
...path,
pathname: makePath(base, path.pathname, withContext),
};
};
const getHistoryBase = (history) => {
if (history.location) {
return history.location.pathname;
} else {
return location.pathname;
}
};
export const history = browserHistory;
export const location = {};
history.listen((loc) => {
location.pathname = loc.pathname;
location.state = loc.state;
location.search = loc.search;
location.hash = loc.hash;
});
export const push = (path, state, withContext = true) => {
return history.push(processPath(getHistoryBase(history), path, withContext), state);
};
export const replace = (path, state, withContext = true) => {
return history.replace(processPath(getHistoryBase(history), path, withContext), state);
};
export const go = (n) => {
return history.go(n);
};
export const goBack = () => {
return history.goBack();
};
export const goForward = () => {
return history.goForward();
};
const checkThis = (theThis) => {
if (!theThis || !theThis.props) {
throw new Error('The this is not a component.');
}
if (!theThis.props.router) {
throw new Error('please use withRouter.');
}
};
const getThisBase = (theThis) => {
if (theThis.props.location) {
return theThis.props.location.pathname;
} else if (typeof window !== 'undefined') {
return window.location.pathname; // eslint-disable-line no-undef
} else {
throw new Error('can not find base path!');
}
};
export const thisPush = (theThis, pathOrLoc, withContext = true) => {
checkThis(theThis);
const route = processPath(getThisBase(theThis), pathOrLoc, withContext);
return theThis.props.router.push(route);
};
export const thisReplace = (theThis, pathOrLoc, withContext = true) => {
checkThis(theThis);
const route = processPath(getThisBase(theThis), pathOrLoc, withContext);
return theThis.props.router.replace(route);
};
export const thisGo = (theThis, n) => {
checkThis(theThis);
return theThis.props.router.go(n);
};
export const thisGoBack = (theThis) => {
checkThis(theThis);
return theThis.props.router.goBack();
};
export const thisGoForward = (theThis) => {
checkThis(theThis);
return theThis.props.router.goForward();
};
import _, { partial } from 'lodash';
import request from '../utils/request';
import post from '../utils/post';
import doDelete from '../utils/delete';
import config from '../utils/config';
// noinspection JSUnusedGlobalSymbols
export const templateApi = (dmPath) => {
return {
admin: {
getInfo: partial(getAdminTemplateInfo, _, dmPath),
getAllInfoes: partial(getAllAdminTemplateInfoes, dmPath),
getConfigure: partial(getAdminTemplateConfigure, _, dmPath),
getPlainConfigure: partial(getAdminTemplatePlainConfigure, _, dmPath),
setConfigure: partial(setAdminTemplateConfigure, _, _, dmPath),
removeConfigure: partial(removeAdminTemplateConfigure, _, dmPath),
getTemplate: partial(getAdminTemplateTemplate, _, dmPath),
setTemplate: partial(setAdminTemplateTemplate, _, _, dmPath),
render: partial(adminRender, _, _, _, dmPath),
},
};
};
export async function getAllAdminTemplateInfoes(dmPath) {
return request(`${config.apiContextPath}/api/template/admin/info`, { dmPath });
}
export async function getAdminTemplateInfo(name, dmPath) {
return request(`${config.apiContextPath}/api/template/admin/${encodeURIComponent(name)}/info`, { dmPath });
}
export async function getAdminTemplateConfigure(name, dmPath) {
return request(`${config.apiContextPath}/api/template/admin/${encodeURIComponent(name)}/configure`, { dmPath });
}
export async function getAdminTemplatePlainConfigure(name, dmPath) {
return request(`${config.apiContextPath}/api/template/admin/${encodeURIComponent(name)}/plainConfigure`, { dmPath });
}
export async function setAdminTemplateConfigure(name, configure, dmPath) {
return post(`${config.apiContextPath}/api/template/admin/${encodeURIComponent(name)}/configure`, { configure, dmPath });
}
export async function removeAdminTemplateConfigure(name, dmPath) {
return doDelete(`${config.apiContextPath}/api/template/admin/${encodeURIComponent(name)}/configure`, { dmPath });
}
export async function setAdminTemplateTemplate(name, uri, dmPath) {
return post(`${config.apiContextPath}/api/template/admin/${encodeURIComponent(name)}/template`, { uri, dmPath });
}
export async function getAdminTemplateTemplate(name, dmPath) {
return request(`${config.apiContextPath}/api/template/admin/${encodeURIComponent(name)}/template`, { dmPath });
}
export async function adminRender(name, params, mediaType, dmPath) {
return post(`${config.apiContextPath}/api/template/admin/${encodeURIComponent(name)}/render`, { dmPath, mediaType, params });
}
import request from '../../utils/request';
import post from '../../utils/post';
import config from '../../utils/config';
export const auditLegacyEntities = async () => {
return post(`${config.apiContextPath}/api/tools/envers/audit-legacy-entities`);
};
export const getEnversTaskStatus = async () => {
return request(`${config.apiContextPath}/api/tools/envers/audit-legacy-entities/status`);
};
import post from '../utils/post';
import config from '../utils/config';
export const bindCert = async (uid, cert) => {
return post(`${config.apiContextPath}/api/uca/admin/cert`, { uid, cert });
};
/** @module services/update */
import DeviceInfo from 'react-native-device-info';
import post from '../utils/post';
import { encrypt } from '../utils/helper';
import config from '../utils/config';
/**
* @typedef {Object} DeploymentInfo 部署信息
* @property {number} id 部署id
* @property {string} versionNumber 版本号
* @property {string} description 描述,一般为更新说明
* @property {Date} updateTime 部署发布时间
* @property {string} uri 资源内部uri,表示app安装包文件的内部定位地址
* @property {string} status 部署状态,可能值为release,development,broken。release表示公开版本,development表示内部测试版,broken表示有重大bug,短时间不能解决,需要回滚
*/
/**
* @typedef {Object} VersionCheck 升级检查结果
* @property {string} tokenId 更新服务器所使用的tokenId
* @property {string} action 可能值分别为update(可更新),rollback(需回滚),upToDate(已经是最新版,无需更新)
* @property {DeploymentInfo} deploymentInfo 需更新或回滚的部署包信息
*/
/**
* 升级检查
* @returns {Promise.<VersionCheck>}
*/
export const checkUpdate = async () => {
const { tokenId } = await post(`${config.updateContextPath}/api/auth/login`, {
type: 'quest',
authRequest: {
type: 'quest',
},
tokenInfo: {
productId: config.productId,
deviceId: `${DeviceInfo.getUniqueID()}`,
},
}, {}, {}, false);
const result = await post(`${config.updateContextPath}/api/app/user/apps/check`, {
name: config.productId,
version: DeviceInfo.getVersion(),
token: encrypt(tokenId),
}, {}, {}, false);
result.tokenId = tokenId;
return result;
};
import { partial } from 'lodash';
import request from '../utils/request';
import post from '../utils/post';
import config from '../utils/config';
export const userApi = (id) => {
return {
admin: {
getConfigure: partial(getUserConfigure, id),
setConfigure: partial(setUserConfigure, id),
refresh: partial(refreshUser, id),
},
};
};
export const roleApi = (id) => {
return {
admin: {
getConfigure: partial(getRoleConfigure, id),
setConfigure: partial(setRoleConfigure, id),
refresh: partial(refreshRole, id),
},
};
};
export async function getUserConfigure(id) {
return request(`${config.apiContextPath}/api/user/admin/user/${id}/configure`);
}
export async function setUserConfigure(id, configure) {
return post(`${config.apiContextPath}/api/user/admin/user/${id}/configure`, { configure });
}
export async function refreshUser(id) {
return post(`${config.apiContextPath}/api/user/admin/user/${id}/refresh`);
}
export async function getRoleConfigure(id) {
return request(`${config.apiContextPath}/api/user/admin/role/${id}/configure`);
}
export async function setRoleConfigure(id, configure) {
return post(`${config.apiContextPath}/api/user/admin/role/${id}/configure`, { configure });
}
export async function refreshRole(id) {
return post(`${config.apiContextPath}/api/user/admin/role/${id}/refresh`);
}
import _ from 'lodash';
import { datasourceApi } from '../services/datasource';
export const getData = async (coordinate, { pst, psz, params = {}, filters = [], sortBys = [], sortTypes = [] }) => {
const options = { pst, psz, params, filters, sortBys, sortTypes };
const api = datasourceApi(coordinate);
const meta = await api.meta();
const dsb = await api.query(options);
return getArrayData(dsb, meta);
};
export const getMeta = async (coordinate) => {
const api = datasourceApi(coordinate);
const meta = await api.meta();
return makeColumns(meta);
};
const parseMetas = (metas) => {
const ret = {};
if (!metas) {
return ret;
}
_.forEach(metas, (value, key) => {
let finalValue;
try {
finalValue = JSON.parse(value);
} catch (err) {
finalValue = value;
}
_.set(ret, key, finalValue);
});
return _.pickBy(ret, _.negate(_.isUndefined));
};
const makeColumns = (meta) => {
return (meta.properties || [])
.filter(property => !property.skip)
.map((property) => {
const props = parseMetas(property.metas);
if (!props.title && props.label) {
props.title = props.label;
}
if (props.order === undefined) {
props.order = 0;
}
if ((props.fixed === true || props.fixed === 'left' || props.fixed === 'right') && props.width === undefined) {
props.width = 150;
}
return _.pickBy({
...props,
key: property.name,
required: property.required,
}, _.negate(_.isUndefined));
})
.filter(c => c.visible !== false);
};
// const tmp = async(ddd) => {
// await
// }
// function abc() {
//
// for (cont a of b) {
// await a()
// }
// getData().then((r) => {
//
// }).catch(err => {
//
// })
// }
const getArrayData = ({ dataType, arrayData, singularData }, meta) => {
if (dataType === 'TABLE') {
const data = (arrayData || []).map(() => ({}));
(meta.properties || [])
.filter(property => !property.skip)
.forEach((property, i) => {
data.forEach((row, j) => {
row[property.name] = arrayData[j][i]; // eslint-disable-line no-param-reassign
});
});
return data;
} else if (dataType === 'PROPERTIES') {
const data = [];
(meta.properties || [])
.filter(property => !property.skip)
.forEach((property) => {
data.push((singularData || {})[property.name]);
});
return [_.toPlainObject(data)];
} else {
throw new Error(`Unsupported data type: ${dataType}`);
}
};
/* eslint-disable no-param-reassign */
/**
* Created by yaohx_169 on 2017/6/8.
*/
import { cookie } from './config';
import { getCookie, setCookie, delCookie } from './helper';
import db from './db';
export async function getToken() {
return getCookie(cookie.token);
}
export async function setToken(token) {
setCookie(cookie.token, token);
}
export async function delToken() {
delCookie(cookie.token);
}
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);
}
const normHistory = (history, size) => {
if (!history) {
history = {};
}
if (!history.size) {
if (size) {
history.size = size;
} else {
history.size = 10;
}
} else if (size && history.size !== size) {
history.size = size;
}
if (history.size < 1) {
history.size = 1;
}
if (!history.data) {
history.data = [];
history.start = 0;
history.top = 0;
history.empty = true;
}
return history;
};
const next = (i, size) => {
if (i < 0 || i >= size) {
throw new Error(`out of range: ${i} in ${size}`);
}
if (i + 1 >= size) {
return 0;
} else {
return i + 1;
}
};
const prev = (i, size) => {
if (i < 0 || i >= size) {
throw new Error(`out of range: ${i} in ${size}`);
}
if (i - i < 0) {
return size - 1;
} else {
return i - 1;
}
};
export const histories = {
async getLatest(name) {
let history = await db.get(`history.${name}`).value();
history = normHistory(history);
if (history.empty) {
return null;
}
return history.data[prev(history.top, history.size)];
},
async createHistory(name, size) {
let history = db.get(`history.${name}`).value();
history = normHistory(history, size);
return db.set(`history.${name}`, history).write();
},
async destroyHistory(name) {
return db.unset(`history.${name}`).write();
},
async getHistory(name, size) {
let history = db.get(`history.${name}`).value();
history = normHistory(history, size);
if (history.empty) {
return [];
} else if (history.top > history.start) {
return history.data.slice(history.start, history.top);
} else {
return [...history.data.slice(history.start, history.size), ...history.data.slice(0, history.top)];
}
},
async pushHistory(name, value, size) {
let history = await db.get(`history.${name}`).value();
history = normHistory(history, size);
history.data[history.top] = value;
const nextPos = next(history.top, history.size);
if (!history.empty && history.start === history.top) {
history.top = history.start = nextPos;
} else {
history.top = nextPos;
}
if (history.empty) {
history.empty = false;
}
return db.set(`history.${name}`, history).write();
},
async popHistory(name) {
let history = await db.get(`history.${name}`).value();
history = normHistory(history);
if (history.empty) {
return;
}
history.top = prev(history.top, history.size);
if (history.top === history.start) {
history.empty = true;
}
return db.set(`history.${name}`, history).write();
},
async init() {
return db.read();
},
};
/* eslint-disable no-undef */
/**
* Created by yaohx_169 on 2017/6/6.
*/
export const cookie = {
token: 'token',
userId: 'userId',
userName: 'userName',
domainPath: 'domainPath',
domainName: 'domainName',
};
export const errors = {
exception: 0x00010000,
no_such_user: 0x00010001,
wrong_password: 0x00010002,
invalid_token: 0x00010003,
invalid_query_param: 0x00010004,
domain_not_set: 0x00010005,
wrong_sms_code: 0x00010006,
sms_code_time_out: 0x00010007,
invalid_mobile: 0x00010008,
no_operation_right: 0x00010100,
no_module_right: 0x00010101,
no_interface_right: 0x00010102,
no_batch_right: 0x00010103,
no_resource_right: 0x00010104,
no_domain_right: 0x00010105,
no_datasource_right: 0x00010106,
general_error: 0x00011111,
// client error:
token_missing: 0x00000001,
unsupported_auth_type: 0x00000003,
auth_failed: 0x00000004,
};
export const api = {
userLogin: '/user/login',
userLogout: '/user/logout',
userInfo: '/userInfo',
users: '/users',
user: '/user/:id',
dashboard: '/dashboard',
};
const defaultDateFormat = 'YYYY-MM-DD';
const defaultTimeFormat = 'HH:mm:ss';
const defaultDateTimeFormat = `${defaultDateFormat} ${defaultTimeFormat}`;
// eslint-disable-next-line no-underscore-dangle
const _apiContextPath = process.env.NODE_ENV === 'development' ? '' : apiContextPath;
// eslint-disable-next-line no-underscore-dangle
const _contextPath = process.env.NODE_ENV === 'development' ? '' : contextPath;
const config = {
name: 'Jbpm Demo',
footerText: '上海铂蓝信息科技有限公司',
logo: `${_contextPath}/logo.png`,
contextPath: _contextPath,
apiContextPath: _apiContextPath,
productId: 'big-machine-web-front',
fastNavigationPage: '',
defaultDateFormat,
defaultTimeFormat,
defaultDateTimeFormat,
pubKey: '-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+/Rs6dYmdtETjHCZq4LF3QjLM/DocRAXrqtMULZf+579dAn+CiM8noLplZT/DRwvfK822eq8sypH+a4NqP7942pPVjOudVvKfiJvmm2TOQHvQ7vi3iyZVdlsxX72JNFo1Ocqwj48aIC/OJ4bMf/VyCKrmKrU2iXND+I4BN8cfhwIDAQAB-----END PUBLIC KEY-----',
};
export default config;
/** @module utils/db */
import low from 'lowdb';
import LocalStorage from 'lowdb/adapters/LocalStorage';
const adapter = new LocalStorage('db');
/**
* @typedef {Object} DB
* @template {T}
*/
/**
* @member {Function} DB~get
* @param {Array.<string>|string} path
* @param {*} [defaultValue]
* @return {DB.<*>}
*/
/**
* @member {Function} DB~set
* @param {Array.<string>|string} path
* @param value
* @return {DB}
*/
/**
* @member {Function} DB~find
* @template {T}
* @param {Function} [predicate=_.identity]
* @param {number} [fromIndex=0]
* @return {DB.<T>}
*/
/**
* @member {Function} DB~unset
* @param {Array.<string>|string} path
* @return {DB.<boolean>}
*/
/**
* @member {Function} DB~read
* @return {Promise.<*>}
*/
/**
* @member {Function} DB~write
* @return {Promise.<*>}
*/
/**
* @member {Function} DB~value
* @template {T}
* @return {Promise.<T>}
*/
/**
* @type {DB.<*>}
*/
const db = low(adapter);
export default db;
/* eslint-disable no-param-reassign */
import { isNil, defaults } from 'lodash';
import { fetch } from './polyfill';
import { checkStatus, normParams, parseObject } from './http-helper';
import middleware from './middleware';
const defaultOptions = {
headers: { Accept: 'application/json' },
};
/**
* Requests a URL, returning a promise.
*
* @param {string} url The URL we want to delete
* @param auth
* @param params
* @param {object} [options] The options we want to pass to "fetch"
* @return {object} An object containing either "data" or "err"
*/
export default async function doDelete(url, params = {}, options = {}, auth = true) {
params = normParams(params);
const res = await middleware.delete.onRequest(url, params, options, auth);
let queryParams = (res ? res.params : params).map(([k, v]) => (isNil(v) ? k : `${k}=${encodeURIComponent(v)}`));
queryParams = queryParams.join('&');
let realUrl = res ? res.url : url;
if (queryParams) {
realUrl = `${url}?${queryParams}`;
}
const realOptions = defaults(res ? res.options : options, defaultOptions);
realOptions.method = 'DELETE';
return fetch(realUrl, realOptions)
.then(checkStatus)
.then(resp => parseObject(resp, middleware.delete.onResponse));
}
import Fingerprint from 'fingerprintjs';
export function getDeviceId() {
// noinspection JSUnresolvedFunction
return new Fingerprint({ ie_activex: true }).get();
}
/* eslint-disable no-param-reassign,prefer-rest-params */
/**
* Created by yaohx_169 on 2017/5/10.
*/
/*
* 添加事件处理程序
* @param object object 要添加事件处理程序的元素
* @param string type 事件名称,如click
* @param function handler 事件处理程序,可以直接以匿名函数的形式给定,或者给一个已经定义的函数名。匿名函数方式给定的事件处理程序在IE6 IE7 IE8中可以移除,在标准浏览器中无法移除。
* @param boolean remove 是否是移除的事件,本参数是为简化下面的removeEvent函数而写的,对添加事件处理程序不起任何作用
*/
export function addEvent(object, type, handler, remove) {
if (typeof object !== 'object' || typeof handler !== 'function') return;
try {
object[remove ? 'removeEventListener' : 'addEventListener'](type, handler, false);
} catch (e) {
const xc = `_${type}`;
object[xc] = object[xc] || [];
if (remove) {
const l = object[xc].length;
for (let i = 0; i < l; i++) {
if (object[xc][i].toString() === handler.toString()) object[xc].splice(i, 1);
}
} else {
const l = object[xc].length;
let exists = false;
for (let i = 0; i < l; i++) {
if (object[xc][i].toString() === handler.toString()) exists = true;
}
if (!exists) object[xc].push(handler);
}
object[`on${type}`] = function cb() {
const l = object[xc].length;
for (let i = 0; i < l; i++) {
object[xc][i].apply(object, arguments);
}
};
}
}
/*
* 移除事件处理程序
*/
export function removeEvent(object, type, handler) {
addEvent(object, type, handler, true);
}
import React from 'react';
import { push } from '../services/route';
import { errors as errorCodes } from './config';
const errStyle = {
overflow: 'auto',
wordWrap: 'break-word',
width: '360px',
height: '360px',
marginLeft: '-24px',
marginTop: '24px',
};
export function processError(err) {
if (err) {
if (err.data && err.data.errorCode) {
const data = err.data;
switch (data.errorCode) {
case errorCodes.no_such_user:
//message.error('用户不存在!');
break;
case errorCodes.invalid_token:
case errorCodes.token_missing:
push('/login');
break;
default:
showError(err);
}
} else if (err instanceof Error) {
showError(err);
}
}
}
function showError(err) {
if (err) {
if (err.data && err.data.errorCode) {
let msg;
if (err.data) {
const data = err.data;
msg = data ? data.message : err.message;
} else {
msg = err.message;
}
if (msg && msg.length < 256) {
//essage.error(msg);
} else {
// Modal.error({
// title: '服务器内部错误',
// content: <div style={errStyle}>{msg}</div>,
// width: 460,
// });
}
} else if (err instanceof Error) {
// Modal.error({
// title: '错误!',
// content: (
// <div style={errStyle}>
// <p>{err.message ? err.message : ''}</p>
// <p>{err.stack ? err.stack : ''}</p>
// </div>
// ),
// width: 460,
// });
}
}
}
export function createError({ code, msg }) {
const error = new Error(msg);
error.data = {
errorCode: code,
message: msg,
};
return error;
}
export const errors = {
tokenMissing: () => createError({
code: errorCodes.token_missing,
msg: '需要登录!',
}),
wrongPassword: () => createError({
code: errorCodes.wrong_password,
msg: '密码错误!',
}),
authFailed: msg => createError({
code: errorCodes.auth_failed,
msg: `登录验证失败!${msg || ''}`,
}),
unsupportedAuthType: (...types) => createError({
code: errorCodes.unsupported_auth_type,
msg: `不支持的客户端验证方式:${types.join('、')}.`,
}),
generalError: msg => createError({
code: errorCodes.general_error,
msg: `${msg || '未知错误。'}`,
}),
};
const findSep = (value, offset = 0) => {
const find = value.indexOf('|', offset);
if (find !== -1) {
let count = 0;
let from = find;
while (value[--from] === '#') ++count;
if ((count & 1) === 1) {
return findSep(value, find + 1);
} else {
return find;
}
} else {
return -1;
}
};
const transform = (value) => {
const find = value.indexOf('#');
if (find !== -1) {
const left = value.slice(0, find);
const me = value[find + 1] ? value[find + 1] : '';
const right = value.slice(find + 2);
return `${left}${me}${transform(right)}`;
} else {
return value;
}
};
export const split = (value, unescape = true) => {
const ret = [];
let offset = 0;
let posSep = -1;
do {
posSep = findSep(value, offset);
if (posSep !== -1) {
if (unescape) {
ret.push(transform(value.slice(offset, posSep)));
} else {
ret.push(value.slice(offset, posSep));
}
offset = posSep + 1;
}
} while (posSep !== -1);
if (unescape) {
ret.push(transform(value.slice(offset)));
} else {
ret.push(value.slice(offset));
}
return ret;
};
import moment from 'moment';
import _ from 'lodash';
import { createJSEncrypt } from './jsencrypt';
import config from './config';
const { contextPath, pubKey } = config;
export function setCookie(name, value, options = {}) {
const { path, domain, expires } = options;
if (name) {
const expireSet = expires ? ` expires=${moment().add(expires, 'ms').toDate().toUTCString()};` : '';
const domainSet = domain ? ` domain=${domain};` : '';
const pathSet = path ? ` path=${path};` : ' path=/';
const valueSet = value ? `${name}=${encodeURIComponent(value)};` : '';
document.cookie = `${valueSet}${expireSet}${domainSet};${pathSet}`; // eslint-disable-line
}
}
export function getCookie(name) {
const reg = new RegExp(`(^|)${name}=([^;]*)(;|$)`, 'g');
const arr = document.cookie.match(reg); // eslint-disable-line
if (arr) {
let value = arr.map(v => v.substring(`${name}=`.length).trim()).filter(v => !!v).pop();
if (value.endsWith(';')) {
value = value.substring(0, value.length - 1);
}
return decodeURIComponent(value);
} else {
return null;
}
}
export function delCookie(name, { domain, path } = {}) {
if (getCookie(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
}
}
export function setLocalStorge(key, value) {
return localStorage.setItem(key, JSON.stringify(value)); // eslint-disable-line
}
export function getLocalStorge(key) {
return JSON.parse(localStorage.getItem(key)); // eslint-disable-line
}
export function delLocalStorge(key) {
return localStorage.removeItem(key); // eslint-disable-line
}
export function locationOrigin(withContext = true) {
return `${location.protocol}//${location.hostname}${location.port ? ':' + location.port : ''}${withContext ? contextPath : ''}`; // eslint-disable-line
}
export function currentPath() {
let path = location.pathname; // eslint-disable-line
if (!path) {
path = '/';
}
if (path[0] !== '/') {
path = `/${path}`;
}
if (path.slice(0, contextPath.length) === contextPath) {
return path.slice(contextPath.length);
} else {
return '/';
}
}
export function fullPath(path) {
return `${contextPath}${path}`;
}
export function encrypt(text) {
const jsEncrypt = createJSEncrypt();
jsEncrypt.setPublicKey(pubKey);
let out = jsEncrypt.encryptLong(text);
out = out.split('=')[0];
out = out.replace(/\+/g, '-');
return out.replace(/\//g, '_');
}
/**
* @param name {String}
* @return {String}
*/
export function queryURL(name) {
const reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, 'i');
// eslint-disable-next-line no-undef
const r = window ? window.location.search.substr(1).match(reg) : null;
if (r !== null) return decodeURI(r[2]);
return null;
}
export function padDigits(number, digits) {
return new Array(Math.max(digits - String(number).length + 1, 0)).join('0') + number;
}
export function is(obj, type) {
return (type === 'Null' && obj === null) ||
(type === 'Undefined' && obj === void 0) || // eslint-disable-line no-void
(type === 'Number' && Number.isFinite(obj)) ||
Object.prototype.toString.call(obj).slice(8, -1) === type;
}
export function makePromise0(thunk) {
return new Promise((resolve) => {
thunk(data => resolve(data));
});
}
export function makePromise1(thunk) {
return new Promise((resolve, reject) => {
thunk(err => reject(err), data => resolve(data));
});
}
export function filterValidParams(params) {
return _.pickBy(params, _.negate(_.isUndefined));
}
import _ from 'lodash';
import { Resolver } from 'fastjson_ref_resolver';
export function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
}
return response.json().then((data) => {
const error = new Error(data.message ? data.message : response.statusText);
error.data = data;
throw error;
});
}
export function normParams(unnormed) {
if (_.isPlainObject(unnormed)) {
return _(unnormed).toPairs().flatMap(([k, v]) => (_.isArray(v) ? v.map(vv => [k, vv]) : [[k, v]])).value();
} else {
return unnormed;
}
}
// eslint-disable-next-line max-len
export function parseObject(response, middleware, { num2str = false, bool2str = false, nul2str = false, ud2str = false, nil2str = false } = {}) {
if (response.status === 204) { // no-content
return null;
} else {
const contentType = response.headers.get('content-type');
if (contentType) {
const needMap = num2str || bool2str || nul2str || ud2str || nil2str;
const mapStr = (value) => {
if (num2str && _.isNumber(value)) {
return value.toString();
}
if (bool2str && _.isBoolean(value)) {
return value.toString();
}
if (nul2str && _.isNull(value)) {
return '';
}
if (ud2str && _.isUndefined(value)) {
return '';
}
if (nil2str && _.isNil(value)) {
return '';
}
return value;
};
const mapObj = (obj, mapArrFunc) => {
if (_.isArray(obj)) {
return mapArrFunc(obj, mapObj);
}
if (_.isPlainObject(obj)) {
return _.mapValues(obj, (val) => {
const ret = mapStr(val);
return mapObj(ret, mapArrFunc);
});
}
return obj;
};
const mapArr = (arr, mapObjFunc) => {
if (_.isPlainObject(arr)) {
return mapObjFunc(arr, mapArr);
}
if (_.isArray(arr)) {
return _.map(arr, (val) => {
const ret = mapStr(val);
return mapArr(ret, mapObjFunc);
});
}
return arr;
};
const mapValue = _.curry(mapObj)(_, mapArr);
if (contentType.indexOf('json') !== -1) {
return response.json()
.then((json) => {
let out = json;
if (_.isObjectLike(out)) {
out = new Resolver(out).resolve();
}
return middleware ? middleware(out) : out;
})
.then((data) => {
return needMap ? mapValue(data) : data;
});
} else if (contentType.indexOf('xml') !== -1) {
return response.text()
.then((text) => {
return require.ensure([], (require) => {
const { parseString } = require('xml2js');
const options = {};
return JSON.parse(parseString(text, options));
});
})
.then((json) => {
let out = json;
if (_.isObjectLike(out)) {
out = new Resolver(out).resolve();
}
return middleware ? middleware(out) : out;
})
.then((data) => {
return needMap ? mapValue(data) : data;
});
} else if (contentType.indexOf('text') !== -1) {
return response.text();
} else {
throw new Error(`Unsupported response content type: ${contentType}`);
}
} else {
throw new Error('No response content type.');
}
}
}
export { NavigationActions } from 'react-navigation';
export const delay = time => new Promise(resolve => setTimeout(resolve, time));
export const createAction = type => payload => ({ type, payload });
/* eslint-disable */
var b64map="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var b64padchar="=";
function hex2b64(h) {
var i;
var c;
var ret = "";
for(i = 0; i+3 <= h.length; i+=3) {
c = parseInt(h.substring(i,i+3),16);
ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63);
}
if(i+1 == h.length) {
c = parseInt(h.substring(i,i+1),16);
ret += b64map.charAt(c << 2);
}
else if(i+2 == h.length) {
c = parseInt(h.substring(i,i+2),16);
ret += b64map.charAt(c >> 2) + b64map.charAt((c & 3) << 4);
}
while((ret.length & 3) > 0) ret += b64padchar;
return ret;
}
// convert a base64 string to hex
function b64tohex(s) {
var ret = ""
var i;
var k = 0; // b64 state, 0-3
var slop;
for(i = 0; i < s.length; ++i) {
if(s.charAt(i) == b64padchar) break;
v = b64map.indexOf(s.charAt(i));
if(v < 0) continue;
if(k == 0) {
ret += int2char(v >> 2);
slop = v & 3;
k = 1;
}
else if(k == 1) {
ret += int2char((slop << 2) | (v >> 4));
slop = v & 0xf;
k = 2;
}
else if(k == 2) {
ret += int2char(slop);
ret += int2char(v >> 2);
slop = v & 3;
k = 3;
}
else {
ret += int2char((slop << 2) | (v >> 4));
ret += int2char(v & 0xf);
k = 0;
}
}
if(k == 1)
ret += int2char(slop << 2);
return ret;
}
// convert a base64 string to a byte/number array
function b64toBA(s) {
//piggyback on b64tohex for now, optimize later
var h = b64tohex(s);
var i;
var a = new Array();
for(i = 0; 2*i < h.length; ++i) {
a[i] = parseInt(h.substring(2*i,2*i+2),16);
}
return a;
}
差异被折叠。
/* eslint-disable no-unused-vars,camelcase */
// prng4.js - uses Arcfour as a PRNG
function Arcfour() {
this.i = 0;
this.j = 0;
this.S = [];
}
// Initialize arcfour context from key, an array of ints, each from [0..255]
function ARC4init(key) {
let i;
let j;
let t;
for (i = 0; i < 256; ++i) { this.S[i] = i; }
j = 0;
for (i = 0; i < 256; ++i) {
j = (j + this.S[i] + key[i % key.length]) & 255;
t = this.S[i];
this.S[i] = this.S[j];
this.S[j] = t;
}
this.i = 0;
this.j = 0;
}
function ARC4next() {
this.i = (this.i + 1) & 255;
this.j = (this.j + this.S[this.i]) & 255;
const t = this.S[this.i];
this.S[this.i] = this.S[this.j];
this.S[this.j] = t;
return this.S[(t + this.S[this.i]) & 255];
}
Arcfour.prototype.init = ARC4init;
Arcfour.prototype.next = ARC4next;
// Plug in your RNG constructor here
function prng_newstate() {
return new Arcfour();
}
// Pool size must be a multiple of 4 and greater than 32.
// An array of bytes the size of the pool will be passed to init()
const rng_psize = 256;
/* eslint-disable */
// Random number generator - requires a PRNG backend, e.g. prng4.js
// For best results, put code like
// <body onClick='rng_seed_time();' onKeyPress='rng_seed_time();'>
// in your main HTML document.
import './prng4';
var rng_state;
var rng_pool;
var rng_pptr;
// Mix in a 32-bit integer into the pool
function rng_seed_int(x) {
rng_pool[rng_pptr++] ^= x & 255;
rng_pool[rng_pptr++] ^= (x >> 8) & 255;
rng_pool[rng_pptr++] ^= (x >> 16) & 255;
rng_pool[rng_pptr++] ^= (x >> 24) & 255;
if(rng_pptr >= rng_psize) rng_pptr -= rng_psize;
}
// Mix in the current time (w/milliseconds) into the pool
function rng_seed_time() {
rng_seed_int(new Date().getTime());
}
// Initialize the pool with junk if needed.
if(rng_pool == null) {
rng_pool = new Array();
rng_pptr = 0;
var t;
if(window.crypto && window.crypto.getRandomValues) {
// Use webcrypto if available
var ua = new Uint8Array(32);
window.crypto.getRandomValues(ua);
for(t = 0; t < 32; ++t)
rng_pool[rng_pptr++] = ua[t];
}
if(navigator.appName == "Netscape" && navigator.appVersion < "5" && window.crypto) {
// Extract entropy (256 bits) from NS4 RNG if available
var z = window.crypto.random(32);
for(t = 0; t < z.length; ++t)
rng_pool[rng_pptr++] = z.charCodeAt(t) & 255;
}
while(rng_pptr < rng_psize) { // extract some randomness from Math.random()
t = Math.floor(65536 * Math.random());
rng_pool[rng_pptr++] = t >>> 8;
rng_pool[rng_pptr++] = t & 255;
}
rng_pptr = 0;
rng_seed_time();
//rng_seed_int(window.screenX);
//rng_seed_int(window.screenY);
}
function rng_get_byte() {
if(rng_state == null) {
rng_seed_time();
rng_state = prng_newstate();
rng_state.init(rng_pool);
for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr)
rng_pool[rng_pptr] = 0;
rng_pptr = 0;
//rng_pool = null;
}
// TODO: allow reseeding after first request
return rng_state.next();
}
function rng_get_bytes(ba) {
var i;
for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte();
}
function SecureRandom() {}
SecureRandom.prototype.nextBytes = rng_get_bytes;
/* eslint-disable */
// Depends on jsbn.js and rng.js
// Version 1.1: support utf-8 encoding in pkcs1pad2
import './jsbn';
import './rng';
import './base64';
const stringToUtf8ByteArray = (str) => {
// TODO(user): Use native implementations if/when available
const out = [];
let p = 0;
for (let i = 0; i < str.length; i++) {
let c = str.charCodeAt(i);
if (c < 128) {
out[p++] = c;
} else if (c < 2048) {
out[p++] = (c >> 6) | 192;
out[p++] = (c & 63) | 128;
} else if (
((c & 0xFC00) === 0xD800) && (i + 1) < str.length &&
((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) {
// Surrogate Pair
c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF);
out[p++] = (c >> 18) | 240;
out[p++] = ((c >> 12) & 63) | 128;
out[p++] = ((c >> 6) & 63) | 128;
out[p++] = (c & 63) | 128;
} else {
out[p++] = (c >> 12) | 224;
out[p++] = ((c >> 6) & 63) | 128;
out[p++] = (c & 63) | 128;
}
}
return out;
};
// convert a (hex) string to a bignum object
function parseBigInt(str,r) {
return new BigInteger(str,r);
}
function linebrk(s,n) {
var ret = "";
var i = 0;
while(i + n < s.length) {
ret += s.substring(i,i+n) + "\n";
i += n;
}
return ret + s.substring(i,s.length);
}
function byte2Hex(b) {
if(b < 0x10)
return "0" + b.toString(16);
else
return b.toString(16);
}
function str2blocks(s, n) {
const bytes = stringToUtf8ByteArray(s);
const blocks = [];
const blockSize = n - 11;
for (let i = 1; i * blockSize < bytes.length; ++i) {
blocks.push(pkcs1pad(bytes.slice((i - 1) * blockSize, i * blockSize), n));
}
return blocks;
}
function pkcs1pad(block, n) {
const out = block;
out.push(0);
const rng = new SecureRandom();
const x = [];
const rSize = n - out.length - 3;
for (let i = 0; i < rSize; ++i) {
x[0] = 0;
while(x[0] === 0) rng.nextBytes(x);
out.push(x[0]);
}
out.push(2);
out.push(0);
return new BigInteger(out);
}
// PKCS#1 (type 2, random) pad input string s to n bytes, and return a bigint
function pkcs1pad2(s,n) {
if(n < s.length + 11) { // TODO: fix for utf-8
alert("Message too long for RSA");
return null;
}
var ba = new Array();
var i = s.length - 1;
while(i >= 0 && n > 0) {
var c = s.charCodeAt(i--);
if(c < 128) { // encode using utf-8
ba[--n] = c;
}
else if((c > 127) && (c < 2048)) {
ba[--n] = (c & 63) | 128;
ba[--n] = (c >> 6) | 192;
}
else {
ba[--n] = (c & 63) | 128;
ba[--n] = ((c >> 6) & 63) | 128;
ba[--n] = (c >> 12) | 224;
}
}
ba[--n] = 0;
var rng = new SecureRandom();
var x = new Array();
while(n > 2) { // random non-zero pad
x[0] = 0;
while(x[0] == 0) rng.nextBytes(x);
ba[--n] = x[0];
}
ba[--n] = 2;
ba[--n] = 0;
return new BigInteger(ba);
}
// "empty" RSA key constructor
function RSAKey() {
this.n = null;
this.e = 0;
this.d = null;
this.p = null;
this.q = null;
this.dmp1 = null;
this.dmq1 = null;
this.coeff = null;
}
// Set the public key fields N and e from hex strings
function RSASetPublic(N,E) {
if(N != null && E != null && N.length > 0 && E.length > 0) {
this.n = parseBigInt(N,16);
this.e = parseInt(E,16);
}
else
alert("Invalid RSA public key");
}
// Perform raw public operation on "x": return x^e (mod n)
function RSADoPublic(x) {
return x.modPowInt(this.e, this.n);
}
// Return the PKCS#1 RSA encryption of "text" as an even-length hex string
function RSAEncrypt(text) {
var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3);
if(m == null) return null;
var c = this.doPublic(m);
if(c == null) return null;
var h = c.toString(16);
if((h.length & 1) == 0) return h; else return "0" + h;
}
function RSAEncryptLongText(text) {
const blocks = str2blocks(text, (this.n.bitLength()+7)>>3);
const out = [];
for (let i = 0; i < blocks.length; ++ i) {
const c = this.doPublic(blocks[i]);
if (c == null) return null;
const h = c.toString(16);
if ((h.length & 1) === 0) {
out.push(h);
} else {
out.push(`0${h}`);
}
}
return out.join('');
}
// Return the PKCS#1 RSA encryption of "text" as a Base64-encoded string
//function RSAEncryptB64(text) {
// var h = this.encrypt(text);
// if(h) return hex2b64(h); else return null;
//}
// protected
RSAKey.prototype.doPublic = RSADoPublic;
// public
RSAKey.prototype.setPublic = RSASetPublic;
RSAKey.prototype.encrypt = RSAEncrypt;
RSAKey.prototype.encryptLong = RSAEncryptLongText;
//RSAKey.prototype.encrypt_b64 = RSAEncryptB64;
export default RSAKey;
This source diff could not be displayed because it is too large. You can view the blob instead.
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论