From cef77012b1eb0c5d801cb6252b5092737ce43f29 Mon Sep 17 00:00:00 2001
From: Benoit Alessandroni <benoit@happy-dev.fr>
Date: Wed, 5 May 2021 14:08:09 +0200
Subject: [PATCH] update: switching from check-session-headers to check-user
 call

---
 dist/index.js   | 2 +-
 src/sib-auth.js | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/dist/index.js b/dist/index.js
index c5bb38b..2406f43 100644
--- a/dist/index.js
+++ b/dist/index.js
@@ -7415,7 +7415,7 @@ eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpac
 /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
 
 "use strict";
-eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */   \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* harmony import */ var _inrupt_solid_client_authn_browser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @inrupt/solid-client-authn-browser */ \"./node_modules/@inrupt/solid-client-authn-browser/dist/index.js\");\n/* harmony import */ var _inrupt_solid_client_authn_browser__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_inrupt_solid_client_authn_browser__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _startinblox_core_dist_libs_helpers_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @startinblox/core/dist/libs/helpers.js */ \"./node_modules/@startinblox/core/dist/libs/helpers.js\");\n\n\n\n// Dev Mode\n// const baseUrl = import.meta.url.replace(/\\/[^/]*$/, '');\nconst baseUrl = 'https://cdn.skypack.dev/@startinblox/oidc@0.14';\n(0,_startinblox_core_dist_libs_helpers_js__WEBPACK_IMPORTED_MODULE_1__.importCSS)(`${baseUrl}/sib-auth.css`);\nclass SIBAuth extends HTMLElement {\n  /**\n   * @typedef {Object} State\n   * @property {string} provider auth provider id\n   * @property {string} value 'login' or 'logout' or null\n   * @property {token} string CRSF token\n   * @property {previousUri} string Previous uri\n   */\n\n  constructor() {\n    super();\n    this.provider = null;\n    this.user = null;\n    this.hide();\n    this.session = (0,_inrupt_solid_client_authn_browser__WEBPACK_IMPORTED_MODULE_0__.handleIncomingRedirect)({\n      restorePreviousSession: true,\n      url: window.location.href,\n    }).then(async (sessionInfo) => {\n      if (sessionInfo && sessionInfo.isLoggedIn) {\n        this.dispatchUserInfo();\n        return sessionInfo;\n      }\n      if (this.hasAttribute('auto-login')) this.login();\n      return null;\n    });\n  }\n\n  connectedCallback() {\n    this.install();\n\n    // Manage redirection on non root urls\n    (0,_inrupt_solid_client_authn_browser__WEBPACK_IMPORTED_MODULE_0__.onSessionRestore)((url) => {\n      window.history.replaceState({}, '', url);\n      this.dispatchEvent(\n        new CustomEvent('newUrl', { bubbles: true }),\n      );\n    });\n  }\n\n  /** @function\n   * @name disconnectedCallback\n   * Clear state and user, uninstall\n   */\n  disconnectedCallback() {\n    (0,_inrupt_solid_client_authn_browser__WEBPACK_IMPORTED_MODULE_0__.logout)();\n    this.uninstall();\n  }\n\n  /** @function\n   * @name install\n   * Replace all bind-user in document\n   */\n  install() {\n    this.bindUserObserver = new MutationObserver((mutations) => {\n      mutations.forEach((mutation) => {\n        if (mutation.type === 'attributes') {\n          if (!mutation.target.hasAttribute('bind-user')) return;\n          this.applyUser(mutation.target);\n          return;\n        }\n        mutation.addedNodes.forEach((node) => {\n          if (!(node instanceof Element)) return;\n          if (node.hasAttribute('bind-user')) this.applyUser(node);\n          if (node.querySelectorAll('[bind-user]').length) {\n            node.querySelectorAll('[bind-user]').forEach((element) => this.applyUser(element));\n          }\n        });\n      });\n    });\n    this.bindUserObserver.observe(document.body, {\n      childList: true,\n      attributes: true,\n      characterData: false,\n      subtree: true,\n      attributeOldValue: false,\n      attributeFilter: ['bind-user'],\n    });\n  }\n\n  /** @function\n   * @name uninstall\n   * Remove method and property previously added on SIBBase\n   */\n  uninstall() {\n    this.bindUserObserver.disconnect();\n  }\n\n  /** @function\n   * @name getProvider\n   * Get provider that match the id\n   * @param {string} id - the provider id\n   * @returns {DOMNode} - The provider DOMNode or null\n   */\n  getProvider(id) {\n    return this.querySelector(`sib-auth-provider[data-id=${id}]`);\n  }\n\n  /** @function\n   * @name getFavoriteProvider\n   * Get favorite or default provider\n   * @returns {DOMNode} - The provider DOMNode or null\n   */\n  getFavoriteProvider() {\n    const id = localStorage.getItem('oidc_favorite_provider');\n    let provider = this.getProvider(id);\n    if (!provider) {\n      const providers = this.querySelectorAll('sib-auth-provider');\n      if (providers.length === 1) {\n        provider = providers.item(0);\n      }\n    }\n    return provider;\n  }\n\n  /** @function\n   * @name getProviders\n   * Get all providers\n   * @returns {DOMNodeList} - The provider DOMNodeList or null\n   */\n  getProviders() {\n    return this.querySelectorAll('sib-auth-provider');\n  }\n\n  /** @function\n   * @name setFavoriteProvider\n   * Set the favorite provider\n   */\n  // eslint-disable-next-line class-methods-use-this\n  setFavoriteProvider(id) {\n    localStorage.setItem('oidc_favorite_provider', id);\n  }\n\n  /** @function\n   * @name processState\n   * Try to get user, the if a state is set, call the appropriate provider\n   */\n  async processState() {\n    const { provider } = this.getState();\n    const providerElement = this.getProvider(provider);\n    if (providerElement) {\n      this.callProvider(providerElement, 'processState', this);\n    }\n  }\n\n  /** @function\n   * @name dispatchUserInfo\n   * @param {User} userWebId - User\n   * Try to replace data-src by userWebId iri on [bind-user] elements\n   */\n  async dispatchUserInfo() {\n    const processDOM = async () => {\n      const elements = document.querySelectorAll('[bind-user]');\n      elements.forEach((element) => this.applyUser(element));\n    };\n    // check document state and add a hook on DOMContentLoaded if needed\n    if (document.readyState === 'loading') {\n      document.addEventListener('DOMContentLoaded', processDOM);\n    } else {\n      processDOM();\n    }\n  }\n\n  /** @function\n   * @name applyUser\n   * @param {Element} element\n   */\n  async applyUser(element) {\n    const id = await this.getUserWebId();\n    if (id == null) return;\n    if (element.getAttribute(id === 'data-src')) return;\n    element.setAttribute('data-src', id);\n  }\n\n  /** @function\n   * @name getUserWebId\n   * Return User or undefined\n   * @return {User}\n   */\n  async getUserWebId() {\n    const session = await this.session;\n    if (!session) return null;\n    return session.webId;\n  }\n\n  /** @function\n   * @name getUserIdToken\n   * Return User DPOP ID Token or undefined\n   * @return {Token}\n   */\n  async getUserIdToken() {\n    await this.session; // wait for the redirect before getting the token\n    const response = await (0,_inrupt_solid_client_authn_browser__WEBPACK_IMPORTED_MODULE_0__.fetch)(`${this.getFavoriteProvider().attributes['data-authority'].value}check-session-headers/`);\n    const body = await response.json();\n    if (!body) return null;\n    return `${body.Authorization}|SEPARATOR|${body.dpop}`;\n  }\n\n  /** @function\n   * @name getUser\n   * Return user or null\n   * @return {User}\n   */\n  async getUser() {\n    const id = await this.getUserWebId();\n    if (!id) return null;\n    return { '@id': id };\n  }\n\n  /** @function\n   * @name login\n   * Try to login, if favorite provider is set, trigger login, if not, select provider\n   */\n  login() {\n    const favoriteProvider = this.getFavoriteProvider();\n    if (favoriteProvider) {\n      this.callProvider(favoriteProvider, 'login', this);\n    } else {\n      this.show();\n    }\n  }\n\n  /** @function\n   * @name logout\n   * Try to logout if favorite provider is set\n   */\n  logout() {\n    (0,_inrupt_solid_client_authn_browser__WEBPACK_IMPORTED_MODULE_0__.logout)()\n      .then(() => this.dispatchUserInfo())\n      .then(() => window.location.reload());\n  }\n\n  /** @function\n   * @name hide\n   * Hide provider selector\n   */\n  hide() {\n    this.initialDisplayStyle = this.style.display;\n    this.style.display = 'none';\n    this.removeEventListener('click', this.hide);\n  }\n\n  /** @function\n   * @name show\n   * Show provider selector, bind click event\n   */\n  show() {\n    const providers = this.getProviders();\n    providers.forEach((provider) => {\n      provider.onclick = () => {\n        this.setFavoriteProvider(provider.id);\n        this.callProvider(provider, 'login', this);\n      };\n    });\n    this.addEventListener('click', this.hide);\n    this.style.display = this.initialDisplayStyle;\n  }\n\n  /** @function\n   * @name callProvider\n   * Call provider method with args\n   * @param {SIBAuthProvider} provider - auth provider\n   * @param {string} method - the method to call\n   * @param args - arguments to pass\n   */\n  // eslint-disable-next-line class-methods-use-this\n  async callProvider(provider, method, ...args) {\n    await customElements.whenDefined('sib-auth-provider');\n    return provider[method](...args);\n  }\n\n  /**\n   * Returns the auth fetch method for other libs\n   * @returns function\n   */\n  // eslint-disable-next-line class-methods-use-this\n  getFetch() {\n    return _inrupt_solid_client_authn_browser__WEBPACK_IMPORTED_MODULE_0__.fetch;\n  }\n}\n\ncustomElements.define('sib-auth', SIBAuth);\n\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (SIBAuth);\n\n\n//# sourceURL=webpack://@startinblox/oidc/./src/sib-auth.js?");
+eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export */ __webpack_require__.d(__webpack_exports__, {\n/* harmony export */   \"default\": () => (__WEBPACK_DEFAULT_EXPORT__)\n/* harmony export */ });\n/* harmony import */ var _inrupt_solid_client_authn_browser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @inrupt/solid-client-authn-browser */ \"./node_modules/@inrupt/solid-client-authn-browser/dist/index.js\");\n/* harmony import */ var _inrupt_solid_client_authn_browser__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_inrupt_solid_client_authn_browser__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var _startinblox_core_dist_libs_helpers_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @startinblox/core/dist/libs/helpers.js */ \"./node_modules/@startinblox/core/dist/libs/helpers.js\");\n\n\n\n// Dev Mode\n// const baseUrl = import.meta.url.replace(/\\/[^/]*$/, '');\nconst baseUrl = 'https://cdn.skypack.dev/@startinblox/oidc@0.14';\n(0,_startinblox_core_dist_libs_helpers_js__WEBPACK_IMPORTED_MODULE_1__.importCSS)(`${baseUrl}/sib-auth.css`);\nclass SIBAuth extends HTMLElement {\n  /**\n   * @typedef {Object} State\n   * @property {string} provider auth provider id\n   * @property {string} value 'login' or 'logout' or null\n   * @property {token} string CRSF token\n   * @property {previousUri} string Previous uri\n   */\n\n  constructor() {\n    super();\n    this.provider = null;\n    this.user = null;\n    this.hide();\n    this.session = (0,_inrupt_solid_client_authn_browser__WEBPACK_IMPORTED_MODULE_0__.handleIncomingRedirect)({\n      restorePreviousSession: true,\n      url: window.location.href,\n    }).then(async (sessionInfo) => {\n      if (sessionInfo && sessionInfo.isLoggedIn) {\n        this.dispatchUserInfo();\n        return sessionInfo;\n      }\n      if (this.hasAttribute('auto-login')) this.login();\n      return null;\n    });\n  }\n\n  connectedCallback() {\n    this.install();\n\n    // Manage redirection on non root urls\n    (0,_inrupt_solid_client_authn_browser__WEBPACK_IMPORTED_MODULE_0__.onSessionRestore)((url) => {\n      window.history.replaceState({}, '', url);\n      this.dispatchEvent(\n        new CustomEvent('newUrl', { bubbles: true }),\n      );\n    });\n  }\n\n  /** @function\n   * @name disconnectedCallback\n   * Clear state and user, uninstall\n   */\n  disconnectedCallback() {\n    (0,_inrupt_solid_client_authn_browser__WEBPACK_IMPORTED_MODULE_0__.logout)();\n    this.uninstall();\n  }\n\n  /** @function\n   * @name install\n   * Replace all bind-user in document\n   */\n  install() {\n    this.bindUserObserver = new MutationObserver((mutations) => {\n      mutations.forEach((mutation) => {\n        if (mutation.type === 'attributes') {\n          if (!mutation.target.hasAttribute('bind-user')) return;\n          this.applyUser(mutation.target);\n          return;\n        }\n        mutation.addedNodes.forEach((node) => {\n          if (!(node instanceof Element)) return;\n          if (node.hasAttribute('bind-user')) this.applyUser(node);\n          if (node.querySelectorAll('[bind-user]').length) {\n            node.querySelectorAll('[bind-user]').forEach((element) => this.applyUser(element));\n          }\n        });\n      });\n    });\n    this.bindUserObserver.observe(document.body, {\n      childList: true,\n      attributes: true,\n      characterData: false,\n      subtree: true,\n      attributeOldValue: false,\n      attributeFilter: ['bind-user'],\n    });\n  }\n\n  /** @function\n   * @name uninstall\n   * Remove method and property previously added on SIBBase\n   */\n  uninstall() {\n    this.bindUserObserver.disconnect();\n  }\n\n  /** @function\n   * @name getProvider\n   * Get provider that match the id\n   * @param {string} id - the provider id\n   * @returns {DOMNode} - The provider DOMNode or null\n   */\n  getProvider(id) {\n    return this.querySelector(`sib-auth-provider[data-id=${id}]`);\n  }\n\n  /** @function\n   * @name getFavoriteProvider\n   * Get favorite or default provider\n   * @returns {DOMNode} - The provider DOMNode or null\n   */\n  getFavoriteProvider() {\n    const id = localStorage.getItem('oidc_favorite_provider');\n    let provider = this.getProvider(id);\n    if (!provider) {\n      const providers = this.querySelectorAll('sib-auth-provider');\n      if (providers.length === 1) {\n        provider = providers.item(0);\n      }\n    }\n    return provider;\n  }\n\n  /** @function\n   * @name getProviders\n   * Get all providers\n   * @returns {DOMNodeList} - The provider DOMNodeList or null\n   */\n  getProviders() {\n    return this.querySelectorAll('sib-auth-provider');\n  }\n\n  /** @function\n   * @name setFavoriteProvider\n   * Set the favorite provider\n   */\n  // eslint-disable-next-line class-methods-use-this\n  setFavoriteProvider(id) {\n    localStorage.setItem('oidc_favorite_provider', id);\n  }\n\n  /** @function\n   * @name processState\n   * Try to get user, the if a state is set, call the appropriate provider\n   */\n  async processState() {\n    const { provider } = this.getState();\n    const providerElement = this.getProvider(provider);\n    if (providerElement) {\n      this.callProvider(providerElement, 'processState', this);\n    }\n  }\n\n  /** @function\n   * @name dispatchUserInfo\n   * @param {User} userWebId - User\n   * Try to replace data-src by userWebId iri on [bind-user] elements\n   */\n  async dispatchUserInfo() {\n    const processDOM = async () => {\n      const elements = document.querySelectorAll('[bind-user]');\n      elements.forEach((element) => this.applyUser(element));\n    };\n    // check document state and add a hook on DOMContentLoaded if needed\n    if (document.readyState === 'loading') {\n      document.addEventListener('DOMContentLoaded', processDOM);\n    } else {\n      processDOM();\n    }\n  }\n\n  /** @function\n   * @name applyUser\n   * @param {Element} element\n   */\n  async applyUser(element) {\n    const id = await this.getUserWebId();\n    if (id == null) return;\n    if (element.getAttribute(id === 'data-src')) return;\n    element.setAttribute('data-src', id);\n  }\n\n  /** @function\n   * @name getUserWebId\n   * Return User or undefined\n   * @return {User}\n   */\n  async getUserWebId() {\n    const session = await this.session;\n    if (!session) return null;\n    return session.webId;\n  }\n\n  /** @function\n   * @name getUserIdToken\n   * Return User DPOP ID Token or undefined\n   * @return {Token}\n   */\n  async getUserIdToken() {\n    await this.session; // wait for the redirect before getting the token\n    const response = await (0,_inrupt_solid_client_authn_browser__WEBPACK_IMPORTED_MODULE_0__.fetch)(`${this.getFavoriteProvider().attributes['data-authority'].value}check-user/`);\n    const body = await response.json();\n    if (!body) return null;\n    return `${body.Authorization}|SEPARATOR|${body.dpop}`;\n  }\n\n  /** @function\n   * @name getUser\n   * Return user or null\n   * @return {User}\n   */\n  async getUser() {\n    const id = await this.getUserWebId();\n    if (!id) return null;\n    return { '@id': id };\n  }\n\n  /** @function\n   * @name login\n   * Try to login, if favorite provider is set, trigger login, if not, select provider\n   */\n  login() {\n    const favoriteProvider = this.getFavoriteProvider();\n    if (favoriteProvider) {\n      this.callProvider(favoriteProvider, 'login', this);\n    } else {\n      this.show();\n    }\n  }\n\n  /** @function\n   * @name logout\n   * Try to logout if favorite provider is set\n   */\n  logout() {\n    (0,_inrupt_solid_client_authn_browser__WEBPACK_IMPORTED_MODULE_0__.logout)()\n      .then(() => this.dispatchUserInfo())\n      .then(() => window.location.reload());\n  }\n\n  /** @function\n   * @name hide\n   * Hide provider selector\n   */\n  hide() {\n    this.initialDisplayStyle = this.style.display;\n    this.style.display = 'none';\n    this.removeEventListener('click', this.hide);\n  }\n\n  /** @function\n   * @name show\n   * Show provider selector, bind click event\n   */\n  show() {\n    const providers = this.getProviders();\n    providers.forEach((provider) => {\n      provider.onclick = () => {\n        this.setFavoriteProvider(provider.id);\n        this.callProvider(provider, 'login', this);\n      };\n    });\n    this.addEventListener('click', this.hide);\n    this.style.display = this.initialDisplayStyle;\n  }\n\n  /** @function\n   * @name callProvider\n   * Call provider method with args\n   * @param {SIBAuthProvider} provider - auth provider\n   * @param {string} method - the method to call\n   * @param args - arguments to pass\n   */\n  // eslint-disable-next-line class-methods-use-this\n  async callProvider(provider, method, ...args) {\n    await customElements.whenDefined('sib-auth-provider');\n    return provider[method](...args);\n  }\n\n  /**\n   * Returns the auth fetch method for other libs\n   * @returns function\n   */\n  // eslint-disable-next-line class-methods-use-this\n  getFetch() {\n    return _inrupt_solid_client_authn_browser__WEBPACK_IMPORTED_MODULE_0__.fetch;\n  }\n}\n\ncustomElements.define('sib-auth', SIBAuth);\n\n/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (SIBAuth);\n\n\n//# sourceURL=webpack://@startinblox/oidc/./src/sib-auth.js?");
 
 /***/ }),
 
diff --git a/src/sib-auth.js b/src/sib-auth.js
index f172559..01390a3 100644
--- a/src/sib-auth.js
+++ b/src/sib-auth.js
@@ -198,7 +198,7 @@ class SIBAuth extends HTMLElement {
    */
   async getUserIdToken() {
     await this.session; // wait for the redirect before getting the token
-    const response = await fetch(`${this.getFavoriteProvider().attributes['data-authority'].value}check-session-headers/`);
+    const response = await fetch(`${this.getFavoriteProvider().attributes['data-authority'].value}check-user/`);
     const body = await response.json();
     if (!body) return null;
     return `${body.Authorization}SEPARATOR${body.dpop}`;
-- 
GitLab