abp.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901
  1. var abp = abp || {};
  2. (function () {
  3. /* Application paths *****************************************/
  4. //Current application root path (including virtual directory if exists).
  5. abp.appPath = abp.appPath || '/';
  6. abp.pageLoadTime = new Date();
  7. //Converts given path to absolute path using abp.appPath variable.
  8. abp.toAbsAppPath = function (path) {
  9. if (path.indexOf('/') == 0) {
  10. path = path.substring(1);
  11. }
  12. return abp.appPath + path;
  13. };
  14. /* MULTITENANCY */
  15. abp.multiTenancy = abp.multiTenancy || {};
  16. abp.multiTenancy.isEnabled = false;
  17. abp.multiTenancy.sides = {
  18. TENANT: 1,
  19. HOST: 2
  20. };
  21. abp.multiTenancy.tenantIdCookieName = 'Abp.TenantId';
  22. abp.multiTenancy.setTenantIdCookie = function (tenantId) {
  23. if (tenantId) {
  24. abp.utils.setCookieValue(
  25. abp.multiTenancy.tenantIdCookieName,
  26. tenantId.toString(),
  27. new Date(new Date().getTime() + 5 * 365 * 86400000), //5 years
  28. abp.appPath,
  29. abp.domain
  30. );
  31. } else {
  32. abp.utils.deleteCookie(abp.multiTenancy.tenantIdCookieName, abp.appPath);
  33. }
  34. };
  35. abp.multiTenancy.getTenantIdCookie = function () {
  36. var value = abp.utils.getCookieValue(abp.multiTenancy.tenantIdCookieName);
  37. if (!value) {
  38. return null;
  39. }
  40. return parseInt(value);
  41. }
  42. /* SESSION */
  43. abp.session = abp.session || {
  44. multiTenancySide: abp.multiTenancy.sides.HOST
  45. };
  46. /* LOCALIZATION ***********************************************/
  47. //Implements Localization API that simplifies usage of localization scripts generated by Abp.
  48. abp.localization = abp.localization || {};
  49. abp.localization.languages = [];
  50. abp.localization.currentLanguage = {};
  51. abp.localization.sources = [];
  52. abp.localization.values = {};
  53. abp.localization.localize = function (key, sourceName) {
  54. sourceName = sourceName || abp.localization.defaultSourceName;
  55. var source = abp.localization.values[sourceName];
  56. if (!source) {
  57. abp.log.warn('Could not find localization source: ' + sourceName);
  58. return key;
  59. }
  60. var value = source[key];
  61. if (value == undefined) {
  62. return key;
  63. }
  64. var copiedArguments = Array.prototype.slice.call(arguments, 0);
  65. copiedArguments.splice(1, 1);
  66. copiedArguments[0] = value;
  67. return abp.utils.formatString.apply(this, copiedArguments);
  68. };
  69. abp.localization.getSource = function (sourceName) {
  70. return function (key) {
  71. var copiedArguments = Array.prototype.slice.call(arguments, 0);
  72. copiedArguments.splice(1, 0, sourceName);
  73. return abp.localization.localize.apply(this, copiedArguments);
  74. };
  75. };
  76. abp.localization.isCurrentCulture = function (name) {
  77. return abp.localization.currentCulture &&
  78. abp.localization.currentCulture.name &&
  79. abp.localization.currentCulture.name.indexOf(name) == 0;
  80. };
  81. abp.localization.getBrowserLanguage = function () {
  82. let language = ''
  83. let browserLanguage = (navigator.language || navigator.browserLanguage).toLowerCase()
  84. if (abp.utils.getCookieValue('FangCom.Localization.CultureName')) {
  85. browserLanguage = abp.utils.getCookieValue('FangCom.Localization.CultureName').toLowerCase()
  86. }
  87. if (browserLanguage.indexOf('zh') > -1) {
  88. language = 'zh_CN'
  89. } else if (browserLanguage.indexOf('en') > -1) {
  90. language = 'en'
  91. }
  92. return language
  93. }
  94. abp.localization.defaultSourceName = undefined;
  95. abp.localization.abpWeb = abp.localization.getSource('AbpWeb');
  96. /* AUTHORIZATION **********************************************/
  97. //Implements Authorization API that simplifies usage of authorization scripts generated by Abp.
  98. abp.auth = abp.auth || {};
  99. abp.auth.allPermissions = abp.auth.allPermissions || {};
  100. abp.auth.grantedPermissions = abp.auth.grantedPermissions || {};
  101. //Deprecated. Use abp.auth.isGranted instead.
  102. abp.auth.hasPermission = function (permissionName) {
  103. return abp.auth.isGranted.apply(this, arguments);
  104. };
  105. //Deprecated. Use abp.auth.isAnyGranted instead.
  106. abp.auth.hasAnyOfPermissions = function () {
  107. return abp.auth.isAnyGranted.apply(this, arguments);
  108. };
  109. //Deprecated. Use abp.auth.areAllGranted instead.
  110. abp.auth.hasAllOfPermissions = function () {
  111. return abp.auth.areAllGranted.apply(this, arguments);
  112. };
  113. abp.auth.isGranted = function (permissionName) {
  114. return abp.auth.allPermissions[permissionName] != undefined && abp.auth.grantedPermissions[permissionName] != undefined;
  115. };
  116. abp.auth.isAnyGranted = function () {
  117. if (!arguments || arguments.length <= 0) {
  118. return true;
  119. }
  120. for (var i = 0; i < arguments.length; i++) {
  121. if (abp.auth.isGranted(arguments[i])) {
  122. return true;
  123. }
  124. }
  125. return false;
  126. };
  127. abp.auth.areAllGranted = function () {
  128. if (!arguments || arguments.length <= 0) {
  129. return true;
  130. }
  131. for (var i = 0; i < arguments.length; i++) {
  132. if (!abp.auth.isGranted(arguments[i])) {
  133. return false;
  134. }
  135. }
  136. return true;
  137. };
  138. abp.auth.tokenCookieName = 'FangCom.AuthToken';
  139. abp.auth.setToken = function (authToken, expireDate) {
  140. abp.utils.setCookieValue(abp.auth.tokenCookieName, authToken, expireDate, abp.appPath, abp.domain);
  141. };
  142. abp.auth.getToken = function () {
  143. return abp.utils.getCookieValue(abp.auth.tokenCookieName);
  144. }
  145. abp.auth.clearToken = function () {
  146. abp.auth.setToken();
  147. }
  148. /* FEATURE SYSTEM *********************************************/
  149. //Implements Features API that simplifies usage of feature scripts generated by Abp.
  150. abp.features = abp.features || {};
  151. abp.features.allFeatures = abp.features.allFeatures || {};
  152. abp.features.get = function (name) {
  153. return abp.features.allFeatures[name];
  154. }
  155. abp.features.getValue = function (name) {
  156. var feature = abp.features.get(name);
  157. if (feature == undefined) {
  158. return undefined;
  159. }
  160. return feature.value;
  161. }
  162. abp.features.isEnabled = function (name) {
  163. var value = abp.features.getValue(name);
  164. return value == 'true' || value == 'True';
  165. }
  166. /* SETTINGS **************************************************/
  167. //Implements Settings API that simplifies usage of setting scripts generated by Abp.
  168. abp.setting = abp.setting || {};
  169. abp.setting.values = abp.setting.values || {};
  170. abp.setting.get = function (name) {
  171. return abp.setting.values[name];
  172. };
  173. abp.setting.getBoolean = function (name) {
  174. var value = abp.setting.get(name);
  175. return value == 'true' || value == 'True';
  176. };
  177. abp.setting.getInt = function (name) {
  178. return parseInt(abp.setting.values[name]);
  179. };
  180. /* REALTIME NOTIFICATIONS ************************************/
  181. abp.notifications = abp.notifications || {};
  182. abp.notifications.severity = {
  183. INFO: 0,
  184. SUCCESS: 1,
  185. WARN: 2,
  186. ERROR: 3,
  187. FATAL: 4
  188. };
  189. abp.notifications.userNotificationState = {
  190. UNREAD: 0,
  191. READ: 1
  192. };
  193. abp.notifications.getUserNotificationStateAsString = function (userNotificationState) {
  194. switch (userNotificationState) {
  195. case abp.notifications.userNotificationState.READ:
  196. return 'READ';
  197. case abp.notifications.userNotificationState.UNREAD:
  198. return 'UNREAD';
  199. default:
  200. abp.log.warn('Unknown user notification state value: ' + userNotificationState)
  201. return '?';
  202. }
  203. };
  204. abp.notifications.getUiNotifyFuncBySeverity = function (severity) {
  205. switch (severity) {
  206. case abp.notifications.severity.SUCCESS:
  207. return abp.notify.success;
  208. case abp.notifications.severity.WARN:
  209. return abp.notify.warn;
  210. case abp.notifications.severity.ERROR:
  211. return abp.notify.error;
  212. case abp.notifications.severity.FATAL:
  213. return abp.notify.error;
  214. case abp.notifications.severity.INFO:
  215. default:
  216. return abp.notify.info;
  217. }
  218. };
  219. abp.notifications.messageFormatters = {};
  220. abp.notifications.messageFormatters['Abp.Notifications.MessageNotificationData'] = function (userNotification) {
  221. return userNotification.notification.data.message || userNotification.notification.data.properties.Message;
  222. };
  223. abp.notifications.messageFormatters['Abp.Notifications.LocalizableMessageNotificationData'] = function (userNotification) {
  224. var message = userNotification.notification.data.message || userNotification.notification.data.properties.Message;
  225. var localizedMessage = abp.localization.localize(
  226. message.name,
  227. message.sourceName
  228. );
  229. if (userNotification.notification.data.properties) {
  230. var properties = Object.keys(userNotification.notification.data.properties);
  231. for (var i = 0; i < properties.length; i++) {
  232. localizedMessage = localizedMessage.replace('{' + properties[i] + '}', userNotification.notification.data.properties[properties[i]]);
  233. }
  234. }
  235. return localizedMessage;
  236. };
  237. abp.notifications.getFormattedMessageFromUserNotification = function (userNotification) {
  238. var formatter = abp.notifications.messageFormatters[userNotification.notification.data.type];
  239. if (!formatter) {
  240. abp.log.warn('No message formatter defined for given data type: ' + userNotification.notification.data.type)
  241. return '?';
  242. }
  243. if (!abp.utils.isFunction(formatter)) {
  244. abp.log.warn('Message formatter should be a function! It is invalid for data type: ' + userNotification.notification.data.type)
  245. return '?';
  246. }
  247. return formatter(userNotification);
  248. }
  249. abp.notifications.showUiNotifyForUserNotification = function (userNotification, options) {
  250. var message = abp.notifications.getFormattedMessageFromUserNotification(userNotification);
  251. var uiNotifyFunc = abp.notifications.getUiNotifyFuncBySeverity(userNotification.notification.severity);
  252. uiNotifyFunc(message, undefined, options);
  253. }
  254. /* LOGGING ***************************************************/
  255. //Implements Logging API that provides secure & controlled usage of console.log
  256. abp.log = abp.log || {};
  257. abp.log.levels = {
  258. DEBUG: 1,
  259. INFO: 2,
  260. WARN: 3,
  261. ERROR: 4,
  262. FATAL: 5
  263. };
  264. abp.log.level = abp.log.levels.DEBUG;
  265. abp.log.log = function (logObject, logLevel) {
  266. if (!window.console || !window.console.log) {
  267. return;
  268. }
  269. if (logLevel != undefined && logLevel < abp.log.level) {
  270. return;
  271. }
  272. console.log(logObject);
  273. };
  274. abp.log.debug = function (logObject) {
  275. abp.log.log("DEBUG: ", abp.log.levels.DEBUG);
  276. abp.log.log(logObject, abp.log.levels.DEBUG);
  277. };
  278. abp.log.info = function (logObject) {
  279. abp.log.log("INFO: ", abp.log.levels.INFO);
  280. abp.log.log(logObject, abp.log.levels.INFO);
  281. };
  282. abp.log.warn = function (logObject) {
  283. abp.log.log("WARN: ", abp.log.levels.WARN);
  284. abp.log.log(logObject, abp.log.levels.WARN);
  285. };
  286. abp.log.error = function (logObject) {
  287. abp.log.log("ERROR: ", abp.log.levels.ERROR);
  288. abp.log.log(logObject, abp.log.levels.ERROR);
  289. };
  290. abp.log.fatal = function (logObject) {
  291. abp.log.log("FATAL: ", abp.log.levels.FATAL);
  292. abp.log.log(logObject, abp.log.levels.FATAL);
  293. };
  294. /* NOTIFICATION *********************************************/
  295. //Defines Notification API, not implements it
  296. abp.notify = abp.notify || {};
  297. abp.notify.success = function (message, title, options) {
  298. abp.log.warn('abp.notify.success is not implemented!');
  299. };
  300. abp.notify.info = function (message, title, options) {
  301. abp.log.warn('abp.notify.info is not implemented!');
  302. };
  303. abp.notify.warn = function (message, title, options) {
  304. abp.log.warn('abp.notify.warn is not implemented!');
  305. };
  306. abp.notify.error = function (message, title, options) {
  307. abp.log.warn('abp.notify.error is not implemented!');
  308. };
  309. /* MESSAGE **************************************************/
  310. //Defines Message API, not implements it
  311. abp.message = abp.message || {};
  312. var showMessage = function (message, title) {
  313. alert((title || '') + ' ' + message);
  314. };
  315. abp.message.info = function (message, title) {
  316. abp.log.warn('abp.message.info is not implemented!');
  317. return showMessage(message, title);
  318. };
  319. abp.message.success = function (message, title) {
  320. abp.log.warn('abp.message.success is not implemented!');
  321. return showMessage(message, title);
  322. };
  323. abp.message.warn = function (message, title) {
  324. abp.log.warn('abp.message.warn is not implemented!');
  325. return showMessage(message, title);
  326. };
  327. abp.message.error = function (message, title) {
  328. abp.log.warn('abp.message.error is not implemented!');
  329. return showMessage(message, title);
  330. };
  331. abp.message.confirm = function (message, titleOrCallback, callback) {
  332. abp.log.warn('abp.message.confirm is not implemented!');
  333. if (titleOrCallback && !(typeof titleOrCallback == 'string')) {
  334. callback = titleOrCallback;
  335. }
  336. var result = confirm(message);
  337. callback && callback(result);
  338. };
  339. /* UI *******************************************************/
  340. abp.ui = abp.ui || {};
  341. /* UI BLOCK */
  342. //Defines UI Block API, not implements it
  343. abp.ui.block = function (elm) {
  344. abp.log.warn('abp.ui.block is not implemented!');
  345. };
  346. abp.ui.unblock = function (elm) {
  347. abp.log.warn('abp.ui.unblock is not implemented!');
  348. };
  349. /* UI BUSY */
  350. //Defines UI Busy API, not implements it
  351. abp.ui.setBusy = function (elm, optionsOrPromise) {
  352. abp.log.warn('abp.ui.setBusy is not implemented!');
  353. };
  354. abp.ui.clearBusy = function (elm) {
  355. abp.log.warn('abp.ui.clearBusy is not implemented!');
  356. };
  357. /* SIMPLE EVENT BUS *****************************************/
  358. abp.event = (function () {
  359. var _callbacks = {};
  360. var on = function (eventName, callback) {
  361. if (!_callbacks[eventName]) {
  362. _callbacks[eventName] = [];
  363. }
  364. _callbacks[eventName].push(callback);
  365. };
  366. var off = function (eventName, callback) {
  367. var callbacks = _callbacks[eventName];
  368. if (!callbacks) {
  369. return;
  370. }
  371. var index = -1;
  372. for (var i = 0; i < callbacks.length; i++) {
  373. if (callbacks[i] === callback) {
  374. index = i;
  375. break;
  376. }
  377. }
  378. if (index < 0) {
  379. return;
  380. }
  381. _callbacks[eventName].splice(index, 1);
  382. };
  383. var trigger = function (eventName) {
  384. var callbacks = _callbacks[eventName];
  385. if (!callbacks || !callbacks.length) {
  386. return;
  387. }
  388. var args = Array.prototype.slice.call(arguments, 1);
  389. for (var i = 0; i < callbacks.length; i++) {
  390. callbacks[i].apply(this, args);
  391. }
  392. };
  393. // Public interface ///////////////////////////////////////////////////
  394. return {
  395. on: on,
  396. off: off,
  397. trigger: trigger
  398. };
  399. })();
  400. /* UTILS ***************************************************/
  401. abp.utils = abp.utils || {};
  402. /* Creates a name namespace.
  403. * Example:
  404. * var taskService = abp.utils.createNamespace(abp, 'services.task');
  405. * taskService will be equal to abp.services.task
  406. * first argument (root) must be defined first
  407. ************************************************************/
  408. abp.utils.createNamespace = function (root, ns) {
  409. var parts = ns.split('.');
  410. for (var i = 0; i < parts.length; i++) {
  411. if (typeof root[parts[i]] == 'undefined') {
  412. root[parts[i]] = {};
  413. }
  414. root = root[parts[i]];
  415. }
  416. return root;
  417. };
  418. /* Find and replaces a string (search) to another string (replacement) in
  419. * given string (str).
  420. * Example:
  421. * abp.utils.replaceAll('This is a test string', 'is', 'X') = 'ThX X a test string'
  422. ************************************************************/
  423. abp.utils.replaceAll = function (str, search, replacement) {
  424. var fix = search.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  425. return str.replace(new RegExp(fix, 'g'), replacement);
  426. };
  427. /* Formats a string just like string.format in C#.
  428. * Example:
  429. * abp.utils.formatString('Hello {0}','Tuana') = 'Hello Tuana'
  430. ************************************************************/
  431. abp.utils.formatString = function () {
  432. if (arguments.length < 1) {
  433. return null;
  434. }
  435. var str = arguments[0];
  436. for (var i = 1; i < arguments.length; i++) {
  437. var placeHolder = '{' + (i - 1) + '}';
  438. str = abp.utils.replaceAll(str, placeHolder, arguments[i]);
  439. }
  440. return str;
  441. };
  442. abp.utils.toPascalCase = function (str) {
  443. if (!str || !str.length) {
  444. return str;
  445. }
  446. if (str.length === 1) {
  447. return str.charAt(0).toUpperCase();
  448. }
  449. return str.charAt(0).toUpperCase() + str.substr(1);
  450. }
  451. abp.utils.toCamelCase = function (str) {
  452. if (!str || !str.length) {
  453. return str;
  454. }
  455. if (str.length === 1) {
  456. return str.charAt(0).toLowerCase();
  457. }
  458. return str.charAt(0).toLowerCase() + str.substr(1);
  459. }
  460. abp.utils.truncateString = function (str, maxLength) {
  461. if (!str || !str.length || str.length <= maxLength) {
  462. return str;
  463. }
  464. return str.substr(0, maxLength);
  465. };
  466. abp.utils.truncateStringWithPostfix = function (str, maxLength, postfix) {
  467. postfix = postfix || '...';
  468. if (!str || !str.length || str.length <= maxLength) {
  469. return str;
  470. }
  471. if (maxLength <= postfix.length) {
  472. return postfix.substr(0, maxLength);
  473. }
  474. return str.substr(0, maxLength - postfix.length) + postfix;
  475. };
  476. abp.utils.isFunction = function (obj) {
  477. //alternative for $.isFunction
  478. return !!(obj && obj.constructor && obj.call && obj.apply);
  479. };
  480. /**
  481. * parameterInfos should be an array of { name, value } objects
  482. * where name is query string parameter name and value is it's value.
  483. * includeQuestionMark is true by default.
  484. */
  485. abp.utils.buildQueryString = function (parameterInfos, includeQuestionMark) {
  486. if (includeQuestionMark === undefined) {
  487. includeQuestionMark = true;
  488. }
  489. var qs = '';
  490. function addSeperator() {
  491. if (!qs.length) {
  492. if (includeQuestionMark) {
  493. qs = qs + '?';
  494. }
  495. } else {
  496. qs = qs + '&';
  497. }
  498. }
  499. for (var i = 0; i < parameterInfos.length; ++i) {
  500. var parameterInfo = parameterInfos[i];
  501. if (parameterInfo.value === undefined) {
  502. continue;
  503. }
  504. if (parameterInfo.value === null) {
  505. parameterInfo.value = '';
  506. }
  507. addSeperator();
  508. if (parameterInfo.value.toJSON && typeof parameterInfo.value.toJSON === "function") {
  509. qs = qs + parameterInfo.name + '=' + encodeURIComponent(parameterInfo.value.toJSON());
  510. } else if (Array.isArray(parameterInfo.value) && parameterInfo.value.length) {
  511. for (var j = 0; j < parameterInfo.value.length; j++) {
  512. if (j > 0) {
  513. addSeperator();
  514. }
  515. qs = qs + parameterInfo.name + '[' + j + ']=' + encodeURIComponent(parameterInfo.value[j]);
  516. }
  517. } else {
  518. qs = qs + parameterInfo.name + '=' + encodeURIComponent(parameterInfo.value);
  519. }
  520. }
  521. return qs;
  522. }
  523. /**
  524. * Sets a cookie value for given key.
  525. * This is a simple implementation created to be used by ABP.
  526. * Please use a complete cookie library if you need.
  527. * @param {string} key
  528. * @param {string} value
  529. * @param {Date} expireDate (optional). If not specified the cookie will expire at the end of session.
  530. * @param {string} path (optional)
  531. */
  532. abp.utils.setCookieValue = function (key, value, expireDate, path, domain) {
  533. var cookieValue = encodeURIComponent(key) + '=';
  534. if (value) {
  535. cookieValue = cookieValue + encodeURIComponent(value);
  536. }
  537. if (expireDate) {
  538. cookieValue = cookieValue + "; expires=" + expireDate.toUTCString();
  539. }
  540. if (path) {
  541. cookieValue = cookieValue + "; path=" + path;
  542. }
  543. if (domain) {
  544. cookieValue = cookieValue + "; domain=" + domain;
  545. }
  546. document.cookie = cookieValue;
  547. };
  548. /**
  549. * Gets a cookie with given key.
  550. * This is a simple implementation created to be used by ABP.
  551. * Please use a complete cookie library if you need.
  552. * @param {string} key
  553. * @returns {string} Cookie value or null
  554. */
  555. abp.utils.getCookieValue = function (key) {
  556. var equalities = document.cookie.split('; ');
  557. for (var i = 0; i < equalities.length; i++) {
  558. if (!equalities[i]) {
  559. continue;
  560. }
  561. var splitted = equalities[i].split('=');
  562. if (splitted.length != 2) {
  563. continue;
  564. }
  565. if (decodeURIComponent(splitted[0]) === key) {
  566. return decodeURIComponent(splitted[1] || '');
  567. }
  568. }
  569. return null;
  570. };
  571. /**
  572. * Deletes cookie for given key.
  573. * This is a simple implementation created to be used by ABP.
  574. * Please use a complete cookie library if you need.
  575. * @param {string} key
  576. * @param {string} path (optional)
  577. */
  578. abp.utils.deleteCookie = function (key, path) {
  579. var cookieValue = encodeURIComponent(key) + '=';
  580. cookieValue = cookieValue + "; expires=" + (new Date(new Date().getTime() - 86400000)).toUTCString();
  581. if (path) {
  582. cookieValue = cookieValue + "; path=" + path;
  583. }
  584. document.cookie = cookieValue;
  585. }
  586. /**
  587. * Gets the domain of given url
  588. * @param {string} url
  589. * @returns {string}
  590. */
  591. abp.utils.getDomain = function (url) {
  592. var domainRegex = /(https?:){0,1}\/\/((?:[\w\d-]+\.)+[\w\d]{2,})/i;
  593. var matches = domainRegex.exec(url);
  594. return (matches && matches[2]) ? matches[2] : '';
  595. }
  596. /* TIMING *****************************************/
  597. abp.timing = abp.timing || {};
  598. abp.timing.utcClockProvider = (function () {
  599. var toUtc = function (date) {
  600. return Date.UTC(
  601. date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds()
  602. );
  603. }
  604. var now = function () {
  605. return new Date();
  606. };
  607. var normalize = function (date) {
  608. if (!date) {
  609. return date;
  610. }
  611. return new Date(toUtc(date));
  612. };
  613. // Public interface ///////////////////////////////////////////////////
  614. return {
  615. now: now,
  616. normalize: normalize,
  617. supportsMultipleTimezone: true
  618. };
  619. })();
  620. abp.timing.localClockProvider = (function () {
  621. var toLocal = function (date) {
  622. return new Date(
  623. date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()
  624. );
  625. }
  626. var now = function () {
  627. return toLocal(new Date());
  628. }
  629. var normalize = function (date) {
  630. if (!date) {
  631. return date;
  632. }
  633. return toLocal(date);
  634. }
  635. // Public interface ///////////////////////////////////////////////////
  636. return {
  637. now: now,
  638. normalize: normalize,
  639. supportsMultipleTimezone: false
  640. };
  641. })();
  642. abp.timing.unspecifiedClockProvider = (function () {
  643. var now = function () {
  644. return new Date();
  645. }
  646. var normalize = function (date) {
  647. return date;
  648. }
  649. // Public interface ///////////////////////////////////////////////////
  650. return {
  651. now: now,
  652. normalize: normalize,
  653. supportsMultipleTimezone: false
  654. };
  655. })();
  656. abp.timing.convertToUserTimezone = function (date) {
  657. var localTime = date.getTime();
  658. var utcTime = localTime + (date.getTimezoneOffset() * 60000);
  659. var targetTime = parseInt(utcTime) + parseInt(abp.timing.timeZoneInfo.windows.currentUtcOffsetInMilliseconds);
  660. return new Date(targetTime);
  661. };
  662. /* CLOCK *****************************************/
  663. abp.clock = abp.clock || {};
  664. abp.clock.now = function () {
  665. if (abp.clock.provider) {
  666. return abp.clock.provider.now();
  667. }
  668. return new Date();
  669. }
  670. abp.clock.normalize = function (date) {
  671. if (abp.clock.provider) {
  672. return abp.clock.provider.normalize(date);
  673. }
  674. return date;
  675. }
  676. abp.clock.provider = abp.timing.unspecifiedClockProvider;
  677. /* SECURITY ***************************************/
  678. abp.security = abp.security || {};
  679. abp.security.antiForgery = abp.security.antiForgery || {};
  680. abp.security.antiForgery.tokenCookieName = 'XSRF-TOKEN';
  681. abp.security.antiForgery.tokenHeaderName = 'X-XSRF-TOKEN';
  682. abp.security.antiForgery.getToken = function () {
  683. return abp.utils.getCookieValue(abp.security.antiForgery.tokenCookieName);
  684. };
  685. abp.security.antiForgery.shouldSendToken = function (settings) {
  686. if (settings.crossDomain === undefined || settings.crossDomain === null) {
  687. return abp.utils.getDomain(location.href) === abp.utils.getDomain(settings.url);
  688. }
  689. return !settings.crossDomain;
  690. };
  691. })();