abp.js 35 KB

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