1import{W as O}from"./index-BzhIBMaP.js";class c extends O{constructor(){super()}parseJwt(e){const t=e.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),i=decodeURIComponent(atob(t).split("").map(n=>"%"+("00"+n.charCodeAt(0).toString(16)).slice(-2)).join(""));return JSON.parse(i)}async loadScript(e){return new Promise((o,t)=>{const i=document.createElement("script");i.src=e,i.async=!0,i.onload=()=>{o()},i.onerror=t,document.body.appendChild(i)})}}c.OAUTH_STATE_KEY="social_login_oauth_pending";class S extends c{constructor(){super(...arguments),this.clientId=null,this.redirectUrl=null,this.scriptLoaded=!1,this.scriptUrl="https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js"}async initialize(e,o){this.clientId=e,this.redirectUrl=o||null,e&&await this.loadAppleScript()}async login(e){if(!this.clientId)throw new Error("Apple Client ID not set. Call initialize() first.");if(!this.scriptLoaded)throw new Error("Apple Sign-In script not loaded.");return new Promise((o,t)=>{var i;AppleID.auth.init({clientId:this.clientId,scope:((i=e.scopes)===null||i===void 0?void 0:i.join(" "))||"name email",redirectURI:this.redirectUrl||window.location.href,state:e.state,nonce:e.nonce,usePopup:!0}),AppleID.auth.signIn().then(n=>{var s,a,r,d,u;const g={profile:{user:n.user||"",email:((s=n.user)===null||s===void 0?void 0:s.email)||null,givenName:((r=(a=n.user)===null||a===void 0?void 0:a.name)===null||r===void 0?void 0:r.firstName)||null,familyName:((u=(d=n.user)===null||d===void 0?void 0:d.name)===null||u===void 0?void 0:u.lastName)||null},accessToken:{token:n.authorization.id_token||""},idToken:n.authorization.code||null};o({provider:"apple",result:g})}).catch(n=>{t(n)})})}async logout(){console.log("Apple logout: Session should be managed on the client side")}async isLoggedIn(){return console.log("Apple login status should be managed on the client side"),{isLoggedIn:!1}}async getAuthorizationCode(){throw console.log("Apple authorization code should be stored during login"),new Error("Apple authorization code not available")}async refresh(){console.log("Apple refresh not available on web")}async loadAppleScript(){if(!this.scriptLoaded)return this.loadScript(this.scriptUrl).then(()=>{this.scriptLoaded=!0})}}class I extends c{constructor(){super(...arguments),this.appId=null,this.scriptLoaded=!1}async initialize(e){this.appId=e,e&&(await this.loadFacebookScript(),FB.init({appId:this.appId,version:"v17.0",xfbml:!0,cookie:!0}))}async login(e){if(!this.appId)throw new Error("Facebook App ID not set. Call initialize() first.");return new Promise((o,t)=>{FB.login(i=>{i.status==="connected"?FB.api("/me",{fields:"id,name,email,picture"},n=>{var s,a;const r={accessToken:{token:i.authResponse.accessToken,userId:i.authResponse.userID},profile:{userID:n.id,name:n.name,email:n.email||null,imageURL:((a=(s=n.picture)===null||s===void 0?void 0:s.data)===null||a===void 0?void 0:a.url)||null,friendIDs:[],birthday:null,ageRange:null,gender:null,location:null,hometown:null,profileURL:null},idToken:null};o({provider:"facebook",result:r})}):t(new Error("Facebook login failed"))},{scope:e.permissions.join(",")})})}async logout(){return new Promise(e=>{FB.logout(()=>e())})}async isLoggedIn(){return new Promise(e=>{FB.getLoginStatus(o=>{e({isLoggedIn:o.status==="connected"})})})}async getAuthorizationCode(){return new Promise((e,o)=>{FB.getLoginStatus(t=>{var i;t.status==="connected"?e({jwt:((i=t.authResponse)===null||i===void 0?void 0:i.accessToken)||""}):o(new Error("No Facebook authorization code available"))})})}async refresh(e){await this.login(e)}async loadFacebookScript(){if(!this.scriptLoaded)return this.loadScript("https://connect.facebook.net/en_US/sdk.js").then(()=>{this.scriptLoaded=!0})}}class L extends c{constructor(){super(...arguments),this.clientId=null,this.loginType="online",this.GOOGLE_TOKEN_REQUEST_URL="https://www.googleapis.com/oauth2/v3/tokeninfo",this.GOOGLE_STATE_KEY="capgo_social_login_google_state"}async initialize(e,o,t){this.clientId=e,o&&(this.loginType=o),this.hostedDomain=t}async login(e){if(!this.clientId)throw new Error("Google Client ID not set. Call initialize() first.");let o=e.scopes||[];o.length>0?(o.includes("https://www.googleapis.com/auth/userinfo.email")||o.push("https://www.googleapis.com/auth/userinfo.email"),o.includes("https://www.googleapis.com/auth/userinfo.profile")||o.push("https://www.googleapis.com/auth/userinfo.profile"),o.includes("openid")||o.push("openid")):o=["https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile","openid"];const t=e.nonce||Math.random().toString(36).substring(2);return this.traditionalOAuth({scopes:o,nonce:t,hostedDomain:this.hostedDomain})}async logout(){if(this.loginType==="offline")return Promise.reject("Offline login doesn't store tokens. logout is not available");const e=this.getGoogleState();e&&await this.rawLogoutGoogle(e.accessToken)}async isLoggedIn(){if(this.loginType==="offline")return Promise.reject("Offline login doesn't store tokens. isLoggedIn is not available");const e=this.getGoogleState();if(!e)return{isLoggedIn:!1};try{const o=await this.accessTokenIsValid(e.accessToken),t=this.idTokenValid(e.idToken);if(o&&t)return{isLoggedIn:!0};try{await this.rawLogoutGoogle(e.accessToken,!1)}
1catch(i){console.error("Access token is not valid, but cannot logout",i)}return{isLoggedIn:!1}}catch(o){return Promise.reject(o)}}async getAuthorizationCode(){if(this.loginType==="offline")return Promise.reject("Offline login doesn't store tokens. getAuthorizationCode is not available");const e=this.getGoogleState();if(!e)throw new Error("No Google authorization code available");try{const o=await this.accessTokenIsValid(e.accessToken),t=this.idTokenValid(e.idToken);if(o&&t)return{accessToken:e.accessToken,jwt:e.idToken};try{await this.rawLogoutGoogle(e.accessToken,!1)}catch(i){console.error("Access token is not valid, but cannot logout",i)}throw new Error("No Google authorization code available")}catch(o){return Promise.reject(o)}}async refresh(){return Promise.reject("Not implemented")}handleOAuthRedirect(e){const o=e.searchParams,t=o.get("code");if(t&&o.has("scope"))return{provider:"google",result:{serverAuthCode:t,responseType:"offline"}};const i=e.hash.substring(1);if(console.log("handleOAuthRedirect",e.hash),!i)return null;console.log("handleOAuthRedirect ok");const n=new URLSearchParams(i),s=n.get("access_token"),a=n.get("id_token");if(s&&a){localStorage.removeItem(c.OAUTH_STATE_KEY);const r=this.parseJwt(a);return{provider:"google",result:{accessToken:{token:s},idToken:a,profile:{email:r.email||null,familyName:r.family_name||null,givenName:r.given_name||null,id:r.sub||null,name:r.name||null,imageUrl:r.picture||null},responseType:"online"}}}return null}async accessTokenIsValid(e){const o="".concat(this.GOOGLE_TOKEN_REQUEST_URL,"?access_token=").concat(encodeURIComponent(e));try{const t=await fetch(o);if(!t.ok)return console.log("Invalid response from ".concat(this.GOOGLE_TOKEN_REQUEST_URL,". Response not successful. Status code: ").concat(t.status,". Assuming that the token is not valid")),!1;const i=await t.text();if(!i)throw console.error("Invalid response from ".concat(this.GOOGLE_TOKEN_REQUEST_URL,". Response body is null")),new Error("Invalid response from ".concat(this.GOOGLE_TOKEN_REQUEST_URL,". Response body is null"));let n;try{n=JSON.parse(i)}catch(r){throw console.error("Invalid response from ".concat(this.GOOGLE_TOKEN_REQUEST_URL,". Response body is not valid JSON. Error: ").concat(r)),new Error("Invalid response from ".concat(this.GOOGLE_TOKEN_REQUEST_URL,". Response body is not valid JSON. Error: ").concat(r))}const s=n.expires_in;if(s==null)throw console.error("Invalid response from ".concat(this.GOOGLE_TOKEN_REQUEST_URL,". Response JSON does not include 'expires_in'.")),new Error("Invalid response from ".concat(this.GOOGLE_TOKEN_REQUEST_URL,". Response JSON does not include 'expires_in'."));let a;try{if(a=parseInt(s,10),isNaN(a))throw new Error("'expires_in' is not a valid integer")}catch(r){throw console.error("Invalid response from ".concat(this.GOOGLE_TOKEN_REQUEST_URL,". 'expires_in': ").concat(s," is not a valid integer. Error: ").concat(r)),new Error("Invalid response from ".concat(this.GOOGLE_TOKEN_REQUEST_URL,". 'expires_in': ").concat(s," is not a valid integer. Error: ").concat(r))}return a>5}catch(t){throw console.error(t),t}}idTokenValid(e){try{const o=this.parseJwt(e),t=Math.ceil(Date.now()/1e3)+5;return o.exp&&t<o.exp}catch(o){return!1}}async rawLogoutGoogle(e,o=null){if(o===null&&(o=await this.accessTokenIsValid(e)),o===!0)return new Promise((t,i)=>{try{google.accounts.oauth2.revoke(e,async()=>{this.clearStateGoogle(),t()})}catch(n){i(n)}});this.clearStateGoogle()}persistStateGoogle(e,o){try{window.localStorage.setItem(this.GOOGLE_STATE_KEY,JSON.stringify({accessToken:e,idToken:o}))}catch(t){console.error("Cannot persist state google",t)}}clearStateGoogle(){try{window.localStorage.removeItem(this.GOOGLE_STATE_KEY)}catch(e){console.error("Cannot clear state google",e)}}getGoogleState(){try{const e=window.localStorage.getItem(this.GOOGLE_STATE_KEY);if(!e)return null;const{accessToken:o,idToken:t}=JSON.parse(e);return{accessToken:o,idToken:t}}catch(e){return console.error("Cannot get state google",e),null}}async traditionalOAuth({scopes:e,hostedDomain:o,nonce:t}){const i=[...new Set([...e||[],"openid"])],n=new URLSearchParams(Object.assign(Object.assign({client_id:this.clientId,redirect_uri:window.location.href,response_type:this.loginType==="offline"?"code":"token id_token",scope:i.join(" ")},t&&{nonce:t}),{include_granted_scopes:"true",state:"popup"}));o!==void 0&&n.append("hd",o);const s="https://accounts.google.com/o/oauth2/v2/auth?".concat(n.toString()),a=500,r=600,d=window.screenX+(window.outerWidth-a)/2,u=window.screenY+(window.outerHeight-r)/2;localStorage.setItem(c.OAUTH_STATE_KEY,"true");
1const g=window.open(s,"Google Sign In","width=".concat(a,",height=").concat(r,",left=").concat(d,",top=").concat(u,",popup=1"));return new Promise((y,m)=>{if(!g){m(new Error("Failed to open popup"));return}const v=p=>{var _,E,T;if(!(p.origin!==window.location.origin||!((E=(_=p.data)===null||_===void 0?void 0:_.source)===null||E===void 0)&&E.startsWith("angular")))if(((T=p.data)===null||T===void 0?void 0:T.type)==="oauth-response")if(window.removeEventListener("message",v),this.loginType==="online"){const{accessToken:h,idToken:f}=p.data;if(h&&f){const l=this.parseJwt(f);this.persistStateGoogle(h.token,f),y({provider:"google",result:{accessToken:{token:h.token},idToken:f,profile:{email:l.email||null,familyName:l.family_name||null,givenName:l.given_name||null,id:l.sub||null,name:l.name||null,imageUrl:l.picture||null},responseType:"online"}})}}else{const{serverAuthCode:h}=p.data;y({provider:"google",result:{responseType:"offline",serverAuthCode:h}})}else m(new Error("Login failed"))};window.addEventListener("message",v),setTimeout(()=>{window.removeEventListener("message",v),g.close(),m(new Error("OAuth timeout"))},3e5)})}}class k extends O{constructor(){var e;if(super(),this.googleProvider=new L,this.appleProvider=new S,this.facebookProvider=new I,localStorage.getItem(k.OAUTH_STATE_KEY)){console.log("OAUTH_STATE_KEY found");const o=this.handleOAuthRedirect();o&&((e=window.opener)===null||e===void 0||e.postMessage(Object.assign({type:"oauth-response"},o.result),window.location.origin),window.close())}}handleOAuthRedirect(){const e=new URL(window.location.href);return this.googleProvider.handleOAuthRedirect(e)}async initialize(e){var o,t,i;const n=[];!((o=e.google)===null||o===void 0)&&o.webClientId&&n.push(this.googleProvider.initialize(e.google.webClientId,e.google.mode,e.google.hostedDomain)),!((t=e.apple)===null||t===void 0)&&t.clientId&&n.push(this.appleProvider.initialize(e.apple.clientId,e.apple.redirectUrl)),!((i=e.facebook)===null||i===void 0)&&i.appId&&n.push(this.facebookProvider.initialize(e.facebook.appId)),await Promise.all(n)}async login(e){switch(e.provider){case"google":return this.googleProvider.login(e.options);case"apple":return this.appleProvider.login(e.options);case"facebook":return this.facebookProvider.login(e.options);default:throw new Error("Login for ".concat(e.provider," is not implemented on web"))}}async logout(e){switch(e.provider){case"google":return this.googleProvider.logout();case"apple":return this.appleProvider.logout();case"facebook":return this.facebookProvider.logout();default:throw new Error("Logout for ".concat(e.provider," is not implemented"))}}async isLoggedIn(e){switch(e.provider){case"google":return this.googleProvider.isLoggedIn();case"apple":return this.appleProvider.isLoggedIn();case"facebook":return this.facebookProvider.isLoggedIn();default:throw new Error("isLoggedIn for ".concat(e.provider," is not implemented"))}}async getAuthorizationCode(e){switch(e.provider){case"google":return this.googleProvider.getAuthorizationCode();case"apple":return this.appleProvider.getAuthorizationCode();case"facebook":return this.facebookProvider.getAuthorizationCode();default:throw new Error("getAuthorizationCode for ".concat(e.provider," is not implemented"))}}async refresh(e){switch(e.provider){case"google":return this.googleProvider.refresh();case"apple":return this.appleProvider.refresh();case"facebook":return this.facebookProvider.refresh(e.options);default:throw new Error("Refresh for ".concat(e.provider," is not implemented"))}}}k.OAUTH_STATE_KEY="social_login_oauth_pending";export{k as SocialLoginWeb};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.