提交 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 */
// Copyright (c) 2005 Tom Wu
// All Rights Reserved.
// See "LICENSE" for details.
// Basic JavaScript BN library - subset useful for RSA encryption.
// Bits per digit
var dbits;
// JavaScript engine analysis
var canary = 0xdeadbeefcafe;
var j_lm = ((canary&0xffffff)==0xefcafe);
// (public) Constructor
function BigInteger(a,b,c) {
if(a != null)
if("number" == typeof a) this.fromNumber(a,b,c);
else if(b == null && "string" != typeof a) this.fromString(a,256);
else this.fromString(a,b);
}
// return new, unset BigInteger
function nbi() { return new BigInteger(null); }
// am: Compute w_j += (x*this_i), propagate carries,
// c is initial carry, returns final carry.
// c < 3*dvalue, x < 2*dvalue, this_i < dvalue
// We need to select the fastest one that works in this environment.
// am1: use a single mult and divide to get the high bits,
// max digit bits should be 26 because
// max internal value = 2*dvalue^2-2*dvalue (< 2^53)
function am1(i,x,w,j,c,n) {
while(--n >= 0) {
var v = x*this[i++]+w[j]+c;
c = Math.floor(v/0x4000000);
w[j++] = v&0x3ffffff;
}
return c;
}
// am2 avoids a big mult-and-extract completely.
// Max digit bits should be <= 30 because we do bitwise ops
// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
function am2(i,x,w,j,c,n) {
var xl = x&0x7fff, xh = x>>15;
while(--n >= 0) {
var l = this[i]&0x7fff;
var h = this[i++]>>15;
var m = xh*l+h*xl;
l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff);
c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);
w[j++] = l&0x3fffffff;
}
return c;
}
// Alternately, set max digit bits to 28 since some
// browsers slow down when dealing with 32-bit numbers.
function am3(i,x,w,j,c,n) {
var xl = x&0x3fff, xh = x>>14;
while(--n >= 0) {
var l = this[i]&0x3fff;
var h = this[i++]>>14;
var m = xh*l+h*xl;
l = xl*l+((m&0x3fff)<<14)+w[j]+c;
c = (l>>28)+(m>>14)+xh*h;
w[j++] = l&0xfffffff;
}
return c;
}
if(j_lm && (navigator.appName == "Microsoft Internet Explorer")) {
BigInteger.prototype.am = am2;
dbits = 30;
}
else if(j_lm && (navigator.appName != "Netscape")) {
BigInteger.prototype.am = am1;
dbits = 26;
}
else { // Mozilla/Netscape seems to prefer am3
BigInteger.prototype.am = am3;
dbits = 28;
}
BigInteger.prototype.DB = dbits;
BigInteger.prototype.DM = ((1<<dbits)-1);
BigInteger.prototype.DV = (1<<dbits);
var BI_FP = 52;
BigInteger.prototype.FV = Math.pow(2,BI_FP);
BigInteger.prototype.F1 = BI_FP-dbits;
BigInteger.prototype.F2 = 2*dbits-BI_FP;
// Digit conversions
var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
var BI_RC = new Array();
var rr,vv;
rr = "0".charCodeAt(0);
for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv;
rr = "a".charCodeAt(0);
for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
rr = "A".charCodeAt(0);
for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
function int2char(n) { return BI_RM.charAt(n); }
function intAt(s,i) {
var c = BI_RC[s.charCodeAt(i)];
return (c==null)?-1:c;
}
// (protected) copy this to r
function bnpCopyTo(r) {
for(var i = this.t-1; i >= 0; --i) r[i] = this[i];
r.t = this.t;
r.s = this.s;
}
// (protected) set from integer value x, -DV <= x < DV
function bnpFromInt(x) {
this.t = 1;
this.s = (x<0)?-1:0;
if(x > 0) this[0] = x;
else if(x < -1) this[0] = x+this.DV;
else this.t = 0;
}
// return bigint initialized to value
function nbv(i) { var r = nbi(); r.fromInt(i); return r; }
// (protected) set from string and radix
function bnpFromString(s,b) {
var k;
if(b == 16) k = 4;
else if(b == 8) k = 3;
else if(b == 256) k = 8; // byte array
else if(b == 2) k = 1;
else if(b == 32) k = 5;
else if(b == 4) k = 2;
else { this.fromRadix(s,b); return; }
this.t = 0;
this.s = 0;
var i = s.length, mi = false, sh = 0;
while(--i >= 0) {
var x = (k==8)?s[i]&0xff:intAt(s,i);
if(x < 0) {
if(s.charAt(i) == "-") mi = true;
continue;
}
mi = false;
if(sh == 0)
this[this.t++] = x;
else if(sh+k > this.DB) {
this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh;
this[this.t++] = (x>>(this.DB-sh));
}
else
this[this.t-1] |= x<<sh;
sh += k;
if(sh >= this.DB) sh -= this.DB;
}
if(k == 8 && (s[0]&0x80) != 0) {
this.s = -1;
if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh;
}
this.clamp();
if(mi) BigInteger.ZERO.subTo(this,this);
}
// (protected) clamp off excess high words
function bnpClamp() {
var c = this.s&this.DM;
while(this.t > 0 && this[this.t-1] == c) --this.t;
}
// (public) return string representation in given radix
function bnToString(b) {
if(this.s < 0) return "-"+this.negate().toString(b);
var k;
if(b == 16) k = 4;
else if(b == 8) k = 3;
else if(b == 2) k = 1;
else if(b == 32) k = 5;
else if(b == 4) k = 2;
else return this.toRadix(b);
var km = (1<<k)-1, d, m = false, r = "", i = this.t;
var p = this.DB-(i*this.DB)%k;
if(i-- > 0) {
if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); }
while(i >= 0) {
if(p < k) {
d = (this[i]&((1<<p)-1))<<(k-p);
d |= this[--i]>>(p+=this.DB-k);
}
else {
d = (this[i]>>(p-=k))&km;
if(p <= 0) { p += this.DB; --i; }
}
if(d > 0) m = true;
if(m) r += int2char(d);
}
}
return m?r:"0";
}
// (public) -this
function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; }
// (public) |this|
function bnAbs() { return (this.s<0)?this.negate():this; }
// (public) return + if this > a, - if this < a, 0 if equal
function bnCompareTo(a) {
var r = this.s-a.s;
if(r != 0) return r;
var i = this.t;
r = i-a.t;
if(r != 0) return (this.s<0)?-r:r;
while(--i >= 0) if((r=this[i]-a[i]) != 0) return r;
return 0;
}
// returns bit length of the integer x
function nbits(x) {
var r = 1, t;
if((t=x>>>16) != 0) { x = t; r += 16; }
if((t=x>>8) != 0) { x = t; r += 8; }
if((t=x>>4) != 0) { x = t; r += 4; }
if((t=x>>2) != 0) { x = t; r += 2; }
if((t=x>>1) != 0) { x = t; r += 1; }
return r;
}
// (public) return the number of bits in "this"
function bnBitLength() {
if(this.t <= 0) return 0;
return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM));
}
// (protected) r = this << n*DB
function bnpDLShiftTo(n,r) {
var i;
for(i = this.t-1; i >= 0; --i) r[i+n] = this[i];
for(i = n-1; i >= 0; --i) r[i] = 0;
r.t = this.t+n;
r.s = this.s;
}
// (protected) r = this >> n*DB
function bnpDRShiftTo(n,r) {
for(var i = n; i < this.t; ++i) r[i-n] = this[i];
r.t = Math.max(this.t-n,0);
r.s = this.s;
}
// (protected) r = this << n
function bnpLShiftTo(n,r) {
var bs = n%this.DB;
var cbs = this.DB-bs;
var bm = (1<<cbs)-1;
var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i;
for(i = this.t-1; i >= 0; --i) {
r[i+ds+1] = (this[i]>>cbs)|c;
c = (this[i]&bm)<<bs;
}
for(i = ds-1; i >= 0; --i) r[i] = 0;
r[ds] = c;
r.t = this.t+ds+1;
r.s = this.s;
r.clamp();
}
// (protected) r = this >> n
function bnpRShiftTo(n,r) {
r.s = this.s;
var ds = Math.floor(n/this.DB);
if(ds >= this.t) { r.t = 0; return; }
var bs = n%this.DB;
var cbs = this.DB-bs;
var bm = (1<<bs)-1;
r[0] = this[ds]>>bs;
for(var i = ds+1; i < this.t; ++i) {
r[i-ds-1] |= (this[i]&bm)<<cbs;
r[i-ds] = this[i]>>bs;
}
if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<<cbs;
r.t = this.t-ds;
r.clamp();
}
// (protected) r = this - a
function bnpSubTo(a,r) {
var i = 0, c = 0, m = Math.min(a.t,this.t);
while(i < m) {
c += this[i]-a[i];
r[i++] = c&this.DM;
c >>= this.DB;
}
if(a.t < this.t) {
c -= a.s;
while(i < this.t) {
c += this[i];
r[i++] = c&this.DM;
c >>= this.DB;
}
c += this.s;
}
else {
c += this.s;
while(i < a.t) {
c -= a[i];
r[i++] = c&this.DM;
c >>= this.DB;
}
c -= a.s;
}
r.s = (c<0)?-1:0;
if(c < -1) r[i++] = this.DV+c;
else if(c > 0) r[i++] = c;
r.t = i;
r.clamp();
}
// (protected) r = this * a, r != this,a (HAC 14.12)
// "this" should be the larger one if appropriate.
function bnpMultiplyTo(a,r) {
var x = this.abs(), y = a.abs();
var i = x.t;
r.t = i+y.t;
while(--i >= 0) r[i] = 0;
for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t);
r.s = 0;
r.clamp();
if(this.s != a.s) BigInteger.ZERO.subTo(r,r);
}
// (protected) r = this^2, r != this (HAC 14.16)
function bnpSquareTo(r) {
var x = this.abs();
var i = r.t = 2*x.t;
while(--i >= 0) r[i] = 0;
for(i = 0; i < x.t-1; ++i) {
var c = x.am(i,x[i],r,2*i,0,1);
if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) {
r[i+x.t] -= x.DV;
r[i+x.t+1] = 1;
}
}
if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1);
r.s = 0;
r.clamp();
}
// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
// r != q, this != m. q or r may be null.
function bnpDivRemTo(m,q,r) {
var pm = m.abs();
if(pm.t <= 0) return;
var pt = this.abs();
if(pt.t < pm.t) {
if(q != null) q.fromInt(0);
if(r != null) this.copyTo(r);
return;
}
if(r == null) r = nbi();
var y = nbi(), ts = this.s, ms = m.s;
var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus
if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); }
else { pm.copyTo(y); pt.copyTo(r); }
var ys = y.t;
var y0 = y[ys-1];
if(y0 == 0) return;
var yt = y0*(1<<this.F1)+((ys>1)?y[ys-2]>>this.F2:0);
var d1 = this.FV/yt, d2 = (1<<this.F1)/yt, e = 1<<this.F2;
var i = r.t, j = i-ys, t = (q==null)?nbi():q;
y.dlShiftTo(j,t);
if(r.compareTo(t) >= 0) {
r[r.t++] = 1;
r.subTo(t,r);
}
BigInteger.ONE.dlShiftTo(ys,t);
t.subTo(y,y); // "negative" y so we can replace sub with am later
while(y.t < ys) y[y.t++] = 0;
while(--j >= 0) {
// Estimate quotient digit
var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2);
if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out
y.dlShiftTo(j,t);
r.subTo(t,r);
while(r[i] < --qd) r.subTo(t,r);
}
}
if(q != null) {
r.drShiftTo(ys,q);
if(ts != ms) BigInteger.ZERO.subTo(q,q);
}
r.t = ys;
r.clamp();
if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder
if(ts < 0) BigInteger.ZERO.subTo(r,r);
}
// (public) this mod a
function bnMod(a) {
var r = nbi();
this.abs().divRemTo(a,null,r);
if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r);
return r;
}
// Modular reduction using "classic" algorithm
function Classic(m) { this.m = m; }
function cConvert(x) {
if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);
else return x;
}
function cRevert(x) { return x; }
function cReduce(x) { x.divRemTo(this.m,null,x); }
function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
Classic.prototype.convert = cConvert;
Classic.prototype.revert = cRevert;
Classic.prototype.reduce = cReduce;
Classic.prototype.mulTo = cMulTo;
Classic.prototype.sqrTo = cSqrTo;
// (protected) return "-1/this % 2^DB"; useful for Mont. reduction
// justification:
// xy == 1 (mod m)
// xy = 1+km
// xy(2-xy) = (1+km)(1-km)
// x[y(2-xy)] = 1-k^2m^2
// x[y(2-xy)] == 1 (mod m^2)
// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
// JS multiply "overflows" differently from C/C++, so care is needed here.
function bnpInvDigit() {
if(this.t < 1) return 0;
var x = this[0];
if((x&1) == 0) return 0;
var y = x&3; // y == 1/x mod 2^2
y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4
y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8
y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16
// last step - calculate inverse mod DV directly;
// assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits
// we really want the negative inverse, and -DV < y < DV
return (y>0)?this.DV-y:-y;
}
// Montgomery reduction
function Montgomery(m) {
this.m = m;
this.mp = m.invDigit();
this.mpl = this.mp&0x7fff;
this.mph = this.mp>>15;
this.um = (1<<(m.DB-15))-1;
this.mt2 = 2*m.t;
}
// xR mod m
function montConvert(x) {
var r = nbi();
x.abs().dlShiftTo(this.m.t,r);
r.divRemTo(this.m,null,r);
if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r);
return r;
}
// x/R mod m
function montRevert(x) {
var r = nbi();
x.copyTo(r);
this.reduce(r);
return r;
}
// x = x/R mod m (HAC 14.32)
function montReduce(x) {
while(x.t <= this.mt2) // pad x so am has enough room later
x[x.t++] = 0;
for(var i = 0; i < this.m.t; ++i) {
// faster way of calculating u0 = x[i]*mp mod DV
var j = x[i]&0x7fff;
var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM;
// use am to combine the multiply-shift-add into one call
j = i+this.m.t;
x[j] += this.m.am(0,u0,x,i,0,this.m.t);
// propagate carry
while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; }
}
x.clamp();
x.drShiftTo(this.m.t,x);
if(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
}
// r = "x^2/R mod m"; x != r
function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
// r = "xy/R mod m"; x,y != r
function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
Montgomery.prototype.convert = montConvert;
Montgomery.prototype.revert = montRevert;
Montgomery.prototype.reduce = montReduce;
Montgomery.prototype.mulTo = montMulTo;
Montgomery.prototype.sqrTo = montSqrTo;
// (protected) true iff this is even
function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; }
// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
function bnpExp(e,z) {
if(e > 0xffffffff || e < 1) return BigInteger.ONE;
var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1;
g.copyTo(r);
while(--i >= 0) {
z.sqrTo(r,r2);
if((e&(1<<i)) > 0) z.mulTo(r2,g,r);
else { var t = r; r = r2; r2 = t; }
}
return z.revert(r);
}
// (public) this^e % m, 0 <= e < 2^32
function bnModPowInt(e,m) {
var z;
if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);
return this.exp(e,z);
}
// protected
BigInteger.prototype.copyTo = bnpCopyTo;
BigInteger.prototype.fromInt = bnpFromInt;
BigInteger.prototype.fromString = bnpFromString;
BigInteger.prototype.clamp = bnpClamp;
BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
BigInteger.prototype.drShiftTo = bnpDRShiftTo;
BigInteger.prototype.lShiftTo = bnpLShiftTo;
BigInteger.prototype.rShiftTo = bnpRShiftTo;
BigInteger.prototype.subTo = bnpSubTo;
BigInteger.prototype.multiplyTo = bnpMultiplyTo;
BigInteger.prototype.squareTo = bnpSquareTo;
BigInteger.prototype.divRemTo = bnpDivRemTo;
BigInteger.prototype.invDigit = bnpInvDigit;
BigInteger.prototype.isEven = bnpIsEven;
BigInteger.prototype.exp = bnpExp;
// public
BigInteger.prototype.toString = bnToString;
BigInteger.prototype.negate = bnNegate;
BigInteger.prototype.abs = bnAbs;
BigInteger.prototype.compareTo = bnCompareTo;
BigInteger.prototype.bitLength = bnBitLength;
BigInteger.prototype.mod = bnMod;
BigInteger.prototype.modPowInt = bnModPowInt;
// "constants"
BigInteger.ZERO = nbv(0);
BigInteger.ONE = nbv(1);
/* 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.
import _ from 'lodash';
const { isString, get, sortBy } = _;
/**
* @callback KeyExtractor
* @param value
* @return key
*/
/**
* 获取用于对比的key
* @param value
* @param {string|KeyExtractor} [keyMethod]
* @return {*}
*/
const getKey = (value, keyMethod) => {
if (!keyMethod) {
return value;
} else if (isString(keyMethod)) {
return get(value, keyMethod);
} else {
return keyMethod(value);
}
};
/**
* 在数组中查找某个对象,并返回
* @param {Array} array
* @param toFind 查找目标
* @param {string|KeyExtractor} [key] 用于判断2个数据是否相同
* @return result 找到的对象
*/
const findBy = (array, toFind, key) => {
if (array) {
for (const el of array) {
if (getKey(el, key) === toFind) {
return el;
}
}
}
return null;
};
/**
* 计算频率数据
* @param {Array} array 数据
* @param {string|KeyExtractor} [key] 用于判断2个数据是否相同
* @param {string} [order=desc] 怎么排序,可选值为asc和desc
*/
export const toHistogram = (array, key, order = 'desc') => {
if (!array || array.length === 0) {
return [];
}
const res = [];
let newKey;
if (!key) {
newKey = 'data';
} else if (isString(key)) {
newKey = `data.${key}`;
} else {
newKey = value => key(value.data);
}
for (const el of array) {
const find = findBy(res, getKey(el, key), newKey);
if (find) {
++find.num;
} else {
res.push({
data: el,
num: 1,
});
}
}
switch (order) {
case 'desc':
return _(res).sortBy(v => v.num).reverse().value();
case 'asc':
return sortBy(res, v => v.num);
default:
throw new Error(`unsupported order: ${order}`);
}
};
/* eslint-disable no-unused-vars */
import { getToken } from './auth';
import { encrypt } from './helper';
import { errors } from './error';
const putTokenOnUrl = async (url, params, options) => {
let token = await getToken();
if (!token) {
throw errors.tokenMissing();
}
token = encrypt(token);
return {
url,
options,
params: [...params, ['token', token]],
};
};
const putTokenToBody = async (url, data, params, options) => {
let token = await getToken();
if (!token) {
throw errors.tokenMissing();
}
token = encrypt(token);
return {
url,
params,
options,
data: {
token,
...data,
},
};
};
const parseResponse = (response) => {
const { errorCode, data, message } = response;
if (errorCode === 0) {
return data;
} else {
const error = new Error(message || data);
error.data = response;
throw error;
}
};
export default {
get: {
onRequest: async (url, params, options, auth) => {
if (auth) {
return putTokenOnUrl(url, params, options);
} else {
return {
url,
options,
params,
};
}
},
onResponse: parseResponse,
},
post: {
onRequest: async (url, data, params, options, auth) => {
if (auth) {
return putTokenToBody(url, data, params, options);
} else {
return {
url,
params,
options,
data,
};
}
},
onResponse: parseResponse,
},
delete: {
onRequest: async (url, params, options, auth) => {
if (auth) {
return putTokenOnUrl(url, params, options);
} else {
return {
url,
options,
params,
};
}
},
onResponse: parseResponse,
},
};
/* eslint-disable */
export const fetch = require('dva/fetch');
/* 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',
},
};
const sortBodyForToken = (keys) => {
const idxToken = keys.indexOf('token');
if (idxToken !== -1) {
if (idxToken === 0) {
return keys;
} else if (idxToken === keys.length - 1) {
return ['token', ...keys.slice(0, keys.length - 1)];
} else {
return ['token', ...keys.slice(0, idxToken), ...keys.slice(idxToken + 1)];
}
} else {
return keys;
}
};
const orderedStringify = (obj) => {
const allKeys = [];
JSON.stringify(obj, (k, v) => { allKeys.push(k); return v; });
return JSON.stringify(obj, sortBodyForToken(allKeys));
};
export default async function post(url, data, params = {}, options = {}, auth = true) {
if (!data) {
data = {};
}
params = normParams(params);
const res = await middleware.post.onRequest(url, data, params, options, auth);
let queryParams = res ? res.params : params;
queryParams = queryParams.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);
if (!realOptions.headers) {
realOptions.headers = {
Accept: 'application/json',
};
}
realOptions.headers['Content-Type'] = 'application/json';
realOptions.method = 'POST';
const body = res ? res.data : data;
realOptions.body = orderedStringify(body);
return fetch(realUrl, realOptions)
.then(checkStatus)
.then(resp => parseObject(resp, middleware.post.onResponse));
}
export const makeCancelable = (promise, silence = true) => {
let hasCanceled = false;
const canceledError = { isCanceled: true };
const wrappedPromise = new Promise((resolve, reject) => {
promise.then(
val => (hasCanceled ? reject(canceledError) : resolve(val)),
error => (hasCanceled ? reject(canceledError) : reject(error)),
);
});
return {
run: cb => cb(wrappedPromise).catch((err) => {
if (silence && err !== canceledError) {
throw err;
}
}),
cancel() {
hasCanceled = true;
},
};
};
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 request
* @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 request(url, params = {}, options = {}, auth = true) {
const normedParams = normParams(params);
const res = await middleware.get.onRequest(url, normedParams, options, auth);
const newUrl = res ? res.url : url;
const newParams = res ? res.params : normedParams;
const newOptions = res ? res.options : options;
let queryParams = newParams.map(([k, v]) => (isNil(v) ? k : `${k}=${encodeURIComponent(v)}`));
queryParams = queryParams.join('&');
let realUrl = newUrl;
if (queryParams) {
realUrl = `${url}?${queryParams}`;
}
return fetch(realUrl, defaults(newOptions, defaultOptions))
.then(checkStatus)
.then(resp => parseObject(resp, middleware.get.onResponse));
}
export function years(value) {
return [
'y', value,
];
}
export function quarters(value) {
return [
'Q', value,
];
}
export function months(value) {
return [
'M', value,
];
}
export function weeks(value) {
return [
'w', value,
];
}
export function days(value) {
return [
'd', value,
];
}
export function hours(value) {
return [
'h', value,
];
}
export function minutes(value) {
return [
'm', value,
];
}
export function seconds(value) {
return [
's', value,
];
}
export function milliseconds(value) {
return [
'ms', value,
];
}
import AXO from 'axo';
import bowser from 'bowser';
export const isBrowserSupport = () => {
return bowser.msie;
};
/**
* 初始化
* @return {number} 0: success; 1: blocked by the browser; 2: driver not installed
*/
export const init = () => {
if (bowser.msie) {
try {
const se = new AXO('SafeEngineCOM.SafeEngineCtl');
if (se) {
return 0;
} else {
return 2;
}
} catch (err) {
return 1;
}
} else {
return 3;
}
};
/**
* 获取证书
* @param password usb-key的密钥
* @return {{[cert]: string, [deadTime]: number, status: number, [error]: string}}
*/
export const getCert = (password) => {
if (bowser.msie) {
const safeEngine = new AXO('SafeEngineCOM.SafeEngineCtl');
if (!safeEngine) {
return {
status: 1,
input: password,
error: '未安装USB证书控件。',
};
}
safeEngine.SEH_InitialSession(27, 'com1', password, 100, 2, '', '');
if (safeEngine.ErrorCode !== 0) {
return {
status: safeEngine.ErrorCode,
input: password,
error: 'USB-KEY初始化失败,请确认USB-KEY是否插入或密码是否正确。',
};
}
try {
const cert = safeEngine.SEH_GetSelfCertificate(27, 'com1', '');
if (safeEngine.ErrorCode !== 0) {
return {
status: safeEngine.ErrorCode,
input: password,
error: `获取个人证书错误,错误代码为:${safeEngine.ErrorCode}。`,
};
}
const res = {
status: 0,
cert,
input: password,
};
const deadTime = safeEngine.SEH_GetCertValidDate(cert);
res.deadTime = parseInt(deadTime, 10);
return res;
} finally {
safeEngine.SEH_ClearSession();
}
} else {
return {
status: 1,
error: '当前浏览器不支持activeX控件,请切换ie或带ie内核的360之类的浏览器。',
};
}
};
/**
* 签名
* @param password usb-key的密钥
* @param data 需要签名的数据,从服务端获取
* @return {{input: string, [cert]: string, [deadTime]: number, [signed]: string, status: number, [error]: string}}
*/
export const sign = (password, data) => {
if (bowser.msie || bowser.msedge) {
const safeEngine = new AXO('SafeEngineCOM.SafeEngineCtl');
if (!safeEngine) {
return {
status: 1,
input: password,
error: '未安装USB证书控件。',
};
}
safeEngine.SEH_InitialSession(27, 'com1', password, 100, 2, '', '');
if (safeEngine.ErrorCode !== 0) {
return {
status: safeEngine.ErrorCode,
input: password,
error: 'USB-KEY初始化失败,请确认USB-KEY是否插入或密码是否正确。',
};
}
try {
const cert = safeEngine.SEH_GetSelfCertificate(27, 'com1', '');
if (safeEngine.ErrorCode !== 0) {
return {
status: safeEngine.ErrorCode,
input: password,
error: `获取个人证书错误,错误代码为:${safeEngine.ErrorCode}。`,
};
}
const res = { cert, status: 0, input: password };
const deadTime = safeEngine.SEH_GetCertValidDate(cert);
res.deadTime = parseInt(deadTime, 10);
const signed = safeEngine.SEH_SignData(data, 3);
if (safeEngine.ErrorCode !== 0) {
return {
status: safeEngine.ErrorCode,
input: password,
error: `数字签名失败,错误代码为:${safeEngine.ErrorCode}。`,
};
}
res.signed = signed;
return res;
} finally {
safeEngine.SEH_ClearSession();
}
} else {
return {
status: 1,
error: '当前浏览器不支持activeX控件,请切换ie或带ie内核的360之类的浏览器。',
};
}
};
module.exports = function webpack(config) {
return config;
};
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论