@smart-cloud/gatey-core 2.3.7 → 2.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/package.json +2 -2
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var x=Object.defineProperty;var ee=Object.getOwnPropertyDescriptor;var te=Object.getOwnPropertyNames;var re=Object.prototype.hasOwnProperty;var ne=(e,t)=>{for(var r in t)x(e,r,{get:t[r],enumerable:!0})},oe=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of te(t))!re.call(e,o)&&o!==r&&x(e,o,{get:()=>t[o],enumerable:!(n=ee(t,o))||n.enumerable});return e};var ie=e=>oe(x({},"__esModule",{value:!0}),e);var Ae={};ne(Ae,{TEXT_DOMAIN:()=>j,clearMfaPreferences:()=>N,configureAmplify:()=>T,getAmplifyConfig:()=>E,getGateyPlugin:()=>s,getGroups:()=>R,getMfaPreferences:()=>k,getPreferredRole:()=>W,getRoles:()=>z,getScopes:()=>B,getStore:()=>p,getStoreDispatch:()=>y,getStoreSelect:()=>G,getUserAttributes:()=>_,initializeGatey:()=>me,isAuthenticated:()=>D,isInGroup:()=>M,loadAuthSession:()=>m,loadMFAPreferences:()=>L,loadUserAttributes:()=>F,login:()=>$,logout:()=>b,observeStore:()=>C,resolveGateyRedirectTarget:()=>V,resolveGateyTarget:()=>l,sanitizeAuthenticatorConfig:()=>I,store:()=>ye,waitForGateyReady:()=>U});module.exports=ie(Ae);var a=require("aws-amplify/api");function s(){return globalThis.WpSuite?.plugins?.gatey}function l(e){let t=e?.trim();if(t)try{if(/^[a-z][a-z\d+.-]*:/i.test(t))return new URL(t).toString();let n=s()?.siteUrl?.trim()||window.location.href,o=t.startsWith("/")?t.replace(/^\/+/,""):t;return new URL(o,n).toString()}catch{return t}}function V(e){let t=e?.trim();if(!t)return;let r=/^[a-z][a-z\d+.-]*:/i.test(t),n=t.startsWith("/");if(!r&&!n)return l(t);try{let o=new URL(window.location.href),c=new URL(t,o.origin);return c.origin===o.origin?c.toString():void 0}catch{return}}async function U(e=8e3){let t=s();if(t?.status!=="available"){if(t?.status==="error")throw new Error("Gatey failed");await new Promise((r,n)=>{let o=()=>d(r),c=()=>d(()=>n(new Error("Gatey failed"))),d=u=>{window.removeEventListener("wpsuite:gatey:ready",o),window.removeEventListener("wpsuite:gatey:error",c),S&&clearTimeout(S),u()};window.addEventListener("wpsuite:gatey:ready",o,{once:!0}),window.addEventListener("wpsuite:gatey:error",c,{once:!0});let S=e?window.setTimeout(()=>d(()=>n(new Error("Gatey timeout"))),e):0})}}async function p(e=1e4){await U(e);let r=s()?.cognito?.store;if(!r)throw new Error("Gatey store is not available");return r}var O=require("aws-amplify"),i=require("aws-amplify/auth");var K=require("@smart-cloud/wpsuite-core"),X=require("aws-amplify/auth"),v=require("aws-amplify/utils"),g=require("@wordpress/data"),J=require("@smart-cloud/wpsuite-core");var P="gatey_account",j="gatey";var w=e=>{e?.username?window.localStorage.setItem(P,JSON.stringify(e)):window.localStorage.removeItem(P)},A=async e=>{let t=JSON.parse(window.localStorage.getItem(P)??"{}"),r=!1;if(t?.username)try{let n=await(0,X.fetchAuthSession)();n?.tokens?.accessToken?.payload?.exp&&n.tokens.accessToken.payload.exp>new Date().getTime()/1e3&&(r=!0)}catch(n){console.error(n)}else try{t=await q(!1),t?.username&&(w(t),t.loaded=!0,r=!0)}catch(n){console.error(n)}return!r&&t?.username&&(w({}),p().then(async n=>{await b(e?.signOutHook),y(n).clearAccount()})),t},se=async e=>{let t=window.location.hostname.toLowerCase().split(":")[0],r=s();if(!r)throw new Error("Gatey plugin is not available");let n=l(r.settings?.signInPage)??window.location.origin,o=r.settings?.secondaryUserPoolDomains&&t.toLowerCase().match(r.settings.secondaryUserPoolDomains.toLowerCase())&&r.settings?.userPoolConfigurations.secondary?.Auth?.Cognito?.userPoolId?r.settings?.userPoolConfigurations.secondary:r.settings?.userPoolConfigurations.default,c={Auth:{Cognito:{userPoolClientId:"",userPoolId:"",identityPoolId:"",...o.Auth?.Cognito,loginWith:{oauth:{domain:"",scopes:[],responseType:"code",...o.Auth?.Cognito?.loginWith?.oauth,redirectSignIn:[n],redirectSignOut:[n]}}}},API:{...o.API,REST:{...o.API?.REST,admin:{endpoint:r.restUrl}}}},d=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default;d?.apis?.forEach(u=>{let h=c.API?.REST;h&&(h[u.name]={endpoint:u.endpoint,region:u.region})}),T(c,{API:{REST:{headers:async u=>{let h=d?.apis?.find(f=>f.name===u.apiName);if(u.apiName==="admin"||h?.authorization==="ID_TOKEN"||h?.authorization==="ACCESS_TOKEN")try{let f=await m();if(f?.tokens?.idToken&&f?.tokens?.accessToken)return{Authorization:`Bearer ${u.apiName==="admin"||h?.authorization==="ID_TOKEN"?f.tokens.idToken.toString():f.tokens.accessToken.toString()}`}}catch(f){console.error(f),p().then(Z=>{y(Z).clearAccount()})}return{}}}}})},ae=async()=>{let e=s();if(!e)throw new Error("Gatey plugin is not available");return(0,K.getCustomTranslations)({legacyUrl:e.settings.customTranslationsUrl})},I=e=>{let t=e&&typeof e=="object"?e:{},r={customProviders:Array.isArray(t.customProviders)?t.customProviders:[],formFields:Array.isArray(t.formFields)?t.formFields:[],apiConfigurations:typeof t.apiConfigurations=="object"&&t.apiConfigurations?t.apiConfigurations:{default:{apis:[]}}};return typeof t.subscriptionType=="string"&&(r.subscriptionType=t.subscriptionType),r},ue=async()=>{let e=I(await(0,J.getConfig)("gatey"));se(e);let t=window.location.hostname.toLowerCase().split(":")[0],r=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default,n=await A(r),o=await ae();return{config:e,amplifyConfig:{},account:n,signedIn:!!n?.username&&!n.loaded,nextUrl:void 0,language:void 0,direction:void 0,customTranslations:o,reloadAuthSession:0,reloadUserAttributes:0,reloadMFAPreferences:0}},ce={setAmplifyConfig(e){return{type:"SET_AMPLIFY_CONFIG",amplifyConfig:e}},setAccount(e){return{type:"SET_ACCOUNT",account:e}},clearAccount(){return{type:"CLEAR_ACCOUNT"}},setSignedIn(e){return{type:"SET_SIGNED_IN",signedIn:e}},setNextUrl(e){return{type:"SET_NEXT_URL",nextUrl:e}},setLanguage(e){return!e||e==="system"?v.I18n.setLanguage(""):v.I18n.setLanguage(e),{type:"SET_LANGUAGE",language:e}},setDirection(e){return{type:"SET_DIRECTION",direction:e}},reloadAuthSession(){return{type:"RELOAD_AUTH_SESSION"}},reloadUserAttributes(){return{type:"RELOAD_USER_ATTRIBUTES"}},reloadMFAPreferences(){return{type:"RELOAD_MFA_PREFERENCE"}}},ge={getAmplifyConfig(e){return e.amplifyConfig},getAccount(e){return e.account},getNextUrl(e){return e.nextUrl},isSignedIn(e){return e.signedIn},getConfig(e){return e.config},getCustomTranslations(e){return e.customTranslations},getLanguage(e){return e.language},getDirection(e){return e.direction},getState(e){return e}},le={},y=e=>(0,g.dispatch)(e),G=e=>(0,g.select)(e),Y=async()=>{let e=await ue(),t=(0,g.createReduxStore)("smartcloud/gatey",{reducer(r=e,n){switch(n.type){case"SET_AMPLIFY_CONFIG":return{...r,amplifyConfig:n.amplifyConfig};case"SET_ACCOUNT":return w(n.account),{...r,account:n.account};case"CLEAR_ACCOUNT":return w({}),{...r,account:{}};case"RELOAD_AUTH_SESSION":{let o=Math.random();return{...r,reloadAuthSession:r.reloadAuthSession!==o?o:o+1}}case"RELOAD_USER_ATTRIBUTES":{let o=Math.random();return{...r,reloadUserAttributes:r.reloadUserAttributes!==o?o:o+1}}case"RELOAD_MFA_PREFERENCE":{let o=Math.random();return{...r,reloadMFAPreferences:r.reloadMFAPreferences!==o?o:o+1}}case"SET_SIGNED_IN":return{...r,signedIn:n.signedIn};case"SET_NEXT_URL":return{...r,nextUrl:n.nextUrl};case"SET_LANGUAGE":return{...r,language:n.language};case"SET_DIRECTION":return{...r,direction:n.direction}}return r},actions:ce,selectors:ge,resolvers:le});return(0,g.register)(t),t},C=(e,t,r)=>{let n;function o(){let d=G(e).getState(),S=t(d);if(S!==n){let u=n;n=S,r(n,u)}}let c=(0,g.subscribe)(o,e);return o(),c};var E=()=>O.Amplify.getConfig(),T=(e,t)=>{O.Amplify.configure(e,t)},m=e=>(0,i.fetchAuthSession)(e),F=()=>(0,i.fetchUserAttributes)(),L=()=>(0,i.fetchMFAPreference)(),q=async(e=!0)=>{let t=e?await A():{};if(t?.username)return t;try{if((await(0,i.fetchAuthSession)()).tokens)return{username:(await(0,i.getCurrentUser)()).username,userAttributes:await F(),mfaPreferences:await L()}}catch(r){console.error(r);try{await(0,i.signOut)()}catch{}}return{}},N=async()=>{await(0,i.updateMFAPreference)({totp:"DISABLED"})},H=()=>A().then(e=>e?.username),_=()=>A().then(e=>e?.userAttributes),k=()=>A().then(e=>e?.mfaPreferences),D=()=>A().then(e=>!!e?.username),M=e=>R().then(t=>t?.includes(e)||!1),R=()=>m().then(e=>e.tokens?.idToken?.payload["cognito:groups"]instanceof Array?e.tokens.idToken.payload["cognito:groups"].map(t=>t):[]).catch(e=>{console.error(e)}),z=async()=>m().then(e=>e.tokens?.idToken?.payload["cognito:roles"]instanceof Array?e.tokens.idToken.payload["cognito:roles"].map(t=>t).map(t=>t.substring(t.indexOf("/")+1)):[]).catch(e=>{console.error(e)}),W=async()=>m().then(e=>{if(!e.tokens?.idToken?.payload["cognito:preferred_role"])return;let t=e.tokens.idToken.payload["cognito:preferred_role"];return t.substring(t.indexOf("/")+1)}).catch(e=>{console.error(e)}),B=()=>m().then(e=>e.tokens?.accessToken.payload.scope?.split(" ")??[]).catch(e=>{console.error(e)}),$=async e=>{let t,r=s();if(!r)throw new Error("Gatey plugin is not available");return r.settings.integrateWpLogin&&r.restUrl?.startsWith("http")&&(t=await r.cognito.post({apiName:"admin",path:"/login"}).response.then(o=>o.body.json()).then(o=>{if(o instanceof Object&&"redirect"in o)return o?.redirect}).catch(o=>{console.error(o)})),e&&await r.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(n=>console.error(n)),l(r.settings.redirectSignIn)??t},b=async e=>{let t=s();if(!t)throw new Error("Gatey plugin is not available");let r;t.settings.integrateWpLogin&&(r=await t.cognito.get({apiName:"admin",path:"/logout"}).response.then(n=>n.body.json()).then(n=>{if(n instanceof Object&&"redirect"in n)return n?.redirect}).catch(n=>{console.error(n)})),e&&await t.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(n=>console.error(n));try{await(0,i.signOut)()}catch{}return l(t.settings.redirectSignOut)??r??l(t.settings.signInPage)??"/"};var Q=require("@smart-cloud/wpsuite-core");var pe=()=>{p().then(e=>{C(e,t=>t.nextUrl,async t=>{t&&window.location.assign(t)}),y(e).clearAccount()}).catch(e=>{console.error("Gatey signOut error:",e)})},de=e=>{p().then(t=>{y(t).setLanguage(e??"en")}).catch(t=>{console.error("Gatey setLanguage error:",t)})},fe=e=>{p().then(t=>{y(t).setDirection(e??"auto")}).catch(t=>{console.error("Gatey setDirection error:",t)})};var ye=async()=>p(),me=()=>{let e=globalThis.WpSuite,t=s();if(!t)throw new Error("Gatey plugin is not available");(0,Q.attachDefaultPluginRuntime)(t),t.status=t.status??"initializing";let r=Y();return t.cognito={store:r,observeStore:C,setLanguage:de,setDirection:fe,getAmplifyConfig:E,isAuthenticated:D,isInGroup:M,getUsername:H,getUserAttributes:_,getMfaPreferences:k,clearMfaPreferences:N,getGroups:R,getRoles:z,getPreferredRole:W,getScopes:B,signOut:pe,get:a.get,post:a.post,put:a.put,del:a.del,head:a.head,patch:a.patch},r.then(()=>{t.status="available",e?.events?.emit("wpsuite:gatey:ready",{key:t.key,version:t.version})}).catch(n=>{t.status="error",e?.events?.emit("wpsuite:gatey:error",{key:t.key,error:String(n)})}),t};0&&(module.exports={TEXT_DOMAIN,clearMfaPreferences,configureAmplify,getAmplifyConfig,getGateyPlugin,getGroups,getMfaPreferences,getPreferredRole,getRoles,getScopes,getStore,getStoreDispatch,getStoreSelect,getUserAttributes,initializeGatey,isAuthenticated,isInGroup,loadAuthSession,loadMFAPreferences,loadUserAttributes,login,logout,observeStore,resolveGateyRedirectTarget,resolveGateyTarget,sanitizeAuthenticatorConfig,store,waitForGateyReady});
|
|
1
|
+
"use strict";var v=Object.defineProperty;var re=Object.getOwnPropertyDescriptor;var ne=Object.getOwnPropertyNames;var oe=Object.prototype.hasOwnProperty;var ie=(e,t)=>{for(var r in t)v(e,r,{get:t[r],enumerable:!0})},se=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ne(t))!oe.call(e,o)&&o!==r&&v(e,o,{get:()=>t[o],enumerable:!(n=re(t,o))||n.enumerable});return e};var ae=e=>se(v({},"__esModule",{value:!0}),e);var he={};ie(he,{TEXT_DOMAIN:()=>X,clearMfaPreferences:()=>_,configureAmplify:()=>b,getAmplifyConfig:()=>x,getGateyPlugin:()=>s,getGroups:()=>U,getMfaPreferences:()=>M,getPreferredRole:()=>V,getRoles:()=>B,getScopes:()=>K,getStore:()=>p,getStoreDispatch:()=>y,getStoreSelect:()=>F,getUserAttributes:()=>D,initializeGatey:()=>Se,isAuthenticated:()=>z,isInGroup:()=>W,loadAuthSession:()=>m,loadMFAPreferences:()=>k,loadUserAttributes:()=>N,login:()=>Z,logout:()=>E,observeStore:()=>P,resolveGateyRedirectTarget:()=>j,resolveGateyTarget:()=>l,sanitizeAuthenticatorConfig:()=>O,store:()=>Ae,waitForGateyReady:()=>I});module.exports=ae(he);var a=require("aws-amplify/api");function s(){return globalThis.WpSuite?.plugins?.gatey}function l(e){let t=e?.trim();if(t)try{if(/^[a-z][a-z\d+.-]*:/i.test(t))return new URL(t).toString();let n=s()?.siteUrl?.trim()||window.location.href,o=t.startsWith("/")?t.replace(/^\/+/,""):t;return new URL(o,n).toString()}catch{return t}}function j(e){let t=e?.trim();if(!t)return;let r=/^[a-z][a-z\d+.-]*:/i.test(t),n=t.startsWith("/");if(!r&&!n)return l(t);try{let o=new URL(window.location.href),c=new URL(t,o.origin);return c.origin===o.origin?c.toString():void 0}catch{return}}async function I(e=8e3){let t=s();if(t?.status!=="available"){if(t?.status==="error")throw new Error("Gatey failed");await new Promise((r,n)=>{let o=()=>d(r),c=()=>d(()=>n(new Error("Gatey failed"))),d=u=>{window.removeEventListener("wpsuite:gatey:ready",o),window.removeEventListener("wpsuite:gatey:error",c),S&&clearTimeout(S),u()};window.addEventListener("wpsuite:gatey:ready",o,{once:!0}),window.addEventListener("wpsuite:gatey:error",c,{once:!0});let S=e?window.setTimeout(()=>d(()=>n(new Error("Gatey timeout"))),e):0})}}async function p(e=1e4){await I(e);let r=s()?.cognito?.store;if(!r)throw new Error("Gatey store is not available");return r}var L=require("aws-amplify"),$=require("aws-amplify/auth/cognito"),R=require("@smart-cloud/wpsuite-core"),i=require("aws-amplify/auth");var J=require("@smart-cloud/wpsuite-core"),Y=require("aws-amplify/auth"),G=require("aws-amplify/utils"),g=require("@wordpress/data"),C=require("@smart-cloud/wpsuite-core");var w="gatey_account",X="gatey";var T=e=>{e?.username?window.localStorage.setItem((0,C.backendProfileStorageKey)(w),JSON.stringify(e)):window.localStorage.removeItem((0,C.backendProfileStorageKey)(w))},A=async e=>{let t=JSON.parse(window.localStorage.getItem((0,C.backendProfileStorageKey)(w))??"{}"),r=!1;if(t?.username)try{let n=await(0,Y.fetchAuthSession)();n?.tokens?.accessToken?.payload?.exp&&n.tokens.accessToken.payload.exp>new Date().getTime()/1e3&&(r=!0)}catch(n){console.error(n)}else try{t=await H(!1),t?.username&&(T(t),t.loaded=!0,r=!0)}catch(n){console.error(n)}return!r&&t?.username&&(T({}),p().then(async n=>{await E(e?.signOutHook),y(n).clearAccount()})),t},ue=async e=>{let t=window.location.hostname.toLowerCase().split(":")[0],r=s();if(!r)throw new Error("Gatey plugin is not available");let n=l(r.settings?.signInPage)??window.location.origin,o=r.settings?.secondaryUserPoolDomains&&t.toLowerCase().match(r.settings.secondaryUserPoolDomains.toLowerCase())&&r.settings?.userPoolConfigurations.secondary?.Auth?.Cognito?.userPoolId?r.settings?.userPoolConfigurations.secondary:r.settings?.userPoolConfigurations.default,c={Auth:{Cognito:{userPoolClientId:"",userPoolId:"",identityPoolId:"",...o.Auth?.Cognito,loginWith:{oauth:{domain:"",scopes:[],responseType:"code",...o.Auth?.Cognito?.loginWith?.oauth,redirectSignIn:[n],redirectSignOut:[n]}}}},API:{...o.API,REST:{...o.API?.REST,admin:{endpoint:r.restUrl}}}},d=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default;d?.apis?.forEach(u=>{let h=c.API?.REST;h&&(h[u.name]={endpoint:u.endpoint,region:u.region})}),b(c,{API:{REST:{headers:async u=>{let h=d?.apis?.find(f=>f.name===u.apiName);if(u.apiName==="admin"||h?.authorization==="ID_TOKEN"||h?.authorization==="ACCESS_TOKEN")try{let f=await m();if(f?.tokens?.idToken&&f?.tokens?.accessToken)return{Authorization:`Bearer ${u.apiName==="admin"||h?.authorization==="ID_TOKEN"?f.tokens.idToken.toString():f.tokens.accessToken.toString()}`}}catch(f){console.error(f),p().then(te=>{y(te).clearAccount()})}return{}}}}})},ce=async()=>{let e=s();if(!e)throw new Error("Gatey plugin is not available");return(0,J.getCustomTranslations)({legacyUrl:e.settings.customTranslationsUrl})},O=e=>{let t=e&&typeof e=="object"?e:{},r={customProviders:Array.isArray(t.customProviders)?t.customProviders:[],formFields:Array.isArray(t.formFields)?t.formFields:[],apiConfigurations:typeof t.apiConfigurations=="object"&&t.apiConfigurations?t.apiConfigurations:{default:{apis:[]}}};return typeof t.subscriptionType=="string"&&(r.subscriptionType=t.subscriptionType),r},ge=async()=>{let e=O(await(0,C.getConfig)("gatey"));ue(e);let t=window.location.hostname.toLowerCase().split(":")[0],r=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default,n=await A(r),o=await ce();return{config:e,amplifyConfig:{},account:n,signedIn:!!n?.username&&!n.loaded,nextUrl:void 0,language:void 0,direction:void 0,customTranslations:o,reloadAuthSession:0,reloadUserAttributes:0,reloadMFAPreferences:0}},le={setAmplifyConfig(e){return{type:"SET_AMPLIFY_CONFIG",amplifyConfig:e}},setAccount(e){return{type:"SET_ACCOUNT",account:e}},clearAccount(){return{type:"CLEAR_ACCOUNT"}},setSignedIn(e){return{type:"SET_SIGNED_IN",signedIn:e}},setNextUrl(e){return{type:"SET_NEXT_URL",nextUrl:e}},setLanguage(e){return!e||e==="system"?G.I18n.setLanguage(""):G.I18n.setLanguage(e),{type:"SET_LANGUAGE",language:e}},setDirection(e){return{type:"SET_DIRECTION",direction:e}},reloadAuthSession(){return{type:"RELOAD_AUTH_SESSION"}},reloadUserAttributes(){return{type:"RELOAD_USER_ATTRIBUTES"}},reloadMFAPreferences(){return{type:"RELOAD_MFA_PREFERENCE"}}},pe={getAmplifyConfig(e){return e.amplifyConfig},getAccount(e){return e.account},getNextUrl(e){return e.nextUrl},isSignedIn(e){return e.signedIn},getConfig(e){return e.config},getCustomTranslations(e){return e.customTranslations},getLanguage(e){return e.language},getDirection(e){return e.direction},getState(e){return e}},de={},y=e=>(0,g.dispatch)(e),F=e=>(0,g.select)(e),q=async()=>{let e=await ge(),t=(0,g.createReduxStore)("smartcloud/gatey",{reducer(r=e,n){switch(n.type){case"SET_AMPLIFY_CONFIG":return{...r,amplifyConfig:n.amplifyConfig};case"SET_ACCOUNT":return T(n.account),{...r,account:n.account};case"CLEAR_ACCOUNT":return T({}),{...r,account:{}};case"RELOAD_AUTH_SESSION":{let o=Math.random();return{...r,reloadAuthSession:r.reloadAuthSession!==o?o:o+1}}case"RELOAD_USER_ATTRIBUTES":{let o=Math.random();return{...r,reloadUserAttributes:r.reloadUserAttributes!==o?o:o+1}}case"RELOAD_MFA_PREFERENCE":{let o=Math.random();return{...r,reloadMFAPreferences:r.reloadMFAPreferences!==o?o:o+1}}case"SET_SIGNED_IN":return{...r,signedIn:n.signedIn};case"SET_NEXT_URL":return{...r,nextUrl:n.nextUrl};case"SET_LANGUAGE":return{...r,language:n.language};case"SET_DIRECTION":return{...r,direction:n.direction}}return r},actions:le,selectors:pe,resolvers:de});return(0,g.register)(t),t},P=(e,t,r)=>{let n;function o(){let d=F(e).getState(),S=t(d);if(S!==n){let u=n;n=S,r(n,u)}}let c=(0,g.subscribe)(o,e);return o(),c};var x=()=>L.Amplify.getConfig(),b=(e,t)=>{let r=(0,R.getBackendProfileContext)()?(0,R.createBackendProfileStorage)(window.localStorage):void 0;r&&$.cognitoUserPoolsTokenProvider.setKeyValueStorage(r),L.Amplify.configure(e,t)},m=e=>(0,i.fetchAuthSession)(e),N=()=>(0,i.fetchUserAttributes)(),k=()=>(0,i.fetchMFAPreference)(),H=async(e=!0)=>{let t=e?await A():{};if(t?.username)return t;try{if((await(0,i.fetchAuthSession)()).tokens)return{username:(await(0,i.getCurrentUser)()).username,userAttributes:await N(),mfaPreferences:await k()}}catch(r){console.error(r);try{await(0,i.signOut)()}catch{}}return{}},_=async()=>{await(0,i.updateMFAPreference)({totp:"DISABLED"})},Q=()=>A().then(e=>e?.username),D=()=>A().then(e=>e?.userAttributes),M=()=>A().then(e=>e?.mfaPreferences),z=()=>A().then(e=>!!e?.username),W=e=>U().then(t=>t?.includes(e)||!1),U=()=>m().then(e=>e.tokens?.idToken?.payload["cognito:groups"]instanceof Array?e.tokens.idToken.payload["cognito:groups"].map(t=>t):[]).catch(e=>{console.error(e)}),B=async()=>m().then(e=>e.tokens?.idToken?.payload["cognito:roles"]instanceof Array?e.tokens.idToken.payload["cognito:roles"].map(t=>t).map(t=>t.substring(t.indexOf("/")+1)):[]).catch(e=>{console.error(e)}),V=async()=>m().then(e=>{if(!e.tokens?.idToken?.payload["cognito:preferred_role"])return;let t=e.tokens.idToken.payload["cognito:preferred_role"];return t.substring(t.indexOf("/")+1)}).catch(e=>{console.error(e)}),K=()=>m().then(e=>e.tokens?.accessToken.payload.scope?.split(" ")??[]).catch(e=>{console.error(e)}),Z=async e=>{let t,r=s();if(!r)throw new Error("Gatey plugin is not available");return r.settings.integrateWpLogin&&r.restUrl?.startsWith("http")&&(t=await r.cognito.post({apiName:"admin",path:"/login"}).response.then(o=>o.body.json()).then(o=>{if(o instanceof Object&&"redirect"in o)return o?.redirect}).catch(o=>{console.error(o)})),e&&await r.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(n=>console.error(n)),l(r.settings.redirectSignIn)??t},E=async e=>{let t=s();if(!t)throw new Error("Gatey plugin is not available");let r;t.settings.integrateWpLogin&&(r=await t.cognito.get({apiName:"admin",path:"/logout"}).response.then(n=>n.body.json()).then(n=>{if(n instanceof Object&&"redirect"in n)return n?.redirect}).catch(n=>{console.error(n)})),e&&await t.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(n=>console.error(n));try{await(0,i.signOut)()}catch{}return l(t.settings.redirectSignOut)??r??l(t.settings.signInPage)??"/"};var ee=require("@smart-cloud/wpsuite-core");var fe=()=>{p().then(e=>{P(e,t=>t.nextUrl,async t=>{t&&window.location.assign(t)}),y(e).clearAccount()}).catch(e=>{console.error("Gatey signOut error:",e)})},ye=e=>{p().then(t=>{y(t).setLanguage(e??"en")}).catch(t=>{console.error("Gatey setLanguage error:",t)})},me=e=>{p().then(t=>{y(t).setDirection(e??"auto")}).catch(t=>{console.error("Gatey setDirection error:",t)})};var Ae=async()=>p(),Se=()=>{let e=globalThis.WpSuite,t=s();if(!t)throw new Error("Gatey plugin is not available");(0,ee.attachDefaultPluginRuntime)(t),t.status=t.status??"initializing";let r=q();return t.cognito={store:r,observeStore:P,setLanguage:ye,setDirection:me,getAmplifyConfig:x,isAuthenticated:z,isInGroup:W,getUsername:Q,getUserAttributes:D,getMfaPreferences:M,clearMfaPreferences:_,getGroups:U,getRoles:B,getPreferredRole:V,getScopes:K,signOut:fe,get:a.get,post:a.post,put:a.put,del:a.del,head:a.head,patch:a.patch},r.then(()=>{t.status="available",e?.events?.emit("wpsuite:gatey:ready",{key:t.key,version:t.version})}).catch(n=>{t.status="error",e?.events?.emit("wpsuite:gatey:error",{key:t.key,error:String(n)})}),t};0&&(module.exports={TEXT_DOMAIN,clearMfaPreferences,configureAmplify,getAmplifyConfig,getGateyPlugin,getGroups,getMfaPreferences,getPreferredRole,getRoles,getScopes,getStore,getStoreDispatch,getStoreSelect,getUserAttributes,initializeGatey,isAuthenticated,isInGroup,loadAuthSession,loadMFAPreferences,loadUserAttributes,login,logout,observeStore,resolveGateyRedirectTarget,resolveGateyTarget,sanitizeAuthenticatorConfig,store,waitForGateyReady});
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{del as pe,get as de,head as fe,patch as ye,post as me,put as Ae}from"aws-amplify/api";function s(){return globalThis.WpSuite?.plugins?.gatey}function g(e){let t=e?.trim();if(t)try{if(/^[a-z][a-z\d+.-]*:/i.test(t))return new URL(t).toString();let n=s()?.siteUrl?.trim()||window.location.href,o=t.startsWith("/")?t.replace(/^\/+/,""):t;return new URL(o,n).toString()}catch{return t}}function K(e){let t=e?.trim();if(!t)return;let r=/^[a-z][a-z\d+.-]*:/i.test(t),n=t.startsWith("/");if(!r&&!n)return g(t);try{let o=new URL(window.location.href),a=new URL(t,o.origin);return a.origin===o.origin?a.toString():void 0}catch{return}}async function b(e=8e3){let t=s();if(t?.status!=="available"){if(t?.status==="error")throw new Error("Gatey failed");await new Promise((r,n)=>{let o=()=>u(r),a=()=>u(()=>n(new Error("Gatey failed"))),u=i=>{window.removeEventListener("wpsuite:gatey:ready",o),window.removeEventListener("wpsuite:gatey:error",a),y&&clearTimeout(y),i()};window.addEventListener("wpsuite:gatey:ready",o,{once:!0}),window.addEventListener("wpsuite:gatey:error",a,{once:!0});let y=e?window.setTimeout(()=>u(()=>n(new Error("Gatey timeout"))),e):0})}}async function l(e=1e4){await b(e);let r=s()?.cognito?.store;if(!r)throw new Error("Gatey store is not available");return r}import{Amplify as I}from"aws-amplify";import{fetchAuthSession as G,fetchMFAPreference as ae,fetchUserAttributes as ue,getCurrentUser as ce,signOut as O,updateMFAPreference as ge}from"aws-amplify/auth";import{getCustomTranslations as J}from"@smart-cloud/wpsuite-core";import{fetchAuthSession as Y}from"aws-amplify/auth";import{I18n as E}from"aws-amplify/utils";import{createReduxStore as q,dispatch as H,register as $,select as Q,subscribe as Z}from"@wordpress/data";import{getConfig as ee}from"@smart-cloud/wpsuite-core";var A="gatey_account",X="gatey";var S=e=>{e?.username?window.localStorage.setItem(A,JSON.stringify(e)):window.localStorage.removeItem(A)},p=async e=>{let t=JSON.parse(window.localStorage.getItem(A)??"{}"),r=!1;if(t?.username)try{let n=await Y();n?.tokens?.accessToken?.payload?.exp&&n.tokens.accessToken.payload.exp>new Date().getTime()/1e3&&(r=!0)}catch(n){console.error(n)}else try{t=await v(!1),t?.username&&(S(t),t.loaded=!0,r=!0)}catch(n){console.error(n)}return!r&&t?.username&&(S({}),l().then(async n=>{await P(e?.signOutHook),d(n).clearAccount()})),t},te=async e=>{let t=window.location.hostname.toLowerCase().split(":")[0],r=s();if(!r)throw new Error("Gatey plugin is not available");let n=g(r.settings?.signInPage)??window.location.origin,o=r.settings?.secondaryUserPoolDomains&&t.toLowerCase().match(r.settings.secondaryUserPoolDomains.toLowerCase())&&r.settings?.userPoolConfigurations.secondary?.Auth?.Cognito?.userPoolId?r.settings?.userPoolConfigurations.secondary:r.settings?.userPoolConfigurations.default,a={Auth:{Cognito:{userPoolClientId:"",userPoolId:"",identityPoolId:"",...o.Auth?.Cognito,loginWith:{oauth:{domain:"",scopes:[],responseType:"code",...o.Auth?.Cognito?.loginWith?.oauth,redirectSignIn:[n],redirectSignOut:[n]}}}},API:{...o.API,REST:{...o.API?.REST,admin:{endpoint:r.restUrl}}}},u=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default;u?.apis?.forEach(i=>{let m=a.API?.REST;m&&(m[i.name]={endpoint:i.endpoint,region:i.region})}),C(a,{API:{REST:{headers:async i=>{let m=u?.apis?.find(c=>c.name===i.apiName);if(i.apiName==="admin"||m?.authorization==="ID_TOKEN"||m?.authorization==="ACCESS_TOKEN")try{let c=await f();if(c?.tokens?.idToken&&c?.tokens?.accessToken)return{Authorization:`Bearer ${i.apiName==="admin"||m?.authorization==="ID_TOKEN"?c.tokens.idToken.toString():c.tokens.accessToken.toString()}`}}catch(c){console.error(c),l().then(j=>{d(j).clearAccount()})}return{}}}}})},re=async()=>{let e=s();if(!e)throw new Error("Gatey plugin is not available");return J({legacyUrl:e.settings.customTranslationsUrl})},R=e=>{let t=e&&typeof e=="object"?e:{},r={customProviders:Array.isArray(t.customProviders)?t.customProviders:[],formFields:Array.isArray(t.formFields)?t.formFields:[],apiConfigurations:typeof t.apiConfigurations=="object"&&t.apiConfigurations?t.apiConfigurations:{default:{apis:[]}}};return typeof t.subscriptionType=="string"&&(r.subscriptionType=t.subscriptionType),r},ne=async()=>{let e=R(await ee("gatey"));te(e);let t=window.location.hostname.toLowerCase().split(":")[0],r=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default,n=await p(r),o=await re();return{config:e,amplifyConfig:{},account:n,signedIn:!!n?.username&&!n.loaded,nextUrl:void 0,language:void 0,direction:void 0,customTranslations:o,reloadAuthSession:0,reloadUserAttributes:0,reloadMFAPreferences:0}},oe={setAmplifyConfig(e){return{type:"SET_AMPLIFY_CONFIG",amplifyConfig:e}},setAccount(e){return{type:"SET_ACCOUNT",account:e}},clearAccount(){return{type:"CLEAR_ACCOUNT"}},setSignedIn(e){return{type:"SET_SIGNED_IN",signedIn:e}},setNextUrl(e){return{type:"SET_NEXT_URL",nextUrl:e}},setLanguage(e){return!e||e==="system"?E.setLanguage(""):E.setLanguage(e),{type:"SET_LANGUAGE",language:e}},setDirection(e){return{type:"SET_DIRECTION",direction:e}},reloadAuthSession(){return{type:"RELOAD_AUTH_SESSION"}},reloadUserAttributes(){return{type:"RELOAD_USER_ATTRIBUTES"}},reloadMFAPreferences(){return{type:"RELOAD_MFA_PREFERENCE"}}},ie={getAmplifyConfig(e){return e.amplifyConfig},getAccount(e){return e.account},getNextUrl(e){return e.nextUrl},isSignedIn(e){return e.signedIn},getConfig(e){return e.config},getCustomTranslations(e){return e.customTranslations},getLanguage(e){return e.language},getDirection(e){return e.direction},getState(e){return e}},se={},d=e=>H(e),x=e=>Q(e),U=async()=>{let e=await ne(),t=q("smartcloud/gatey",{reducer(r=e,n){switch(n.type){case"SET_AMPLIFY_CONFIG":return{...r,amplifyConfig:n.amplifyConfig};case"SET_ACCOUNT":return S(n.account),{...r,account:n.account};case"CLEAR_ACCOUNT":return S({}),{...r,account:{}};case"RELOAD_AUTH_SESSION":{let o=Math.random();return{...r,reloadAuthSession:r.reloadAuthSession!==o?o:o+1}}case"RELOAD_USER_ATTRIBUTES":{let o=Math.random();return{...r,reloadUserAttributes:r.reloadUserAttributes!==o?o:o+1}}case"RELOAD_MFA_PREFERENCE":{let o=Math.random();return{...r,reloadMFAPreferences:r.reloadMFAPreferences!==o?o:o+1}}case"SET_SIGNED_IN":return{...r,signedIn:n.signedIn};case"SET_NEXT_URL":return{...r,nextUrl:n.nextUrl};case"SET_LANGUAGE":return{...r,language:n.language};case"SET_DIRECTION":return{...r,direction:n.direction}}return r},actions:oe,selectors:ie,resolvers:se});return $(t),t},h=(e,t,r)=>{let n;function o(){let u=x(e).getState(),y=t(u);if(y!==n){let i=n;n=y,r(n,i)}}let a=Z(o,e);return o(),a};var w=()=>I.getConfig(),C=(e,t)=>{I.configure(e,t)},f=e=>G(e),F=()=>ue(),L=()=>ae(),v=async(e=!0)=>{let t=e?await p():{};if(t?.username)return t;try{if((await G()).tokens)return{username:(await ce()).username,userAttributes:await F(),mfaPreferences:await L()}}catch(r){console.error(r);try{await O()}catch{}}return{}},N=async()=>{await ge({totp:"DISABLED"})},_=()=>p().then(e=>e?.username),k=()=>p().then(e=>e?.userAttributes),D=()=>p().then(e=>e?.mfaPreferences),M=()=>p().then(e=>!!e?.username),z=e=>T().then(t=>t?.includes(e)||!1),T=()=>f().then(e=>e.tokens?.idToken?.payload["cognito:groups"]instanceof Array?e.tokens.idToken.payload["cognito:groups"].map(t=>t):[]).catch(e=>{console.error(e)}),W=async()=>f().then(e=>e.tokens?.idToken?.payload["cognito:roles"]instanceof Array?e.tokens.idToken.payload["cognito:roles"].map(t=>t).map(t=>t.substring(t.indexOf("/")+1)):[]).catch(e=>{console.error(e)}),B=async()=>f().then(e=>{if(!e.tokens?.idToken?.payload["cognito:preferred_role"])return;let t=e.tokens.idToken.payload["cognito:preferred_role"];return t.substring(t.indexOf("/")+1)}).catch(e=>{console.error(e)}),V=()=>f().then(e=>e.tokens?.accessToken.payload.scope?.split(" ")??[]).catch(e=>{console.error(e)}),le=async e=>{let t,r=s();if(!r)throw new Error("Gatey plugin is not available");return r.settings.integrateWpLogin&&r.restUrl?.startsWith("http")&&(t=await r.cognito.post({apiName:"admin",path:"/login"}).response.then(o=>o.body.json()).then(o=>{if(o instanceof Object&&"redirect"in o)return o?.redirect}).catch(o=>{console.error(o)})),e&&await r.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(n=>console.error(n)),g(r.settings.redirectSignIn)??t},P=async e=>{let t=s();if(!t)throw new Error("Gatey plugin is not available");let r;t.settings.integrateWpLogin&&(r=await t.cognito.get({apiName:"admin",path:"/logout"}).response.then(n=>n.body.json()).then(n=>{if(n instanceof Object&&"redirect"in n)return n?.redirect}).catch(n=>{console.error(n)})),e&&await t.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(n=>console.error(n));try{await O()}catch{}return g(t.settings.redirectSignOut)??r??g(t.settings.signInPage)??"/"};import{attachDefaultPluginRuntime as Se}from"@smart-cloud/wpsuite-core";var he=()=>{l().then(e=>{h(e,t=>t.nextUrl,async t=>{t&&window.location.assign(t)}),d(e).clearAccount()}).catch(e=>{console.error("Gatey signOut error:",e)})},Ce=e=>{l().then(t=>{d(t).setLanguage(e??"en")}).catch(t=>{console.error("Gatey setLanguage error:",t)})},Pe=e=>{l().then(t=>{d(t).setDirection(e??"auto")}).catch(t=>{console.error("Gatey setDirection error:",t)})};var je=async()=>l(),Ke=()=>{let e=globalThis.WpSuite,t=s();if(!t)throw new Error("Gatey plugin is not available");Se(t),t.status=t.status??"initializing";let r=U();return t.cognito={store:r,observeStore:h,setLanguage:Ce,setDirection:Pe,getAmplifyConfig:w,isAuthenticated:M,isInGroup:z,getUsername:_,getUserAttributes:k,getMfaPreferences:D,clearMfaPreferences:N,getGroups:T,getRoles:W,getPreferredRole:B,getScopes:V,signOut:he,get:de,post:me,put:Ae,del:pe,head:fe,patch:ye},r.then(()=>{t.status="available",e?.events?.emit("wpsuite:gatey:ready",{key:t.key,version:t.version})}).catch(n=>{t.status="error",e?.events?.emit("wpsuite:gatey:error",{key:t.key,error:String(n)})}),t};export{X as TEXT_DOMAIN,N as clearMfaPreferences,C as configureAmplify,w as getAmplifyConfig,s as getGateyPlugin,T as getGroups,D as getMfaPreferences,B as getPreferredRole,W as getRoles,V as getScopes,l as getStore,d as getStoreDispatch,x as getStoreSelect,k as getUserAttributes,Ke as initializeGatey,M as isAuthenticated,z as isInGroup,f as loadAuthSession,L as loadMFAPreferences,F as loadUserAttributes,le as login,P as logout,h as observeStore,K as resolveGateyRedirectTarget,g as resolveGateyTarget,R as sanitizeAuthenticatorConfig,je as store,b as waitForGateyReady};
|
|
1
|
+
import{del as me,get as Ae,head as Se,patch as he,post as Ce,put as Pe}from"aws-amplify/api";function s(){return globalThis.WpSuite?.plugins?.gatey}function g(e){let t=e?.trim();if(t)try{if(/^[a-z][a-z\d+.-]*:/i.test(t))return new URL(t).toString();let n=s()?.siteUrl?.trim()||window.location.href,o=t.startsWith("/")?t.replace(/^\/+/,""):t;return new URL(o,n).toString()}catch{return t}}function X(e){let t=e?.trim();if(!t)return;let r=/^[a-z][a-z\d+.-]*:/i.test(t),n=t.startsWith("/");if(!r&&!n)return g(t);try{let o=new URL(window.location.href),a=new URL(t,o.origin);return a.origin===o.origin?a.toString():void 0}catch{return}}async function E(e=8e3){let t=s();if(t?.status!=="available"){if(t?.status==="error")throw new Error("Gatey failed");await new Promise((r,n)=>{let o=()=>u(r),a=()=>u(()=>n(new Error("Gatey failed"))),u=i=>{window.removeEventListener("wpsuite:gatey:ready",o),window.removeEventListener("wpsuite:gatey:error",a),y&&clearTimeout(y),i()};window.addEventListener("wpsuite:gatey:ready",o,{once:!0}),window.addEventListener("wpsuite:gatey:error",a,{once:!0});let y=e?window.setTimeout(()=>u(()=>n(new Error("Gatey timeout"))),e):0})}}async function l(e=1e4){await E(e);let r=s()?.cognito?.store;if(!r)throw new Error("Gatey store is not available");return r}import{Amplify as G}from"aws-amplify";import{cognitoUserPoolsTokenProvider as ue}from"aws-amplify/auth/cognito";import{createBackendProfileStorage as ce,getBackendProfileContext as ge}from"@smart-cloud/wpsuite-core";import{fetchAuthSession as O,fetchMFAPreference as le,fetchUserAttributes as pe,getCurrentUser as de,signOut as F,updateMFAPreference as fe}from"aws-amplify/auth";import{getCustomTranslations as Y}from"@smart-cloud/wpsuite-core";import{fetchAuthSession as q}from"aws-amplify/auth";import{I18n as R}from"aws-amplify/utils";import{createReduxStore as H,dispatch as $,register as Q,select as Z,subscribe as ee}from"@wordpress/data";import{getConfig as te,backendProfileStorageKey as C}from"@smart-cloud/wpsuite-core";var A="gatey_account",J="gatey";var S=e=>{e?.username?window.localStorage.setItem(C(A),JSON.stringify(e)):window.localStorage.removeItem(C(A))},p=async e=>{let t=JSON.parse(window.localStorage.getItem(C(A))??"{}"),r=!1;if(t?.username)try{let n=await q();n?.tokens?.accessToken?.payload?.exp&&n.tokens.accessToken.payload.exp>new Date().getTime()/1e3&&(r=!0)}catch(n){console.error(n)}else try{t=await I(!1),t?.username&&(S(t),t.loaded=!0,r=!0)}catch(n){console.error(n)}return!r&&t?.username&&(S({}),l().then(async n=>{await w(e?.signOutHook),d(n).clearAccount()})),t},re=async e=>{let t=window.location.hostname.toLowerCase().split(":")[0],r=s();if(!r)throw new Error("Gatey plugin is not available");let n=g(r.settings?.signInPage)??window.location.origin,o=r.settings?.secondaryUserPoolDomains&&t.toLowerCase().match(r.settings.secondaryUserPoolDomains.toLowerCase())&&r.settings?.userPoolConfigurations.secondary?.Auth?.Cognito?.userPoolId?r.settings?.userPoolConfigurations.secondary:r.settings?.userPoolConfigurations.default,a={Auth:{Cognito:{userPoolClientId:"",userPoolId:"",identityPoolId:"",...o.Auth?.Cognito,loginWith:{oauth:{domain:"",scopes:[],responseType:"code",...o.Auth?.Cognito?.loginWith?.oauth,redirectSignIn:[n],redirectSignOut:[n]}}}},API:{...o.API,REST:{...o.API?.REST,admin:{endpoint:r.restUrl}}}},u=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default;u?.apis?.forEach(i=>{let m=a.API?.REST;m&&(m[i.name]={endpoint:i.endpoint,region:i.region})}),P(a,{API:{REST:{headers:async i=>{let m=u?.apis?.find(c=>c.name===i.apiName);if(i.apiName==="admin"||m?.authorization==="ID_TOKEN"||m?.authorization==="ACCESS_TOKEN")try{let c=await f();if(c?.tokens?.idToken&&c?.tokens?.accessToken)return{Authorization:`Bearer ${i.apiName==="admin"||m?.authorization==="ID_TOKEN"?c.tokens.idToken.toString():c.tokens.accessToken.toString()}`}}catch(c){console.error(c),l().then(j=>{d(j).clearAccount()})}return{}}}}})},ne=async()=>{let e=s();if(!e)throw new Error("Gatey plugin is not available");return Y({legacyUrl:e.settings.customTranslationsUrl})},x=e=>{let t=e&&typeof e=="object"?e:{},r={customProviders:Array.isArray(t.customProviders)?t.customProviders:[],formFields:Array.isArray(t.formFields)?t.formFields:[],apiConfigurations:typeof t.apiConfigurations=="object"&&t.apiConfigurations?t.apiConfigurations:{default:{apis:[]}}};return typeof t.subscriptionType=="string"&&(r.subscriptionType=t.subscriptionType),r},oe=async()=>{let e=x(await te("gatey"));re(e);let t=window.location.hostname.toLowerCase().split(":")[0],r=e?.apiConfigurations?.secondary?.domains&&t.toLowerCase().match(e.apiConfigurations.secondary?.domains.toLowerCase())&&e.apiConfigurations?.secondary?.apis?.length?e.apiConfigurations.secondary:e?.apiConfigurations?.default,n=await p(r),o=await ne();return{config:e,amplifyConfig:{},account:n,signedIn:!!n?.username&&!n.loaded,nextUrl:void 0,language:void 0,direction:void 0,customTranslations:o,reloadAuthSession:0,reloadUserAttributes:0,reloadMFAPreferences:0}},ie={setAmplifyConfig(e){return{type:"SET_AMPLIFY_CONFIG",amplifyConfig:e}},setAccount(e){return{type:"SET_ACCOUNT",account:e}},clearAccount(){return{type:"CLEAR_ACCOUNT"}},setSignedIn(e){return{type:"SET_SIGNED_IN",signedIn:e}},setNextUrl(e){return{type:"SET_NEXT_URL",nextUrl:e}},setLanguage(e){return!e||e==="system"?R.setLanguage(""):R.setLanguage(e),{type:"SET_LANGUAGE",language:e}},setDirection(e){return{type:"SET_DIRECTION",direction:e}},reloadAuthSession(){return{type:"RELOAD_AUTH_SESSION"}},reloadUserAttributes(){return{type:"RELOAD_USER_ATTRIBUTES"}},reloadMFAPreferences(){return{type:"RELOAD_MFA_PREFERENCE"}}},se={getAmplifyConfig(e){return e.amplifyConfig},getAccount(e){return e.account},getNextUrl(e){return e.nextUrl},isSignedIn(e){return e.signedIn},getConfig(e){return e.config},getCustomTranslations(e){return e.customTranslations},getLanguage(e){return e.language},getDirection(e){return e.direction},getState(e){return e}},ae={},d=e=>$(e),U=e=>Z(e),v=async()=>{let e=await oe(),t=H("smartcloud/gatey",{reducer(r=e,n){switch(n.type){case"SET_AMPLIFY_CONFIG":return{...r,amplifyConfig:n.amplifyConfig};case"SET_ACCOUNT":return S(n.account),{...r,account:n.account};case"CLEAR_ACCOUNT":return S({}),{...r,account:{}};case"RELOAD_AUTH_SESSION":{let o=Math.random();return{...r,reloadAuthSession:r.reloadAuthSession!==o?o:o+1}}case"RELOAD_USER_ATTRIBUTES":{let o=Math.random();return{...r,reloadUserAttributes:r.reloadUserAttributes!==o?o:o+1}}case"RELOAD_MFA_PREFERENCE":{let o=Math.random();return{...r,reloadMFAPreferences:r.reloadMFAPreferences!==o?o:o+1}}case"SET_SIGNED_IN":return{...r,signedIn:n.signedIn};case"SET_NEXT_URL":return{...r,nextUrl:n.nextUrl};case"SET_LANGUAGE":return{...r,language:n.language};case"SET_DIRECTION":return{...r,direction:n.direction}}return r},actions:ie,selectors:se,resolvers:ae});return Q(t),t},h=(e,t,r)=>{let n;function o(){let u=U(e).getState(),y=t(u);if(y!==n){let i=n;n=y,r(n,i)}}let a=ee(o,e);return o(),a};var T=()=>G.getConfig(),P=(e,t)=>{let r=ge()?ce(window.localStorage):void 0;r&&ue.setKeyValueStorage(r),G.configure(e,t)},f=e=>O(e),L=()=>pe(),N=()=>le(),I=async(e=!0)=>{let t=e?await p():{};if(t?.username)return t;try{if((await O()).tokens)return{username:(await de()).username,userAttributes:await L(),mfaPreferences:await N()}}catch(r){console.error(r);try{await F()}catch{}}return{}},k=async()=>{await fe({totp:"DISABLED"})},_=()=>p().then(e=>e?.username),D=()=>p().then(e=>e?.userAttributes),M=()=>p().then(e=>e?.mfaPreferences),z=()=>p().then(e=>!!e?.username),W=e=>b().then(t=>t?.includes(e)||!1),b=()=>f().then(e=>e.tokens?.idToken?.payload["cognito:groups"]instanceof Array?e.tokens.idToken.payload["cognito:groups"].map(t=>t):[]).catch(e=>{console.error(e)}),B=async()=>f().then(e=>e.tokens?.idToken?.payload["cognito:roles"]instanceof Array?e.tokens.idToken.payload["cognito:roles"].map(t=>t).map(t=>t.substring(t.indexOf("/")+1)):[]).catch(e=>{console.error(e)}),V=async()=>f().then(e=>{if(!e.tokens?.idToken?.payload["cognito:preferred_role"])return;let t=e.tokens.idToken.payload["cognito:preferred_role"];return t.substring(t.indexOf("/")+1)}).catch(e=>{console.error(e)}),K=()=>f().then(e=>e.tokens?.accessToken.payload.scope?.split(" ")??[]).catch(e=>{console.error(e)}),ye=async e=>{let t,r=s();if(!r)throw new Error("Gatey plugin is not available");return r.settings.integrateWpLogin&&r.restUrl?.startsWith("http")&&(t=await r.cognito.post({apiName:"admin",path:"/login"}).response.then(o=>o.body.json()).then(o=>{if(o instanceof Object&&"redirect"in o)return o?.redirect}).catch(o=>{console.error(o)})),e&&await r.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(n=>console.error(n)),g(r.settings.redirectSignIn)??t},w=async e=>{let t=s();if(!t)throw new Error("Gatey plugin is not available");let r;t.settings.integrateWpLogin&&(r=await t.cognito.get({apiName:"admin",path:"/logout"}).response.then(n=>n.body.json()).then(n=>{if(n instanceof Object&&"redirect"in n)return n?.redirect}).catch(n=>{console.error(n)})),e&&await t.cognito.get({apiName:e.apiName,path:e.path,options:e.options}).response.catch(n=>console.error(n));try{await F()}catch{}return g(t.settings.redirectSignOut)??r??g(t.settings.signInPage)??"/"};import{attachDefaultPluginRuntime as we}from"@smart-cloud/wpsuite-core";var Te=()=>{l().then(e=>{h(e,t=>t.nextUrl,async t=>{t&&window.location.assign(t)}),d(e).clearAccount()}).catch(e=>{console.error("Gatey signOut error:",e)})},be=e=>{l().then(t=>{d(t).setLanguage(e??"en")}).catch(t=>{console.error("Gatey setLanguage error:",t)})},Ee=e=>{l().then(t=>{d(t).setDirection(e??"auto")}).catch(t=>{console.error("Gatey setDirection error:",t)})};var He=async()=>l(),$e=()=>{let e=globalThis.WpSuite,t=s();if(!t)throw new Error("Gatey plugin is not available");we(t),t.status=t.status??"initializing";let r=v();return t.cognito={store:r,observeStore:h,setLanguage:be,setDirection:Ee,getAmplifyConfig:T,isAuthenticated:z,isInGroup:W,getUsername:_,getUserAttributes:D,getMfaPreferences:M,clearMfaPreferences:k,getGroups:b,getRoles:B,getPreferredRole:V,getScopes:K,signOut:Te,get:Ae,post:Ce,put:Pe,del:me,head:Se,patch:he},r.then(()=>{t.status="available",e?.events?.emit("wpsuite:gatey:ready",{key:t.key,version:t.version})}).catch(n=>{t.status="error",e?.events?.emit("wpsuite:gatey:error",{key:t.key,error:String(n)})}),t};export{J as TEXT_DOMAIN,k as clearMfaPreferences,P as configureAmplify,T as getAmplifyConfig,s as getGateyPlugin,b as getGroups,M as getMfaPreferences,V as getPreferredRole,B as getRoles,K as getScopes,l as getStore,d as getStoreDispatch,U as getStoreSelect,D as getUserAttributes,$e as initializeGatey,z as isAuthenticated,W as isInGroup,f as loadAuthSession,N as loadMFAPreferences,L as loadUserAttributes,ye as login,w as logout,h as observeStore,X as resolveGateyRedirectTarget,g as resolveGateyTarget,x as sanitizeAuthenticatorConfig,He as store,E as waitForGateyReady};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@smart-cloud/gatey-core",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.4.0",
|
|
4
4
|
"description": "Login & SSO with Amazon Cognito",
|
|
5
5
|
"author": "Smart Cloud Solutions Inc.",
|
|
6
6
|
"license": "MIT",
|
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
"rollup": "^4.62.3"
|
|
41
41
|
},
|
|
42
42
|
"dependencies": {
|
|
43
|
-
"@smart-cloud/wpsuite-core": "^2.
|
|
43
|
+
"@smart-cloud/wpsuite-core": "^2.5.0"
|
|
44
44
|
},
|
|
45
45
|
"peerDependencies": {
|
|
46
46
|
"@aws-amplify/core": "^6.18.0",
|