account.service.js 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  2. /*
  3. * Copyright 2018 Red Hat Inc. and/or its affiliates and other contributors
  4. * as indicated by the @author tags. All rights reserved.
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  7. * use this file except in compliance with the License. You may obtain a copy of
  8. * the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  14. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  15. * License for the specific language governing permissions and limitations under
  16. * the License.
  17. */
  18. import { ContentAlert } from "../content/ContentAlert.js";
  19. export class AccountServiceError extends Error {
  20. constructor(response) {
  21. super(response.statusText);
  22. this.response = response;
  23. }
  24. }
  25. /**
  26. *
  27. * @author Stan Silvert ssilvert@redhat.com (C) 2018 Red Hat Inc.
  28. */
  29. export class AccountServiceClient {
  30. constructor(keycloakService) {
  31. _defineProperty(this, "kcSvc", void 0);
  32. _defineProperty(this, "accountUrl", void 0);
  33. this.kcSvc = keycloakService;
  34. this.accountUrl = this.kcSvc.authServerUrl() + 'realms/' + this.kcSvc.realm() + '/account';
  35. }
  36. async doGet(endpoint, config) {
  37. return this.doRequest(endpoint, { ...config,
  38. method: 'get'
  39. });
  40. }
  41. async doDelete(endpoint, config) {
  42. return this.doRequest(endpoint, { ...config,
  43. method: 'delete'
  44. });
  45. }
  46. async doPost(endpoint, body, config) {
  47. return this.doRequest(endpoint, { ...config,
  48. body: JSON.stringify(body),
  49. method: 'post'
  50. });
  51. }
  52. async doPut(endpoint, body, config) {
  53. return this.doRequest(endpoint, { ...config,
  54. body: JSON.stringify(body),
  55. method: 'put'
  56. });
  57. }
  58. async doRequest(endpoint, config) {
  59. const response = await fetch(this.makeUrl(endpoint, config).toString(), await this.makeConfig(config));
  60. try {
  61. response.data = await response.json();
  62. } catch (e) {} // ignore. Might be empty
  63. if (!response.ok) {
  64. this.handleError(response);
  65. throw new AccountServiceError(response);
  66. }
  67. return response;
  68. }
  69. handleError(response) {
  70. if (response !== null && response.status === 401) {
  71. if (this.kcSvc.authenticated() && !this.kcSvc.audiencePresent()) {
  72. // authenticated and the audience is not present => not allowed
  73. window.location.href = baseUrl + '#/forbidden';
  74. } else {
  75. // session timed out?
  76. this.kcSvc.login();
  77. }
  78. }
  79. if (response !== null && response.status === 403) {
  80. window.location.href = baseUrl + '#/forbidden';
  81. }
  82. if (response !== null && response.data != null) {
  83. if (response.data['errors'] != null) {
  84. for (let err of response.data['errors']) ContentAlert.danger(err['errorMessage'], err['params']);
  85. } else {
  86. ContentAlert.danger(`${response.statusText}: ${response.data['errorMessage'] ? response.data['errorMessage'] : ''} ${response.data['error'] ? response.data['error'] : ''}`);
  87. }
  88. ;
  89. } else {
  90. ContentAlert.danger(response.statusText);
  91. }
  92. }
  93. makeUrl(endpoint, config) {
  94. if (endpoint.startsWith('http')) return new URL(endpoint);
  95. const url = new URL(this.accountUrl + endpoint); // add request params
  96. if (config && config.hasOwnProperty('params')) {
  97. const params = config.params || {};
  98. Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
  99. }
  100. return url;
  101. }
  102. makeConfig(config = {}) {
  103. return new Promise(resolve => {
  104. this.kcSvc.getToken().then(token => {
  105. resolve({ ...config,
  106. headers: {
  107. 'Content-Type': 'application/json',
  108. ...config.headers,
  109. Authorization: 'Bearer ' + token
  110. }
  111. });
  112. }).catch(() => {
  113. this.kcSvc.login();
  114. });
  115. });
  116. }
  117. }
  118. window.addEventListener("unhandledrejection", event => {
  119. event.promise.catch(error => {
  120. if (error instanceof AccountServiceError) {
  121. // We already handled the error. Ignore unhandled rejection.
  122. event.preventDefault();
  123. }
  124. });
  125. });
  126. //# sourceMappingURL=account.service.js.map