util.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. const app = getApp();
  2. const appConfig = require("../config")
  3. const Encrypt = require("../js/jsencrypt")
  4. function http_build_query(formdata, numeric_prefix, arg_separator) {
  5. var value, key, tmp = [],
  6. that = this;
  7. var _http_build_query_helper = function (key, val, arg_separator) {
  8. var k, tmp = [];
  9. if (val === true) {
  10. val = '1';
  11. } else if (val === false) {
  12. val = '0';
  13. }
  14. if (val != null) {
  15. if (typeof val === 'object') {
  16. for (k in val) {
  17. if (val[k] != null) {
  18. tmp.push(_http_build_query_helper(key + '[' + k + ']', val[k], arg_separator));
  19. }
  20. }
  21. return tmp.join(arg_separator);
  22. } else if (typeof val !== 'function') {
  23. key = urldecode(key),
  24. val = urldecode(val); //有可能参数之前是encode过 add by fengwei
  25. return urlencode(key) + '=' + urlencode(val);
  26. } else {
  27. throw new Error('There was an error processing for http_build_query().');
  28. }
  29. } else {
  30. return '';
  31. }
  32. };
  33. if (!arg_separator) {
  34. arg_separator = '&';
  35. }
  36. for (key in formdata) {
  37. value = formdata[key];
  38. if (numeric_prefix && !isNaN(key)) {
  39. key = String(numeric_prefix) + key;
  40. }
  41. var query = _http_build_query_helper(key, value, arg_separator);
  42. if (query !== '') {
  43. tmp.push(query);
  44. }
  45. }
  46. return tmp.join(arg_separator);
  47. }
  48. //如php urlencode.
  49. function urlencode(str) {
  50. str += '';
  51. return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
  52. }
  53. //php urldecode.
  54. function urldecode(str) {
  55. try {
  56. return decodeURIComponent((str + '').replace(/%(?![\da-f]{2})/gi,
  57. function () {
  58. return '%25';
  59. }).replace(/\+/g, '%20'));
  60. } catch (e) {
  61. return '';
  62. }
  63. }
  64. const formatTime = date => {
  65. const year = date.getFullYear()
  66. const month = date.getMonth() + 1
  67. const day = date.getDate()
  68. const hour = date.getHours()
  69. const minute = date.getMinutes()
  70. const second = date.getSeconds()
  71. return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  72. }
  73. const formatNumber = n => {
  74. n = n.toString()
  75. return n[1] ? n : '0' + n
  76. }
  77. var showCreateTime = function(){
  78. var date = new Date();
  79. const month = date.getMonth() + 1
  80. const day = date.getDate()
  81. const hour = date.getHours()
  82. const minute = date.getMinutes()
  83. return [month, day].map(formatNumber).join('-') + ' ' + [hour, minute].map(formatNumber).join(':');
  84. }
  85. var wordwrap = function (str, width) {
  86. width = width || 64;
  87. if (!str) {
  88. return str;
  89. }
  90. var regex = "(.{1," + width + "})( +|$\n?)|(.{1," + width + "})";
  91. return str.match(RegExp(regex, "g")).join("\n");
  92. };
  93. var sslEncrypt = function(str, publicKey) {
  94. return this.encrypt(str, publicKey);
  95. }
  96. var sslDecrypt = function (str, privateKey) {
  97. //格式化js使用的private key格式,服务端返回的跟本地使用的不一致
  98. privateKey = privateKey.replace("-----BEGIN RSA PRIVATE KEY-----", "-----BEGIN PRIVATE KEY-----");
  99. privateKey = privateKey.replace("-----END RSA PRIVATE KEY-----", "-----END PRIVATE KEY-----");
  100. return this.decrypt(str, privateKey);
  101. }
  102. //验证公私钥
  103. var verifySslKey = function(publicKey, privateKey){
  104. app.log(publicKey, privateKey);
  105. var verifyStr = "It's ok";
  106. var encrypt = this.encrypt(verifyStr, publicKey);
  107. var decrypt = this.decrypt(encrypt, privateKey);
  108. if (decrypt != verifyStr) {
  109. return false;
  110. }
  111. return true;
  112. }
  113. var genSslKey = function(){
  114. var crypt = new Encrypt.JSEncrypt({ default_key_size: 1024 });
  115. crypt.getKey();
  116. var publicKey = crypt.getPublicKey();
  117. var privateKey = crypt.getPrivateKey();
  118. // 去除-----*** RSA **** KEY----- 和空格换行
  119. //publicKey = (publicKey.split('-----'))[2];
  120. //publicKey = publicKey.replace(/\n/g, "").replace(/\r/g, "").replace(/\t/g, "").replace(/\s*/g, "");
  121. //privateKey = (privateKey.split('-----'))[2];
  122. //privateKey = privateKey.replace(/\n/g, "").replace(/\r/g, "").replace(/\t/g, "").replace(/\s*/g, "");
  123. return {
  124. publicKey : publicKey,
  125. privateKey : privateKey
  126. };
  127. }
  128. var encrypt = function (str, publicKey) {
  129. var crypt = new Encrypt.JSEncrypt();
  130. crypt.setPublicKey(publicKey);
  131. return crypt.encrypt(str);
  132. }
  133. var decrypt = function(str, privateKey){
  134. var crypt = new Encrypt.JSEncrypt();
  135. crypt.setPrivateKey(privateKey);
  136. var decStr = crypt.decrypt(str);
  137. if(decStr == null) return false;
  138. return decStr;
  139. }
  140. var getUrl = function(api, params) {
  141. if(typeof params == 'undefined')
  142. {
  143. params = {};
  144. }
  145. if (!appConfig.api[api]) {
  146. return "";
  147. }
  148. params.isLocal = appConfig.api[api].indexOf("localhost") != -1 ? 1 : 0;
  149. if (appConfig.api[api].indexOf("?") !== -1) {
  150. return appConfig.api[api] + "&" + http_build_query(params);
  151. }
  152. return appConfig.api[api] + "?" + http_build_query(params);
  153. }
  154. var getSwitchToLocalStatus = function() {
  155. var localStatus = wx.getStorageSync(appConfig.storeKeys.switchToLocal) || 0;
  156. if(localStatus == 1) {
  157. return true;
  158. }
  159. return false;
  160. }
  161. var syncServerInfo = function() { //同步更新serverInfo和sslKey
  162. var sslKeys = wx.getStorageSync(appConfig.storeKeys.sslKeys)
  163. var serverInfo = wx.getStorageSync(appConfig.storeKeys.serverInfo)
  164. app.log("syncServerInfo", sslKeys, serverInfo);
  165. if (!serverInfo) return false;
  166. if (sslKeys && sslKeys['publicKey'] && sslKeys['privateKey'] &&
  167. serverInfo && serverInfo['sslKeys'] && (sslKeys['publicKey'] == serverInfo['sslKeys']['publicKey'])
  168. ) {
  169. serverInfo['sslKeys']['privateKey'] = sslKeys['privateKey'];
  170. wx.setStorageSync(appConfig.storeKeys.serverInfo, serverInfo);
  171. }
  172. return serverInfo;
  173. }
  174. var hasPublicKey = function() {
  175. var serverInfo = this.syncServerInfo();
  176. if (!serverInfo) {
  177. return false;
  178. }
  179. if (!serverInfo['sslKeys']) {
  180. return false;
  181. }
  182. if (!serverInfo['sslKeys']['publicKey'] || serverInfo['sslKeys']['publicKey'] == "") {
  183. return false;
  184. }
  185. return true;
  186. }
  187. var hasPrivateKey = function() {
  188. var serverInfo = this.syncServerInfo();
  189. if (!serverInfo) {
  190. return false;
  191. }
  192. if (!serverInfo['sslKeys']) {
  193. return false;
  194. }
  195. if (!serverInfo['sslKeys']['privateKey'] || serverInfo['sslKeys']['privateKey'] == "") {
  196. return false;
  197. }
  198. return true;
  199. }
  200. ///
  201. var getPublicKey = function() {
  202. var serverInfo = this.syncServerInfo();
  203. if (!serverInfo) {
  204. return "";
  205. }
  206. if (!serverInfo['sslKeys']) {
  207. return "";
  208. }
  209. if (!serverInfo['sslKeys']['publicKey'] || serverInfo['sslKeys']['publicKey'] == "") {
  210. return "";
  211. }
  212. return serverInfo['sslKeys']['publicKey'];
  213. }
  214. var getPrivateKey = function() {
  215. var serverInfo = this.syncServerInfo();
  216. if (!serverInfo) {
  217. return "";
  218. }
  219. if (!serverInfo['sslKeys']) {
  220. return "";
  221. }
  222. if (!serverInfo['sslKeys']['privateKey'] || serverInfo['sslKeys']['privateKey'] == "") {
  223. return "";
  224. }
  225. return serverInfo['sslKeys']['privateKey'];
  226. }
  227. var hasLogined = function() {
  228. var serverInfo = this.syncServerInfo();
  229. if (!serverInfo) {
  230. return false;
  231. }
  232. if (serverInfo.sessionId && serverInfo.openId &&
  233. serverInfo.sessionId != "" && serverInfo.openId != ""
  234. ) {
  235. return true;
  236. }
  237. return false;
  238. }
  239. var getSessionId = function() {
  240. var serverInfo = this.syncServerInfo();
  241. if (!serverInfo) {
  242. return "";
  243. }
  244. if (!serverInfo['sessionId']) {
  245. return "";
  246. }
  247. return serverInfo['sessionId'];
  248. }
  249. var getOpenId = function() {
  250. var serverInfo = this.syncServerInfo();
  251. if (!serverInfo) {
  252. return "";
  253. }
  254. if (!serverInfo['openId']) {
  255. return "";
  256. }
  257. return serverInfo['openId'];
  258. }
  259. var setBackground = function(url) {
  260. wx.setStorageSync(appConfig.storeKeys.background, url);
  261. }
  262. var getBackground = function() {
  263. var background = wx.getStorageSync(appConfig.storeKeys.background);
  264. app.log(background);
  265. if (!background) return app.globalData.background;
  266. return background;
  267. }
  268. module.exports = {
  269. formatTime: formatTime,
  270. sslEncrypt: encrypt,
  271. sslDecrypt: decrypt,
  272. encrypt: encrypt,
  273. decrypt: decrypt,
  274. genSslKey: genSslKey,
  275. verifySslKey: verifySslKey,
  276. getUrl: getUrl,
  277. getSwitchToLocalStatus: getSwitchToLocalStatus,
  278. showCreateTime: showCreateTime,
  279. syncServerInfo: syncServerInfo,
  280. hasPublicKey: hasPublicKey,
  281. hasPrivateKey: hasPrivateKey,
  282. getPublicKey: getPublicKey,
  283. getPrivateKey: getPrivateKey,
  284. hasLogined: hasLogined,
  285. getSessionId: getSessionId,
  286. getOpenId: getOpenId,
  287. setBackground: setBackground,
  288. getBackground: getBackground,
  289. }