@propelauth/javascript
Version:
A library for managing authentication in the browser, backed by PropelAuth
4 lines (3 loc) • 15.4 kB
JavaScript
!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((e="undefined"!=typeof globalThis?globalThis:e||self).PropelAuth={})}(this,function(e){"use strict";
/*! js-cookie v3.0.5 | MIT */function r(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var s in t)e[s]=t[s]}return e}var t=function e(t,s){function o(e,o,n){if("undefined"!=typeof document){"number"==typeof(n=r({},s,n)).expires&&(n.expires=new Date(Date.now()+864e5*n.expires)),n.expires&&(n.expires=n.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var i="";for(var a in n)n[a]&&(i+="; "+a,!0!==n[a]&&(i+="="+n[a].split(";")[0]));return document.cookie=e+"="+t.write(o,e)+i}}return Object.create({set:o,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var r=document.cookie?document.cookie.split("; "):[],s={},o=0;o<r.length;o++){var n=r[o].split("="),i=n.slice(1).join("=");try{var a=decodeURIComponent(n[0]);if(s[a]=t.read(i,a),e===a)break}catch(e){}}return e?s[e]:s}},remove:function(e,t){o(e,"",r({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,r({},this.attributes,t))},withConverter:function(t){return e(r({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(s)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});const s="active_org_id";let o=function(e){return e.SingleRole="single_role_in_hierarchy",e.MultiRole="multi_role",e}({});class n{constructor(e,r){this.userId=e.userId,this.orgIdToUserOrgInfo=r,this.email=e.email,this.firstName=e.firstName,this.lastName=e.lastName,this.username=e.username,this.createdAt=e.createdAt,this.pictureUrl=e.pictureUrl,this.hasPassword=e.hasPassword,this.hasMfaEnabled=e.hasMfaEnabled,this.canCreateOrgs=e.canCreateOrgs,this.legacyUserId=e.legacyUserId,this.impersonatorUserId=e.impersonatorUserId,this.properties=e.properties}getOrg(e){if(this.orgIdToUserOrgInfo)return this.orgIdToUserOrgInfo[e]}getOrgByName(e){if(!this.orgIdToUserOrgInfo)return;const r=e.toLowerCase().replace(/ /g,"-");for(const e in this.orgIdToUserOrgInfo){const t=this.orgIdToUserOrgInfo[e];if((null==t?void 0:t.urlSafeOrgName)===r)return t}}getUserProperty(e){if(this.properties)return this.properties[e]}getOrgs(){return this.orgIdToUserOrgInfo?Object.values(this.orgIdToUserOrgInfo):[]}isImpersonating(){return!!this.impersonatorUserId}isRole(e,r){const t=this.getOrg(e);return!!t&&t.isRole(r)}isAtLeastRole(e,r){const t=this.getOrg(e);return!!t&&t.isAtLeastRole(r)}hasPermission(e,r){const t=this.getOrg(e);return!!t&&t.hasPermission(r)}hasAllPermissions(e,r){const t=this.getOrg(e);return!!t&&t.hasAllPermissions(r)}static fromJSON(e){const r=JSON.parse(e),t={};for(const e in r.orgIdToUserOrgInfo)t[e]=i.fromJSON(JSON.stringify(r.orgIdToUserOrgInfo[e]));try{return new n({userId:r.userId,email:r.email,createdAt:r.createdAt,firstName:r.firstName,lastName:r.lastName,username:r.username,legacyUserId:r.legacyUserId,impersonatorUserId:r.impersonatorUserId,properties:r.properties,pictureUrl:r.pictureUrl,hasPassword:r.hasPassword,hasMfaEnabled:r.hasMfaEnabled,canCreateOrgs:r.canCreateOrgs},t)}catch(e){throw console.error("Unable to parse User. Make sure the JSON string is a stringified `UserClass` type.",e),e}}}class i{constructor(e,r,t,s,n,i,a,c,l,u){this.orgId=e,this.orgName=r,this.legacyOrgId=u,this.orgMetadata=t,this.urlSafeOrgName=s,this.orgRoleStructure=null!=c?c:o.SingleRole,this.userAssignedRole=n,this.userInheritedRolesPlusCurrentRole=i,this.userPermissions=a,this.userAssignedAdditionalRoles=null!=l?l:[]}isRole(e){return this.orgRoleStructure===o.MultiRole?this.userAssignedRole===e||this.userAssignedAdditionalRoles.includes(e):this.userAssignedRole===e}isAtLeastRole(e){return this.orgRoleStructure===o.MultiRole?this.userAssignedRole===e||this.userAssignedAdditionalRoles.includes(e):this.userInheritedRolesPlusCurrentRole.includes(e)}hasPermission(e){return this.userPermissions.includes(e)}hasAllPermissions(e){return e.every(e=>this.hasPermission(e))}static fromJSON(e){const r=JSON.parse(e);try{return new i(r.orgId,r.orgName,r.orgMetadata,r.urlSafeOrgName,r.userAssignedRole,r.userInheritedRolesPlusCurrentRole,r.userPermissions,r.orgRoleStructure,r.userAssignedAdditionalRoles,r.legacyOrgId)}catch(e){throw console.error("Unable to parse UserOrgInfo. Make sure the JSON string is a stringified `UserOrgInfo` type.",e),e}}}function a(e,r){const t=new URLSearchParams;r&&t.append("active_org_id",r);let s=`${e}/api/v1/refresh_token`;return t.toString()&&(s+=`?${t.toString()}`),fetch(s,{method:"GET",credentials:"include",headers:{"Content-Type":"application/json"}}).then(e=>401===e.status?null:0===e.status?(c(),Promise.reject({status:503,message:"Unable to process authentication response"})):e.ok?function(e){return e.text().then(e=>{try{return function(e){e.orgIdToOrgMemberInfo&&(e.orgHelper=(r=e.orgIdToOrgMemberInfo,{getOrg:e=>r.hasOwnProperty(e)?r[e]:void 0,getOrgIds:()=>Object.keys(r),getOrgs:()=>Object.values(r),getOrgByName(e){for(const t of Object.values(r))if(t.orgName===e||t.urlSafeOrgName===e)return t}}),e.accessHelper=function(e){function r(r,t){const s=e[r];return void 0!==s&&(s.orgRoleStructure===o.MultiRole?s.userAssignedRole===t||s.userAssignedAdditionalRoles.includes(t):s.userAssignedRole===t)}function t(r,t){const s=e[r];return void 0!==s&&(s.orgRoleStructure===o.MultiRole?s.userAssignedRole===t||s.userAssignedAdditionalRoles.includes(t):s.userInheritedRolesPlusCurrentRole.includes(t))}function s(r,t){const s=e[r];return void 0!==s&&s.userPermissions.includes(t)}function n(r,t){const s=e[r];return void 0!==s&&t.every(e=>s.userPermissions.includes(e))}return{isRole:r,isAtLeastRole:t,hasPermission:s,hasAllPermissions:n,getAccessHelperWithOrgId:function(e){return{isRole:t=>r(e,t),isAtLeastRole:r=>t(e,r),hasPermission:r=>s(e,r),hasAllPermissions:r=>n(e,r)}}}}(e.orgIdToOrgMemberInfo));var r;return e.userClass=new n({userId:e.user.userId,email:e.user.email,createdAt:e.user.createdAt,firstName:e.user.firstName,lastName:e.user.lastName,username:e.user.username,properties:e.user.properties,pictureUrl:e.user.pictureUrl,hasPassword:e.user.hasPassword,hasMfaEnabled:e.user.mfaEnabled,canCreateOrgs:e.user.canCreateOrgs,legacyUserId:e.user.legacyUserId,impersonatorUserId:e.impersonatorUserId},function(e){if(void 0===e)return;const r={};for(const t of Object.values(e))r[t.orgId]=new i(t.orgId,t.orgName,t.orgMetadata,t.urlSafeOrgName,t.userAssignedRole,t.userInheritedRolesPlusCurrentRole,t.userPermissions,t.orgRoleStructure,t.userAssignedAdditionalRoles,t.legacyOrgId);return r}(e.orgIdToOrgMemberInfo)),Promise.resolve(e)}((r=e,JSON.parse(r,function(e,r){if("org_id"===e)this.orgId=r;else if("org_name"===e)this.orgName=r;else if("org_metadata"===e)this.orgMetadata=r;else if("url_safe_org_name"===e)this.urlSafeOrgName=r;else if("user_role"===e)this.userAssignedRole=r;else if("inherited_user_roles_plus_current_role"===e)this.userInheritedRolesPlusCurrentRole=r;else if("user_permissions"===e)this.userPermissions=r;else if("access_token"===e)this.accessToken=r;else if("expires_at_seconds"===e)this.expiresAtSeconds=r;else if("org_id_to_org_member_info"===e)this.orgIdToOrgMemberInfo=r;else if("user_id"===e)this.userId=r;else if("email_confirmed"===e)this.emailConfirmed=r;else if("first_name"===e)this.firstName=r;else if("last_name"===e)this.lastName=r;else if("picture_url"===e)this.pictureUrl=r;else if("mfa_enabled"===e)this.mfaEnabled=r;else if("has_password"===e)this.hasPassword=r;else if("can_create_orgs"===e)this.canCreateOrgs=r;else if("created_at"===e)this.createdAt=r;else if("last_active_at"===e)this.lastActiveAt=r;else if("legacy_user_id"===e)this.legacyUserId=r;else if("legacy_org_id"===e)this.legacyOrgId=r;else if("impersonator_user"===e)this.impersonatorUserId=r;else if("org_role_structure"===e)this.orgRoleStructure=r;else{if("additional_roles"!==e)return r;this.userAssignedAdditionalRoles=r}})))}catch(e){return console.error("Unable to process authentication response",e),Promise.reject({status:500,message:"Unable to process authentication response"})}var r},e=>(console.error("Unable to process authentication response",e),Promise.reject({status:500,message:"Unable to process authentication response"})))}(e):Promise.reject({status:e.status,message:e.statusText}))}function c(){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.")}const l=async e=>u(e,3),u=async(e,r)=>{try{return await e()}catch(t){if(r<=0)throw t;return await d(g(r)),u(e,r-1)}},d=e=>new Promise(r=>setTimeout(r,e)),g=e=>e>=3?100:2===e?200:300;function h(){return Date.now()/1e3}function f(){return"undefined"!=typeof localStorage}function m(e){if(!f())return null;const r=localStorage.getItem(e);if(!r)return null;const t=parseInt(r,10);return Number.isNaN(t)?null:t}const p="__PROPEL_AUTH_LOGGED_IN_AT",I="__PROPEL_AUTH_LOGGED_OUT_AT",O=120,v=e=>(window?window.btoa:btoa)(e);e.ACTIVE_ORG_ID_COOKIE_NAME=s,e.OrgMemberInfoClass=i,e.UserClass=n,e.createClient=function(e){const{minSecondsBeforeRefresh:r=O}=e;!function(e){try{const r=new URL(e.authUrl);e.authUrl=r.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:[],accessTokenObservers:[],lastLoggedInAtMessage:m(p),lastLoggedOutAtMessage:m(I),authUrl:e.authUrl,refreshInterval:null,lastRefresh:null,accessTokenActiveOrgMap:{}};function s(e){for(let r=0;r<t.observers.length;r++){const s=t.observers[r];s&&s(e)}}function o(e){var r;const o=null===(r=t.authenticationInfo)||void 0===r?void 0:r.accessToken;t.authenticationInfo=e;const n=null==e?void 0:e.accessToken;!function(e,r){return!e&&(r||!t.initialLoadFinished)}(n,o)?function(e,r){return!r&&e}(n,o)&&(s(!0),function(){const e=h();t.lastLoggedInAtMessage=e,f()&&localStorage.setItem(p,String(e))}()):(s(!1),function(){const e=h();t.lastLoggedOutAtMessage=e,f()&&localStorage.setItem(I,String(e))}()),o!==n&&function(e){for(let r=0;r<t.accessTokenObservers.length;r++){const s=t.accessTokenObservers[r];s&&s(e)}}(n),t.accessTokenActiveOrgMap={},t.lastRefresh=h(),t.initialLoadFinished=!0}async function n(e){try{const e=await l(()=>a(t.authUrl));return o(e),e}catch(r){if(e)return t.authenticationInfo;throw o(null),r}}const i=e=>{let r=new URLSearchParams,s=`${t.authUrl}/signup`;if(e){const{postSignupRedirectUrl:t,userSignupQueryParameters:s}=e;t&&r.set("rt",v(t)),s&&Object.entries(s).forEach(([e,t])=>{r.set(e,t)})}return r.toString()&&(s+=`?${r.toString()}`),s},u=e=>{let r=new URLSearchParams,s=`${t.authUrl}/login`;if(e){const{postLoginRedirectUrl:t,userSignupQueryParameters:s}=e;t&&r.set("rt",v(t)),s&&Object.entries(s).forEach(([e,t])=>{r.set(e,t)})}return r.toString()&&(s+=`?${r.toString()}`),s},d=e=>{let r=new URLSearchParams,s=`${t.authUrl}/account`;if(e){const{redirectBackToUrl:t}=e;t&&r.set("rt",v(t))}return r.toString()&&(s+=`?${r.toString()}`),s},g=(e,r)=>{let s=new URLSearchParams,o=`${t.authUrl}/org`;return e&&s.set("id",e),r&&r.redirectBackToUrl&&s.set("rt",v(r.redirectBackToUrl)),s.toString()&&(o+=`?${s.toString()}`),o},U=e=>{let r=new URLSearchParams,s=`${t.authUrl}/create_org`;if(e){const{redirectBackToUrl:t}=e;t&&r.set("rt",v(t))}return r.toString()&&(s+=`?${r.toString()}`),s},A=(e,r)=>{let s=new URLSearchParams;return r&&r.redirectBackToUrl&&s.set("rt",v(r.redirectBackToUrl)),s.set("id",e),`${t.authUrl}/saml?${s.toString()}`},R={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 r=t.observers.indexOf(e);-1===r?console.error("Cannot find observer to remove"):t.observers.splice(r,1)},addAccessTokenChangeObserver(e){t.accessTokenObservers.includes(e)?console.error("Observer has been attached already."):e?t.accessTokenObservers.push(e):console.error("Cannot add a null observer")},removeAccessTokenChangeObserver(e){const r=t.accessTokenObservers.indexOf(e);-1===r?console.error("Cannot find observer to remove"):t.accessTokenObservers.splice(r,1)},async getAuthenticationInfoOrNull(e){const r=h();if(e)return await n(!1);if(t.authenticationInfo){if(r+600>t.authenticationInfo.expiresAtSeconds){const e=r<t.authenticationInfo.expiresAtSeconds;return await n(e)}return t.authenticationInfo}return await n(!1)},async getAccessTokenForOrg(e){const r=h(),s=t.accessTokenActiveOrgMap[e];if(s&&r<s.fetchedAt+300)return{accessToken:s.accessToken,error:void 0};try{const s=await l(()=>a(t.authUrl,e));if(!s)return{error:"user_not_in_org",accessToken:null};const{accessToken:o}=s;return t.accessTokenActiveOrgMap[e]={accessToken:o,fetchedAt:r},{accessToken:o,error:void 0}}catch(e){return{error:"unexpected_error",accessToken:null}}},getSignupPageUrl:e=>i(e),getLoginPageUrl:e=>u(e),getAccountPageUrl:e=>d(e),getOrgPageUrl:(e,r)=>g(e,r),getCreateOrgPageUrl:e=>U(e),getSetupSAMLPageUrl:(e,r)=>A(e,r),redirectToSignupPage(e){window.location.href=i(e)},redirectToLoginPage(e){window.location.href=u(e)},redirectToAccountPage(e){window.location.href=d(e)},redirectToOrgPage(e,r){window.location.href=g(e,r)},redirectToCreateOrgPage(e){window.location.href=U(e)},redirectToSetupSAMLPage(e,r){window.location.href=A(e,r)},async logout(e){const r=await(s=t.authUrl,fetch(`${s}/api/v1/logout`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"}}).then(e=>0===e.status?(c(),Promise.reject({status:503,message:"Unable to process authentication response"})):e.ok?e.json():(console.error("Logout error",e.status,e.statusText),Promise.reject({status:e.status,message:e.statusText}))));var s;o(null),e&&(window.location.href=r.redirect_to)},destroy(){t.observers=[],t.accessTokenObservers=[],window.removeEventListener("storage",w),window.removeEventListener("online",b),e.disableRefreshOnFocus||window.removeEventListener("focus",b),t.refreshInterval&&clearInterval(t.refreshInterval)}},w=async function(){if(!f())return;const e=m(I),r=m(p);e&&(!t.lastLoggedOutAtMessage||e>t.lastLoggedOutAtMessage)&&(t.lastLoggedOutAtMessage=e,t.authenticationInfo&&await n(!0)),r&&(!t.lastLoggedInAtMessage||r>t.lastLoggedInAtMessage)&&(t.lastLoggedInAtMessage=r,t.authenticationInfo||await n(!0))},b=async function(){t.lastRefresh&&h()>t.lastRefresh+r?await n(!0):await R.getAuthenticationInfoOrNull()};return"undefined"!=typeof window&&(window.addEventListener("storage",w),window.addEventListener("online",b),e.disableRefreshOnFocus||window.addEventListener("focus",b),e.enableBackgroundTokenRefresh&&(R.getAuthenticationInfoOrNull(),t.refreshInterval=window.setInterval(R.getAuthenticationInfoOrNull,6e4))),R},e.getActiveOrgId=()=>t.get(s),e.setActiveOrgId=e=>{t.set(s,e,{sameSite:"lax",secure:!0})}});
//# sourceMappingURL=javascript.min.js.map