@propelauth/javascript
Advanced tools
@@ -209,3 +209,4 @@ 'use strict'; | ||
const LOGGED_OUT_AT_KEY = "__PROPEL_AUTH_LOGGED_OUT_AT"; | ||
const STALE_AUTH_INFO_THRESHOLD_SECS = 4 * 60; | ||
const AUTH_TOKEN_REFRESH_BEFORE_EXPIRATION_SECONDS = 4 * 60; | ||
const DEBOUNCE_DURATION_FOR_REFOCUS_SECONDS = 4 * 60; | ||
@@ -237,3 +238,4 @@ function validateAndCleanupOptions(authOptions) { | ||
authUrl: authOptions.authUrl, | ||
refreshInterval: null | ||
refreshInterval: null, | ||
lastRefresh: null | ||
}; // Helper functions | ||
@@ -288,2 +290,3 @@ | ||
clientState.lastRefresh = currentTimeSeconds(); | ||
clientState.initialLoadFinished = true; | ||
@@ -340,3 +343,3 @@ } | ||
return await forceRefreshToken(false); | ||
} else if (currentTimeSecs + STALE_AUTH_INFO_THRESHOLD_SECS > clientState.authenticationInfo.expiresAtSeconds) { | ||
} else if (currentTimeSecs + AUTH_TOKEN_REFRESH_BEFORE_EXPIRATION_SECONDS > clientState.authenticationInfo.expiresAtSeconds) { | ||
// Small edge case: If we were being proactive | ||
@@ -422,6 +425,11 @@ // and the auth information hasn't expired yet, swallow any exceptions | ||
}; // If we were offline or on a different tab, when we return, refetch auth info | ||
// Some browsers trigger focus more often than we'd like, so we'll debounce a little here as well | ||
const onOnlineOrFocus = async function () { | ||
await forceRefreshToken(true); | ||
if (clientState.lastRefresh && currentTimeSeconds() > clientState.lastRefresh + DEBOUNCE_DURATION_FOR_REFOCUS_SECONDS) { | ||
await forceRefreshToken(true); | ||
} else { | ||
await client.getAuthenticationInfoOrNull(); | ||
} | ||
}; | ||
@@ -428,0 +436,0 @@ |
@@ -205,3 +205,4 @@ let UserRole; | ||
const LOGGED_OUT_AT_KEY = "__PROPEL_AUTH_LOGGED_OUT_AT"; | ||
const STALE_AUTH_INFO_THRESHOLD_SECS = 4 * 60; | ||
const AUTH_TOKEN_REFRESH_BEFORE_EXPIRATION_SECONDS = 4 * 60; | ||
const DEBOUNCE_DURATION_FOR_REFOCUS_SECONDS = 4 * 60; | ||
@@ -233,3 +234,4 @@ function validateAndCleanupOptions(authOptions) { | ||
authUrl: authOptions.authUrl, | ||
refreshInterval: null | ||
refreshInterval: null, | ||
lastRefresh: null | ||
}; // Helper functions | ||
@@ -284,2 +286,3 @@ | ||
clientState.lastRefresh = currentTimeSeconds(); | ||
clientState.initialLoadFinished = true; | ||
@@ -336,3 +339,3 @@ } | ||
return await forceRefreshToken(false); | ||
} else if (currentTimeSecs + STALE_AUTH_INFO_THRESHOLD_SECS > clientState.authenticationInfo.expiresAtSeconds) { | ||
} else if (currentTimeSecs + AUTH_TOKEN_REFRESH_BEFORE_EXPIRATION_SECONDS > clientState.authenticationInfo.expiresAtSeconds) { | ||
// Small edge case: If we were being proactive | ||
@@ -418,6 +421,11 @@ // and the auth information hasn't expired yet, swallow any exceptions | ||
}; // If we were offline or on a different tab, when we return, refetch auth info | ||
// Some browsers trigger focus more often than we'd like, so we'll debounce a little here as well | ||
const onOnlineOrFocus = async function () { | ||
await forceRefreshToken(true); | ||
if (clientState.lastRefresh && currentTimeSeconds() > clientState.lastRefresh + DEBOUNCE_DURATION_FOR_REFOCUS_SECONDS) { | ||
await forceRefreshToken(true); | ||
} else { | ||
await client.getAuthenticationInfoOrNull(); | ||
} | ||
}; | ||
@@ -424,0 +432,0 @@ |
@@ -1,2 +0,2 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).PropelAuth={})}(this,(function(e){"use strict";var t;function n(t){return new Promise(((n,r)=>{const s=new XMLHttpRequest;s.onreadystatechange=function(){if(s.readyState===XMLHttpRequest.DONE){const a=s.status;if(a>=200&&a<300)try{const o=(t=s.responseText,JSON.parse(t,(function(t,n){if("org_id"===t)this.orgId=n;else if("org_name"===t)this.orgName=n;else if("url_safe_org_name"===t)this.urlSafeOrgName=n;else if("user_role"===t)this.userRole=(r=n,e.UserRole[r]);else if("access_token"===t)this.accessToken=n;else if("expires_at_seconds"===t)this.expiresAtSeconds=n;else if("org_id_to_org_member_info"===t)this.orgIdToOrgMemberInfo=n,this.orgHelper=(o=n,{getOrg:e=>o.hasOwnProperty(e)?o[e]:void 0,getOrgIds:()=>Object.keys(o),getOrgs:()=>Object.values(o),getOrgByName(e){for(const t of Object.values(o))if(t.orgName===e||t.urlSafeOrgName===e)return t}});else if("user_id"===t)this.userId=n;else if("email_confirmed"===t)this.emailConfirmed=n;else if("first_name"===t)this.firstName=n;else if("last_name"===t)this.lastName=n;else if("picture_url"===t)this.pictureUrl=n;else{if("mfa_enabled"!==t)return n;this.mfaEnabled=n}var o,r})));n(o)}catch(e){console.error("Unable to process authentication response",e),r({status:500,message:"Unable to process authentication response"})}else 401===a?n(null):0===a?(o(),r({status:503,message:"Unable to process authentication response"})):r({status:a,message:s.responseText})}var t},s.open("get",`${t}/api/v1/refresh_token`),s.withCredentials=!0,s.ontimeout=function(){r({status:408,message:"Request timed out"})},s.send(null)}))}function o(){console.error("Request to PropelAuth failed due to a CORS error. There are a few likely causes: \n 1. In the Frontend Integration section of your dashboard, make sure your requests are coming either the specified Application URL or localhost with a matching port.\n 2. Make sure your server is hosted on HTTPS in production.")}function r(){return Date.now()/1e3}function s(){return"undefined"!=typeof localStorage}function a(e){if(!s())return null;const t=localStorage.getItem(e);if(!t)return null;const n=parseInt(t,10);return Number.isNaN(n)?null:n}e.UserRole=void 0,(t=e.UserRole||(e.UserRole={}))[t.Member=0]="Member",t[t.Admin=1]="Admin",t[t.Owner=2]="Owner";const i="__PROPEL_AUTH_LOGGED_IN_AT",u="__PROPEL_AUTH_LOGGED_OUT_AT";e.createClient=function(e){!function(e){try{const t=new URL(e.authUrl);e.authUrl=t.origin}catch(e){throw console.error("Invalid authUrl",e),new Error("Unable to initialize auth client")}void 0===e.enableBackgroundTokenRefresh&&(e.enableBackgroundTokenRefresh=!0)}(e);const t={initialLoadFinished:!1,authenticationInfo:null,observers:[],lastLoggedInAtMessage:a(i),lastLoggedOutAtMessage:a(u),authUrl:e.authUrl,refreshInterval:null};function l(e){for(let n=0;n<t.observers.length;n++){const o=t.observers[n];o&&o(e)}}function c(e){var n;const o=null===(n=t.authenticationInfo)||void 0===n?void 0:n.accessToken;t.authenticationInfo=e;const s=null==e?void 0:e.accessToken;!function(e,n){return!e&&(n||!t.initialLoadFinished)}(s,o)?function(e,t){return!t&&e}(s,o)&&(l(!0),function(){const e=r();t.lastLoggedInAtMessage=e,localStorage.setItem(i,String(e))}()):(l(!1),function(){const e=r();t.lastLoggedOutAtMessage=e,localStorage.setItem(u,String(e))}()),t.initialLoadFinished=!0}async function d(e){try{const e=await n(t.authUrl);return c(e),e}catch(n){if(e)return t.authenticationInfo;throw c(null),n}}const f={addLoggedInChangeObserver(e){t.observers.includes(e)?console.error("Observer has been attached already."):e?t.observers.push(e):console.error("Cannot add a null observer")},removeLoggedInChangeObserver(e){const n=t.observers.indexOf(e);-1===n?console.error("Cannot find observer to remove"):t.observers.splice(n,1)},async getAuthenticationInfoOrNull(e){const n=r();if(e)return await d(!1);if(t.authenticationInfo){if(n+240>t.authenticationInfo.expiresAtSeconds){const e=n<t.authenticationInfo.expiresAtSeconds;return await d(e)}return t.authenticationInfo}return await d(!1)},redirectToSignupPage(){window.location.href=`${t.authUrl}/signup`},redirectToLoginPage(){window.location.href=`${t.authUrl}/login`},redirectToAccountPage(){window.location.href=`${t.authUrl}/account`},redirectToOrgPage(e){window.location.href=e?`${t.authUrl}/org?id=${e}`:`${t.authUrl}/org`},redirectToCreateOrgPage(){window.location.href=`${t.authUrl}/create_org`},async logout(e){const n=await(r=t.authUrl,new Promise(((e,t)=>{const n=new XMLHttpRequest;n.onreadystatechange=function(){if(n.readyState===XMLHttpRequest.DONE){const r=n.status;if(r>=200&&r<300){const t=JSON.parse(n.responseText);e(t)}else 0===r?(o(),t({status:503,message:"Unable to process authentication response"})):(console.error("Logout error",n.status,n.responseText),t({status:r,message:n.responseText}))}},n.open("post",`${r}/api/v1/logout`),n.withCredentials=!0,n.ontimeout=function(){t({status:408,message:"Request timed out"})},n.send(null)})));var r;c(null),e&&(window.location.href=n.redirect_to)},destroy(){t.observers=[],window.removeEventListener("storage",g),t.refreshInterval&&clearInterval(t.refreshInterval)}},g=async function(){if(!s())return;const e=a(u),n=a(i);e&&(!t.lastLoggedOutAtMessage||e>t.lastLoggedOutAtMessage)&&(t.lastLoggedOutAtMessage=e,t.authenticationInfo&&await d(!0)),n&&(!t.lastLoggedInAtMessage||n>t.lastLoggedInAtMessage)&&(t.lastLoggedInAtMessage=n,t.authenticationInfo||await d(!0))},h=async function(){await d(!0)};return"undefined"!=typeof window&&(window.addEventListener("storage",g),window.addEventListener("online",h),window.addEventListener("focus",h),e.enableBackgroundTokenRefresh&&(f.getAuthenticationInfoOrNull(),t.refreshInterval=window.setInterval(f.getAuthenticationInfoOrNull,6e4))),f}})); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).PropelAuth={})}(this,(function(e){"use strict";var t;function n(t){return new Promise(((n,r)=>{const s=new XMLHttpRequest;s.onreadystatechange=function(){if(s.readyState===XMLHttpRequest.DONE){const a=s.status;if(a>=200&&a<300)try{const o=(t=s.responseText,JSON.parse(t,(function(t,n){if("org_id"===t)this.orgId=n;else if("org_name"===t)this.orgName=n;else if("url_safe_org_name"===t)this.urlSafeOrgName=n;else if("user_role"===t)this.userRole=(r=n,e.UserRole[r]);else if("access_token"===t)this.accessToken=n;else if("expires_at_seconds"===t)this.expiresAtSeconds=n;else if("org_id_to_org_member_info"===t)this.orgIdToOrgMemberInfo=n,this.orgHelper=(o=n,{getOrg:e=>o.hasOwnProperty(e)?o[e]:void 0,getOrgIds:()=>Object.keys(o),getOrgs:()=>Object.values(o),getOrgByName(e){for(const t of Object.values(o))if(t.orgName===e||t.urlSafeOrgName===e)return t}});else if("user_id"===t)this.userId=n;else if("email_confirmed"===t)this.emailConfirmed=n;else if("first_name"===t)this.firstName=n;else if("last_name"===t)this.lastName=n;else if("picture_url"===t)this.pictureUrl=n;else{if("mfa_enabled"!==t)return n;this.mfaEnabled=n}var o,r})));n(o)}catch(e){console.error("Unable to process authentication response",e),r({status:500,message:"Unable to process authentication response"})}else 401===a?n(null):0===a?(o(),r({status:503,message:"Unable to process authentication response"})):r({status:a,message:s.responseText})}var t},s.open("get",`${t}/api/v1/refresh_token`),s.withCredentials=!0,s.ontimeout=function(){r({status:408,message:"Request timed out"})},s.send(null)}))}function o(){console.error("Request to PropelAuth failed due to a CORS error. There are a few likely causes: \n 1. In the Frontend Integration section of your dashboard, make sure your requests are coming either the specified Application URL or localhost with a matching port.\n 2. Make sure your server is hosted on HTTPS in production.")}function r(){return Date.now()/1e3}function s(){return"undefined"!=typeof localStorage}function a(e){if(!s())return null;const t=localStorage.getItem(e);if(!t)return null;const n=parseInt(t,10);return Number.isNaN(n)?null:n}e.UserRole=void 0,(t=e.UserRole||(e.UserRole={}))[t.Member=0]="Member",t[t.Admin=1]="Admin",t[t.Owner=2]="Owner";const i="__PROPEL_AUTH_LOGGED_IN_AT",l="__PROPEL_AUTH_LOGGED_OUT_AT";e.createClient=function(e){!function(e){try{const t=new URL(e.authUrl);e.authUrl=t.origin}catch(e){throw console.error("Invalid authUrl",e),new Error("Unable to initialize auth client")}void 0===e.enableBackgroundTokenRefresh&&(e.enableBackgroundTokenRefresh=!0)}(e);const t={initialLoadFinished:!1,authenticationInfo:null,observers:[],lastLoggedInAtMessage:a(i),lastLoggedOutAtMessage:a(l),authUrl:e.authUrl,refreshInterval:null,lastRefresh:null};function u(e){for(let n=0;n<t.observers.length;n++){const o=t.observers[n];o&&o(e)}}function c(e){var n;const o=null===(n=t.authenticationInfo)||void 0===n?void 0:n.accessToken;t.authenticationInfo=e;const s=null==e?void 0:e.accessToken;!function(e,n){return!e&&(n||!t.initialLoadFinished)}(s,o)?function(e,t){return!t&&e}(s,o)&&(u(!0),function(){const e=r();t.lastLoggedInAtMessage=e,localStorage.setItem(i,String(e))}()):(u(!1),function(){const e=r();t.lastLoggedOutAtMessage=e,localStorage.setItem(l,String(e))}()),t.lastRefresh=r(),t.initialLoadFinished=!0}async function f(e){try{const e=await n(t.authUrl);return c(e),e}catch(n){if(e)return t.authenticationInfo;throw c(null),n}}const d={addLoggedInChangeObserver(e){t.observers.includes(e)?console.error("Observer has been attached already."):e?t.observers.push(e):console.error("Cannot add a null observer")},removeLoggedInChangeObserver(e){const n=t.observers.indexOf(e);-1===n?console.error("Cannot find observer to remove"):t.observers.splice(n,1)},async getAuthenticationInfoOrNull(e){const n=r();if(e)return await f(!1);if(t.authenticationInfo){if(n+240>t.authenticationInfo.expiresAtSeconds){const e=n<t.authenticationInfo.expiresAtSeconds;return await f(e)}return t.authenticationInfo}return await f(!1)},redirectToSignupPage(){window.location.href=`${t.authUrl}/signup`},redirectToLoginPage(){window.location.href=`${t.authUrl}/login`},redirectToAccountPage(){window.location.href=`${t.authUrl}/account`},redirectToOrgPage(e){window.location.href=e?`${t.authUrl}/org?id=${e}`:`${t.authUrl}/org`},redirectToCreateOrgPage(){window.location.href=`${t.authUrl}/create_org`},async logout(e){const n=await(r=t.authUrl,new Promise(((e,t)=>{const n=new XMLHttpRequest;n.onreadystatechange=function(){if(n.readyState===XMLHttpRequest.DONE){const r=n.status;if(r>=200&&r<300){const t=JSON.parse(n.responseText);e(t)}else 0===r?(o(),t({status:503,message:"Unable to process authentication response"})):(console.error("Logout error",n.status,n.responseText),t({status:r,message:n.responseText}))}},n.open("post",`${r}/api/v1/logout`),n.withCredentials=!0,n.ontimeout=function(){t({status:408,message:"Request timed out"})},n.send(null)})));var r;c(null),e&&(window.location.href=n.redirect_to)},destroy(){t.observers=[],window.removeEventListener("storage",g),t.refreshInterval&&clearInterval(t.refreshInterval)}},g=async function(){if(!s())return;const e=a(l),n=a(i);e&&(!t.lastLoggedOutAtMessage||e>t.lastLoggedOutAtMessage)&&(t.lastLoggedOutAtMessage=e,t.authenticationInfo&&await f(!0)),n&&(!t.lastLoggedInAtMessage||n>t.lastLoggedInAtMessage)&&(t.lastLoggedInAtMessage=n,t.authenticationInfo||await f(!0))},h=async function(){t.lastRefresh&&r()>t.lastRefresh+240?await f(!0):await d.getAuthenticationInfoOrNull()};return"undefined"!=typeof window&&(window.addEventListener("storage",g),window.addEventListener("online",h),window.addEventListener("focus",h),e.enableBackgroundTokenRefresh&&(d.getAuthenticationInfoOrNull(),t.refreshInterval=window.setInterval(d.getAuthenticationInfoOrNull,6e4))),d}})); | ||
//# sourceMappingURL=javascript.min.js.map |
@@ -8,3 +8,3 @@ { | ||
}, | ||
"version": "1.2.3", | ||
"version": "1.2.4", | ||
"keywords": [ | ||
@@ -11,0 +11,0 @@ "auth", |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
135766
2.52%847
1.93%