@capgo/capacitor-social-login 7.2.3 → 7.4.6

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.
@@ -6,54 +6,350 @@ const SocialLogin = core.registerPlugin('SocialLogin', {
6
6
  web: () => Promise.resolve().then(function () { return web; }).then((m) => new m.SocialLoginWeb()),
7
7
  });
8
8
 
9
- class SocialLoginWeb extends core.WebPlugin {
9
+ class BaseSocialLogin extends core.WebPlugin {
10
10
  constructor() {
11
- var _a;
12
11
  super();
13
- this.googleClientId = null;
14
- this.appleClientId = null;
15
- this.appleRedirectUrl = null;
16
- this.googleScriptLoaded = false;
17
- this.googleLoginType = 'online';
18
- this.appleScriptLoaded = false;
19
- this.appleScriptUrl = 'https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js';
12
+ }
13
+ parseJwt(token) {
14
+ const base64Url = token.split('.')[1];
15
+ const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
16
+ const jsonPayload = decodeURIComponent(atob(base64)
17
+ .split('')
18
+ .map((c) => {
19
+ return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
20
+ })
21
+ .join(''));
22
+ return JSON.parse(jsonPayload);
23
+ }
24
+ async loadScript(src) {
25
+ return new Promise((resolve, reject) => {
26
+ const script = document.createElement('script');
27
+ script.src = src;
28
+ script.async = true;
29
+ script.onload = () => {
30
+ resolve();
31
+ };
32
+ script.onerror = reject;
33
+ document.body.appendChild(script);
34
+ });
35
+ }
36
+ }
37
+ BaseSocialLogin.OAUTH_STATE_KEY = 'social_login_oauth_pending';
38
+
39
+ class AppleSocialLogin extends BaseSocialLogin {
40
+ constructor() {
41
+ super(...arguments);
42
+ this.clientId = null;
43
+ this.redirectUrl = null;
44
+ this.scriptLoaded = false;
45
+ this.scriptUrl = 'https://appleid.cdn-apple.com/appleauth/static/jsapi/appleid/1/en_US/appleid.auth.js';
46
+ }
47
+ async initialize(clientId, redirectUrl) {
48
+ this.clientId = clientId;
49
+ this.redirectUrl = redirectUrl || null;
50
+ if (clientId) {
51
+ await this.loadAppleScript();
52
+ }
53
+ }
54
+ async login(options) {
55
+ if (!this.clientId) {
56
+ throw new Error('Apple Client ID not set. Call initialize() first.');
57
+ }
58
+ if (!this.scriptLoaded) {
59
+ throw new Error('Apple Sign-In script not loaded.');
60
+ }
61
+ return new Promise((resolve, reject) => {
62
+ var _a;
63
+ AppleID.auth.init({
64
+ clientId: this.clientId,
65
+ scope: ((_a = options.scopes) === null || _a === void 0 ? void 0 : _a.join(' ')) || 'name email',
66
+ redirectURI: this.redirectUrl || window.location.href,
67
+ state: options.state,
68
+ nonce: options.nonce,
69
+ usePopup: true,
70
+ });
71
+ AppleID.auth
72
+ .signIn()
73
+ .then((res) => {
74
+ var _a, _b, _c, _d, _e;
75
+ const result = {
76
+ profile: {
77
+ user: res.user || '',
78
+ email: ((_a = res.user) === null || _a === void 0 ? void 0 : _a.email) || null,
79
+ givenName: ((_c = (_b = res.user) === null || _b === void 0 ? void 0 : _b.name) === null || _c === void 0 ? void 0 : _c.firstName) || null,
80
+ familyName: ((_e = (_d = res.user) === null || _d === void 0 ? void 0 : _d.name) === null || _e === void 0 ? void 0 : _e.lastName) || null,
81
+ },
82
+ accessToken: {
83
+ token: res.authorization.id_token || '',
84
+ },
85
+ idToken: res.authorization.code || null,
86
+ };
87
+ resolve({ provider: 'apple', result });
88
+ })
89
+ .catch((error) => {
90
+ reject(error);
91
+ });
92
+ });
93
+ }
94
+ async logout() {
95
+ // Apple doesn't provide a logout method for web
96
+ console.log('Apple logout: Session should be managed on the client side');
97
+ }
98
+ async isLoggedIn() {
99
+ // Apple doesn't provide a method to check login status on web
100
+ console.log('Apple login status should be managed on the client side');
101
+ return { isLoggedIn: false };
102
+ }
103
+ async getAuthorizationCode() {
104
+ // Apple authorization code should be obtained during login
105
+ console.log('Apple authorization code should be stored during login');
106
+ throw new Error('Apple authorization code not available');
107
+ }
108
+ async refresh() {
109
+ // Apple doesn't provide a refresh method for web
110
+ console.log('Apple refresh not available on web');
111
+ }
112
+ async loadAppleScript() {
113
+ if (this.scriptLoaded)
114
+ return;
115
+ return this.loadScript(this.scriptUrl).then(() => {
116
+ this.scriptLoaded = true;
117
+ });
118
+ }
119
+ }
120
+
121
+ class FacebookSocialLogin extends BaseSocialLogin {
122
+ constructor() {
123
+ super(...arguments);
124
+ this.appId = null;
125
+ this.scriptLoaded = false;
126
+ }
127
+ async initialize(appId) {
128
+ this.appId = appId;
129
+ if (appId) {
130
+ await this.loadFacebookScript();
131
+ FB.init({
132
+ appId: this.appId,
133
+ version: 'v17.0',
134
+ xfbml: true,
135
+ cookie: true,
136
+ });
137
+ }
138
+ }
139
+ async login(options) {
140
+ if (!this.appId) {
141
+ throw new Error('Facebook App ID not set. Call initialize() first.');
142
+ }
143
+ return new Promise((resolve, reject) => {
144
+ FB.login((response) => {
145
+ if (response.status === 'connected') {
146
+ FB.api('/me', { fields: 'id,name,email,picture' }, (userInfo) => {
147
+ var _a, _b;
148
+ const result = {
149
+ accessToken: {
150
+ token: response.authResponse.accessToken,
151
+ userId: response.authResponse.userID,
152
+ },
153
+ profile: {
154
+ userID: userInfo.id,
155
+ name: userInfo.name,
156
+ email: userInfo.email || null,
157
+ imageURL: ((_b = (_a = userInfo.picture) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.url) || null,
158
+ friendIDs: [],
159
+ birthday: null,
160
+ ageRange: null,
161
+ gender: null,
162
+ location: null,
163
+ hometown: null,
164
+ profileURL: null,
165
+ },
166
+ idToken: null,
167
+ };
168
+ resolve({ provider: 'facebook', result });
169
+ });
170
+ }
171
+ else {
172
+ reject(new Error('Facebook login failed'));
173
+ }
174
+ }, { scope: options.permissions.join(',') });
175
+ });
176
+ }
177
+ async logout() {
178
+ return new Promise((resolve) => {
179
+ FB.logout(() => resolve());
180
+ });
181
+ }
182
+ async isLoggedIn() {
183
+ return new Promise((resolve) => {
184
+ FB.getLoginStatus((response) => {
185
+ resolve({ isLoggedIn: response.status === 'connected' });
186
+ });
187
+ });
188
+ }
189
+ async getAuthorizationCode() {
190
+ return new Promise((resolve, reject) => {
191
+ FB.getLoginStatus((response) => {
192
+ var _a;
193
+ if (response.status === 'connected') {
194
+ resolve({ jwt: ((_a = response.authResponse) === null || _a === void 0 ? void 0 : _a.accessToken) || '' });
195
+ }
196
+ else {
197
+ reject(new Error('No Facebook authorization code available'));
198
+ }
199
+ });
200
+ });
201
+ }
202
+ async refresh(options) {
203
+ await this.login(options);
204
+ }
205
+ async loadFacebookScript() {
206
+ if (this.scriptLoaded)
207
+ return;
208
+ return this.loadScript('https://connect.facebook.net/en_US/sdk.js').then(() => {
209
+ this.scriptLoaded = true;
210
+ });
211
+ }
212
+ }
213
+
214
+ class GoogleSocialLogin extends BaseSocialLogin {
215
+ constructor() {
216
+ super(...arguments);
217
+ this.clientId = null;
218
+ this.loginType = 'online';
20
219
  this.GOOGLE_TOKEN_REQUEST_URL = 'https://www.googleapis.com/oauth2/v3/tokeninfo';
21
- this.facebookAppId = null;
22
- this.facebookScriptLoaded = false;
23
- // Set up listener for OAuth redirects if we have a pending OAuth flow
24
- if (localStorage.getItem(SocialLoginWeb.OAUTH_STATE_KEY)) {
25
- console.log('OAUTH_STATE_KEY found');
26
- const result = this.handleOAuthRedirect();
27
- if (result) {
28
- (_a = window.opener) === null || _a === void 0 ? void 0 : _a.postMessage(Object.assign({ type: 'oauth-response' }, result.result), window.location.origin);
29
- window.close();
220
+ this.GOOGLE_STATE_KEY = 'capgo_social_login_google_state';
221
+ }
222
+ async initialize(clientId, mode, hostedDomain) {
223
+ this.clientId = clientId;
224
+ if (mode) {
225
+ this.loginType = mode;
226
+ }
227
+ this.hostedDomain = hostedDomain;
228
+ }
229
+ async login(options) {
230
+ if (!this.clientId) {
231
+ throw new Error('Google Client ID not set. Call initialize() first.');
232
+ }
233
+ let scopes = options.scopes || [];
234
+ if (scopes.length > 0) {
235
+ // If scopes are provided, directly use the traditional OAuth flow
236
+ if (!scopes.includes('https://www.googleapis.com/auth/userinfo.email')) {
237
+ scopes.push('https://www.googleapis.com/auth/userinfo.email');
238
+ }
239
+ if (!scopes.includes('https://www.googleapis.com/auth/userinfo.profile')) {
240
+ scopes.push('https://www.googleapis.com/auth/userinfo.profile');
30
241
  }
242
+ if (!scopes.includes('openid')) {
243
+ scopes.push('openid');
244
+ }
245
+ }
246
+ else {
247
+ scopes = [
248
+ 'https://www.googleapis.com/auth/userinfo.email',
249
+ 'https://www.googleapis.com/auth/userinfo.profile',
250
+ 'openid',
251
+ ];
31
252
  }
253
+ const nonce = options.nonce || Math.random().toString(36).substring(2);
254
+ // If scopes are provided, directly use the traditional OAuth flow
255
+ return this.traditionalOAuth({
256
+ scopes,
257
+ nonce,
258
+ hostedDomain: this.hostedDomain,
259
+ });
32
260
  }
33
- handleOAuthRedirect() {
34
- const paramsRaw = new URL(window.location.href).searchParams;
261
+ async logout() {
262
+ if (this.loginType === 'offline') {
263
+ return Promise.reject("Offline login doesn't store tokens. logout is not available");
264
+ }
265
+ // eslint-disable-next-line
266
+ const state = this.getGoogleState();
267
+ if (!state)
268
+ return;
269
+ await this.rawLogoutGoogle(state.accessToken);
270
+ }
271
+ async isLoggedIn() {
272
+ if (this.loginType === 'offline') {
273
+ return Promise.reject("Offline login doesn't store tokens. isLoggedIn is not available");
274
+ }
275
+ // eslint-disable-next-line
276
+ const state = this.getGoogleState();
277
+ if (!state)
278
+ return { isLoggedIn: false };
279
+ try {
280
+ const isValidAccessToken = await this.accessTokenIsValid(state.accessToken);
281
+ const isValidIdToken = this.idTokenValid(state.idToken);
282
+ if (isValidAccessToken && isValidIdToken) {
283
+ return { isLoggedIn: true };
284
+ }
285
+ else {
286
+ try {
287
+ await this.rawLogoutGoogle(state.accessToken, false);
288
+ }
289
+ catch (e) {
290
+ console.error('Access token is not valid, but cannot logout', e);
291
+ }
292
+ return { isLoggedIn: false };
293
+ }
294
+ }
295
+ catch (e) {
296
+ return Promise.reject(e);
297
+ }
298
+ }
299
+ async getAuthorizationCode() {
300
+ if (this.loginType === 'offline') {
301
+ return Promise.reject("Offline login doesn't store tokens. getAuthorizationCode is not available");
302
+ }
303
+ // eslint-disable-next-line
304
+ const state = this.getGoogleState();
305
+ if (!state)
306
+ throw new Error('No Google authorization code available');
307
+ try {
308
+ const isValidAccessToken = await this.accessTokenIsValid(state.accessToken);
309
+ const isValidIdToken = this.idTokenValid(state.idToken);
310
+ if (isValidAccessToken && isValidIdToken) {
311
+ return { accessToken: state.accessToken, jwt: state.idToken };
312
+ }
313
+ else {
314
+ try {
315
+ await this.rawLogoutGoogle(state.accessToken, false);
316
+ }
317
+ catch (e) {
318
+ console.error('Access token is not valid, but cannot logout', e);
319
+ }
320
+ throw new Error('No Google authorization code available');
321
+ }
322
+ }
323
+ catch (e) {
324
+ return Promise.reject(e);
325
+ }
326
+ }
327
+ async refresh() {
328
+ // For Google, we can prompt for re-authentication
329
+ return Promise.reject('Not implemented');
330
+ }
331
+ handleOAuthRedirect(url) {
332
+ const paramsRaw = url.searchParams;
35
333
  const code = paramsRaw.get('code');
36
334
  if (code && paramsRaw.has('scope')) {
37
335
  return {
38
336
  provider: 'google',
39
337
  result: {
40
- provider: 'google',
41
- result: {
42
- serverAuthCode: code,
43
- },
338
+ serverAuthCode: code,
339
+ responseType: 'offline',
44
340
  },
45
341
  };
46
342
  }
47
- const hash = window.location.hash.substring(1);
48
- console.log('handleOAuthRedirect', window.location.hash);
343
+ const hash = url.hash.substring(1);
344
+ console.log('handleOAuthRedirect', url.hash);
49
345
  if (!hash)
50
- return;
346
+ return null;
51
347
  console.log('handleOAuthRedirect ok');
52
348
  const params = new URLSearchParams(hash);
53
349
  const accessToken = params.get('access_token');
54
350
  const idToken = params.get('id_token');
55
351
  if (accessToken && idToken) {
56
- localStorage.removeItem(SocialLoginWeb.OAUTH_STATE_KEY);
352
+ localStorage.removeItem(BaseSocialLogin.OAUTH_STATE_KEY);
57
353
  const profile = this.parseJwt(idToken);
58
354
  return {
59
355
  provider: 'google',
@@ -70,77 +366,12 @@ class SocialLoginWeb extends core.WebPlugin {
70
366
  name: profile.name || null,
71
367
  imageUrl: profile.picture || null,
72
368
  },
369
+ responseType: 'online',
73
370
  },
74
371
  };
75
372
  }
76
373
  return null;
77
374
  }
78
- async initialize(options) {
79
- var _a, _b, _c;
80
- if ((_a = options.google) === null || _a === void 0 ? void 0 : _a.webClientId) {
81
- this.googleClientId = options.google.webClientId;
82
- if (options.google.mode) {
83
- this.googleLoginType = options.google.mode;
84
- }
85
- this.googleHostedDomain = options.google.hostedDomain;
86
- await this.loadGoogleScript();
87
- }
88
- if ((_b = options.apple) === null || _b === void 0 ? void 0 : _b.clientId) {
89
- this.appleClientId = options.apple.clientId;
90
- this.appleRedirectUrl = options.apple.redirectUrl || null;
91
- await this.loadAppleScript();
92
- }
93
- if ((_c = options.facebook) === null || _c === void 0 ? void 0 : _c.appId) {
94
- this.facebookAppId = options.facebook.appId;
95
- await this.loadFacebookScript();
96
- FB.init({
97
- appId: this.facebookAppId,
98
- version: 'v17.0',
99
- xfbml: true,
100
- cookie: true,
101
- });
102
- }
103
- // Implement initialization for other providers if needed
104
- }
105
- async login(options) {
106
- switch (options.provider) {
107
- case 'google':
108
- return this.loginWithGoogle(options.options);
109
- case 'apple':
110
- return this.loginWithApple(options.options);
111
- case 'facebook':
112
- return this.loginWithFacebook(options.options);
113
- default:
114
- throw new Error(`Login for ${options.provider} is not implemented on web`);
115
- }
116
- }
117
- async logout(options) {
118
- switch (options.provider) {
119
- case 'google':
120
- if (this.googleLoginType === 'offline') {
121
- return Promise.reject("Offline login doesn't store tokens. logout is not available");
122
- }
123
- // Google doesn't have a specific logout method for web
124
- // We can revoke the token if we have it stored
125
- console.log('Google logout: Id token should be revoked on the client side if stored');
126
- // eslint-disable-next-line
127
- const state = this.getGoogleState();
128
- if (!state)
129
- return;
130
- await this.rawLogoutGoogle(state.accessToken);
131
- break;
132
- case 'apple':
133
- // Apple doesn't provide a logout method for web
134
- console.log('Apple logout: Session should be managed on the client side');
135
- break;
136
- case 'facebook':
137
- return new Promise((resolve) => {
138
- FB.logout(() => resolve());
139
- });
140
- default:
141
- throw new Error(`Logout for ${options.provider} is not implemented`);
142
- }
143
- }
144
375
  async accessTokenIsValid(accessToken) {
145
376
  const url = `${this.GOOGLE_TOKEN_REQUEST_URL}?access_token=${encodeURIComponent(accessToken)}`;
146
377
  try {
@@ -224,274 +455,9 @@ class SocialLoginWeb extends core.WebPlugin {
224
455
  return;
225
456
  }
226
457
  }
227
- async isLoggedIn(options) {
228
- switch (options.provider) {
229
- case 'google':
230
- if (this.googleLoginType === 'offline') {
231
- return Promise.reject("Offline login doesn't store tokens. isLoggedIn is not available");
232
- }
233
- // For Google, we can check if there's a valid token
234
- // eslint-disable-next-line
235
- const state = this.getGoogleState();
236
- if (!state)
237
- return { isLoggedIn: false };
238
- try {
239
- // todo: cache accessTokenIsValid calls
240
- const isValidAccessToken = await this.accessTokenIsValid(state.accessToken);
241
- const isValidIdToken = this.idTokenValid(state.idToken);
242
- if (isValidAccessToken && isValidIdToken) {
243
- return { isLoggedIn: true };
244
- }
245
- else {
246
- try {
247
- await this.rawLogoutGoogle(state.accessToken, false);
248
- }
249
- catch (e) {
250
- console.error('Access token is not valid, but cannot logout', e);
251
- }
252
- return { isLoggedIn: false };
253
- }
254
- }
255
- catch (e) {
256
- return Promise.reject(e);
257
- }
258
- case 'apple':
259
- // Apple doesn't provide a method to check login status on web
260
- console.log('Apple login status should be managed on the client side');
261
- return { isLoggedIn: false };
262
- case 'facebook':
263
- return new Promise((resolve) => {
264
- FB.getLoginStatus((response) => {
265
- resolve({ isLoggedIn: response.status === 'connected' });
266
- });
267
- });
268
- default:
269
- throw new Error(`isLoggedIn for ${options.provider} is not implemented`);
270
- }
271
- }
272
- async getAuthorizationCode(options) {
273
- switch (options.provider) {
274
- case 'google':
275
- if (this.googleLoginType === 'offline') {
276
- return Promise.reject("Offline login doesn't store tokens. getAuthorizationCode is not available");
277
- }
278
- // For Google, we can use the id_token as the authorization code
279
- // eslint-disable-next-line
280
- const state = this.getGoogleState();
281
- if (!state)
282
- throw new Error('No Google authorization code available');
283
- try {
284
- // todo: cache accessTokenIsValid calls
285
- const isValidAccessToken = await this.accessTokenIsValid(state.accessToken);
286
- const isValidIdToken = this.idTokenValid(state.idToken);
287
- if (isValidAccessToken && isValidIdToken) {
288
- return { accessToken: state.accessToken, jwt: state.idToken };
289
- }
290
- else {
291
- try {
292
- await this.rawLogoutGoogle(state.accessToken, false);
293
- }
294
- catch (e) {
295
- console.error('Access token is not valid, but cannot logout', e);
296
- }
297
- throw new Error('No Google authorization code available');
298
- }
299
- }
300
- catch (e) {
301
- return Promise.reject(e);
302
- }
303
- case 'apple':
304
- // Apple authorization code should be obtained during login
305
- console.log('Apple authorization code should be stored during login');
306
- throw new Error('Apple authorization code not available');
307
- case 'facebook':
308
- return new Promise((resolve, reject) => {
309
- FB.getLoginStatus((response) => {
310
- var _a;
311
- if (response.status === 'connected') {
312
- resolve({ jwt: ((_a = response.authResponse) === null || _a === void 0 ? void 0 : _a.accessToken) || '' });
313
- }
314
- else {
315
- reject(new Error('No Facebook authorization code available'));
316
- }
317
- });
318
- });
319
- default:
320
- throw new Error(`getAuthorizationCode for ${options.provider} is not implemented`);
321
- }
322
- }
323
- async refresh(options) {
324
- switch (options.provider) {
325
- case 'google':
326
- // For Google, we can prompt for re-authentication
327
- return Promise.reject('Not implemented');
328
- case 'apple':
329
- // Apple doesn't provide a refresh method for web
330
- console.log('Apple refresh not available on web');
331
- break;
332
- case 'facebook':
333
- await this.loginWithFacebook(options.options);
334
- break;
335
- default:
336
- throw new Error(`Refresh for ${options.provider} is not implemented`);
337
- }
338
- }
339
- loginWithGoogle(options) {
340
- if (!this.googleClientId) {
341
- throw new Error('Google Client ID not set. Call initialize() first.');
342
- }
343
- let scopes = options.scopes || [];
344
- if (scopes.length > 0) {
345
- // If scopes are provided, directly use the traditional OAuth flow
346
- if (!scopes.includes('https://www.googleapis.com/auth/userinfo.email')) {
347
- scopes.push('https://www.googleapis.com/auth/userinfo.email');
348
- }
349
- if (!scopes.includes('https://www.googleapis.com/auth/userinfo.profile')) {
350
- scopes.push('https://www.googleapis.com/auth/userinfo.profile');
351
- }
352
- if (!scopes.includes('openid')) {
353
- scopes.push('openid');
354
- }
355
- }
356
- else {
357
- scopes = [
358
- 'https://www.googleapis.com/auth/userinfo.email',
359
- 'https://www.googleapis.com/auth/userinfo.profile',
360
- 'openid',
361
- ];
362
- }
363
- if (scopes.length > 3 || this.googleLoginType === 'offline' || options.disableOneTap) {
364
- // If scopes are provided, directly use the traditional OAuth flow
365
- return this.fallbackToTraditionalOAuth(scopes, this.googleHostedDomain);
366
- }
367
- return new Promise((resolve, reject) => {
368
- google.accounts.id.initialize({
369
- client_id: this.googleClientId,
370
- hd: this.googleHostedDomain,
371
- callback: (response) => {
372
- console.log('google.accounts.id.initialize callback', response);
373
- if (response.error) {
374
- // we use any because type fail but we need to double check if that works
375
- reject(response.error);
376
- }
377
- else {
378
- const payload = this.parseJwt(response.credential);
379
- const result = {
380
- accessToken: null,
381
- responseType: 'online',
382
- idToken: response.credential,
383
- profile: {
384
- email: payload.email || null,
385
- familyName: payload.family_name || null,
386
- givenName: payload.given_name || null,
387
- id: payload.sub || null,
388
- name: payload.name || null,
389
- imageUrl: payload.picture || null,
390
- },
391
- };
392
- resolve({ provider: 'google', result });
393
- }
394
- },
395
- auto_select: true,
396
- });
397
- google.accounts.id.prompt((notification) => {
398
- if (notification.isNotDisplayed() || notification.isSkippedMoment()) {
399
- console.log('OneTap is not displayed or skipped');
400
- // Fallback to traditional OAuth if One Tap is not available
401
- this.fallbackToTraditionalOAuth(scopes, this.googleHostedDomain)
402
- .then((r) => resolve({ provider: 'google', result: r.result }))
403
- .catch(reject);
404
- }
405
- else {
406
- console.log('OneTap is displayed');
407
- }
408
- });
409
- });
410
- }
411
- parseJwt(token) {
412
- const base64Url = token.split('.')[1];
413
- const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
414
- const jsonPayload = decodeURIComponent(atob(base64)
415
- .split('')
416
- .map((c) => {
417
- return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
418
- })
419
- .join(''));
420
- return JSON.parse(jsonPayload);
421
- }
422
- async loadGoogleScript() {
423
- if (this.googleScriptLoaded)
424
- return;
425
- return new Promise((resolve, reject) => {
426
- const script = document.createElement('script');
427
- script.src = 'https://accounts.google.com/gsi/client';
428
- script.async = true;
429
- script.onload = () => {
430
- this.googleScriptLoaded = true;
431
- resolve();
432
- };
433
- script.onerror = reject;
434
- document.body.appendChild(script);
435
- });
436
- }
437
- async loginWithApple(options) {
438
- if (!this.appleClientId) {
439
- throw new Error('Apple Client ID not set. Call initialize() first.');
440
- }
441
- if (!this.appleScriptLoaded) {
442
- throw new Error('Apple Sign-In script not loaded.');
443
- }
444
- return new Promise((resolve, reject) => {
445
- var _a;
446
- AppleID.auth.init({
447
- clientId: this.appleClientId,
448
- scope: ((_a = options.scopes) === null || _a === void 0 ? void 0 : _a.join(' ')) || 'name email',
449
- redirectURI: this.appleRedirectUrl || window.location.href,
450
- state: options.state,
451
- nonce: options.nonce,
452
- usePopup: true,
453
- });
454
- AppleID.auth
455
- .signIn()
456
- .then((res) => {
457
- var _a, _b, _c, _d, _e;
458
- const result = {
459
- profile: {
460
- user: res.user || '',
461
- email: ((_a = res.user) === null || _a === void 0 ? void 0 : _a.email) || null,
462
- givenName: ((_c = (_b = res.user) === null || _b === void 0 ? void 0 : _b.name) === null || _c === void 0 ? void 0 : _c.firstName) || null,
463
- familyName: ((_e = (_d = res.user) === null || _d === void 0 ? void 0 : _d.name) === null || _e === void 0 ? void 0 : _e.lastName) || null,
464
- },
465
- accessToken: {
466
- token: res.authorization.id_token || '',
467
- },
468
- idToken: res.authorization.code || null,
469
- };
470
- resolve({ provider: 'apple', result });
471
- })
472
- .catch((error) => {
473
- reject(error);
474
- });
475
- });
476
- }
477
- async loadAppleScript() {
478
- if (this.appleScriptLoaded)
479
- return;
480
- return new Promise((resolve, reject) => {
481
- const script = document.createElement('script');
482
- script.src = this.appleScriptUrl;
483
- script.async = true;
484
- script.onload = () => {
485
- this.appleScriptLoaded = true;
486
- resolve();
487
- };
488
- script.onerror = reject;
489
- document.body.appendChild(script);
490
- });
491
- }
492
458
  persistStateGoogle(accessToken, idToken) {
493
459
  try {
494
- window.localStorage.setItem('capgo_social_login_google_state', JSON.stringify({ accessToken, idToken }));
460
+ window.localStorage.setItem(this.GOOGLE_STATE_KEY, JSON.stringify({ accessToken, idToken }));
495
461
  }
496
462
  catch (e) {
497
463
  console.error('Cannot persist state google', e);
@@ -499,7 +465,7 @@ class SocialLoginWeb extends core.WebPlugin {
499
465
  }
500
466
  clearStateGoogle() {
501
467
  try {
502
- window.localStorage.removeItem('capgo_social_login_google_state');
468
+ window.localStorage.removeItem(this.GOOGLE_STATE_KEY);
503
469
  }
504
470
  catch (e) {
505
471
  console.error('Cannot clear state google', e);
@@ -507,7 +473,7 @@ class SocialLoginWeb extends core.WebPlugin {
507
473
  }
508
474
  getGoogleState() {
509
475
  try {
510
- const state = window.localStorage.getItem('capgo_social_login_google_state');
476
+ const state = window.localStorage.getItem(this.GOOGLE_STATE_KEY);
511
477
  if (!state)
512
478
  return null;
513
479
  const { accessToken, idToken } = JSON.parse(state);
@@ -518,71 +484,9 @@ class SocialLoginWeb extends core.WebPlugin {
518
484
  return null;
519
485
  }
520
486
  }
521
- async loadFacebookScript() {
522
- if (this.facebookScriptLoaded)
523
- return;
524
- return new Promise((resolve, reject) => {
525
- const script = document.createElement('script');
526
- script.src = 'https://connect.facebook.net/en_US/sdk.js';
527
- script.async = true;
528
- script.defer = true;
529
- script.onload = () => {
530
- this.facebookScriptLoaded = true;
531
- resolve();
532
- };
533
- script.onerror = reject;
534
- document.body.appendChild(script);
535
- });
536
- }
537
- async loginWithFacebook(options) {
538
- if (!this.facebookAppId) {
539
- throw new Error('Facebook App ID not set. Call initialize() first.');
540
- }
541
- return new Promise((resolve, reject) => {
542
- FB.login((response) => {
543
- if (response.status === 'connected') {
544
- FB.api('/me', { fields: 'id,name,email,picture' }, (userInfo) => {
545
- var _a, _b;
546
- const result = {
547
- accessToken: {
548
- token: response.authResponse.accessToken,
549
- userId: response.authResponse.userID,
550
- },
551
- profile: {
552
- userID: userInfo.id,
553
- name: userInfo.name,
554
- email: userInfo.email || null,
555
- imageURL: ((_b = (_a = userInfo.picture) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.url) || null,
556
- friendIDs: [],
557
- birthday: null,
558
- ageRange: null,
559
- gender: null,
560
- location: null,
561
- hometown: null,
562
- profileURL: null,
563
- },
564
- idToken: null,
565
- };
566
- resolve({ provider: 'facebook', result });
567
- });
568
- }
569
- else {
570
- reject(new Error('Facebook login failed'));
571
- }
572
- }, { scope: options.permissions.join(',') });
573
- });
574
- }
575
- async fallbackToTraditionalOAuth(scopes, hostedDomain) {
576
- const uniqueScopes = [...new Set([...scopes, 'openid'])];
577
- const params = new URLSearchParams({
578
- client_id: this.googleClientId,
579
- redirect_uri: window.location.href,
580
- response_type: this.googleLoginType === 'offline' ? 'code' : 'token id_token',
581
- scope: uniqueScopes.join(' '),
582
- nonce: Math.random().toString(36).substring(2),
583
- include_granted_scopes: 'true',
584
- state: 'popup',
585
- });
487
+ async traditionalOAuth({ scopes, hostedDomain, nonce, }) {
488
+ const uniqueScopes = [...new Set([...(scopes || []), 'openid'])];
489
+ const params = 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: uniqueScopes.join(' ') }, (nonce && { nonce })), { include_granted_scopes: 'true', state: 'popup' }));
586
490
  if (hostedDomain !== undefined) {
587
491
  params.append('hd', hostedDomain);
588
492
  }
@@ -591,7 +495,7 @@ class SocialLoginWeb extends core.WebPlugin {
591
495
  const height = 600;
592
496
  const left = window.screenX + (window.outerWidth - width) / 2;
593
497
  const top = window.screenY + (window.outerHeight - height) / 2;
594
- localStorage.setItem(SocialLoginWeb.OAUTH_STATE_KEY, 'true');
498
+ localStorage.setItem(BaseSocialLogin.OAUTH_STATE_KEY, 'true');
595
499
  const popup = window.open(url, 'Google Sign In', `width=${width},height=${height},left=${left},top=${top},popup=1`);
596
500
  // This may never return...
597
501
  return new Promise((resolve, reject) => {
@@ -600,12 +504,12 @@ class SocialLoginWeb extends core.WebPlugin {
600
504
  return;
601
505
  }
602
506
  const handleMessage = (event) => {
603
- var _a;
604
- if (event.origin !== window.location.origin)
507
+ var _a, _b, _c;
508
+ if (event.origin !== window.location.origin || ((_b = (_a = event.data) === null || _a === void 0 ? void 0 : _a.source) === null || _b === void 0 ? void 0 : _b.startsWith('angular')))
605
509
  return;
606
- if (((_a = event.data) === null || _a === void 0 ? void 0 : _a.type) === 'oauth-response') {
510
+ if (((_c = event.data) === null || _c === void 0 ? void 0 : _c.type) === 'oauth-response') {
607
511
  window.removeEventListener('message', handleMessage);
608
- if (this.googleLoginType === 'online') {
512
+ if (this.loginType === 'online') {
609
513
  const { accessToken, idToken } = event.data;
610
514
  if (accessToken && idToken) {
611
515
  const profile = this.parseJwt(idToken);
@@ -655,6 +559,103 @@ class SocialLoginWeb extends core.WebPlugin {
655
559
  });
656
560
  }
657
561
  }
562
+
563
+ class SocialLoginWeb extends core.WebPlugin {
564
+ constructor() {
565
+ var _a;
566
+ super();
567
+ this.googleProvider = new GoogleSocialLogin();
568
+ this.appleProvider = new AppleSocialLogin();
569
+ this.facebookProvider = new FacebookSocialLogin();
570
+ // Set up listener for OAuth redirects if we have a pending OAuth flow
571
+ if (localStorage.getItem(SocialLoginWeb.OAUTH_STATE_KEY)) {
572
+ console.log('OAUTH_STATE_KEY found');
573
+ const result = this.handleOAuthRedirect();
574
+ if (result) {
575
+ (_a = window.opener) === null || _a === void 0 ? void 0 : _a.postMessage(Object.assign({ type: 'oauth-response' }, result.result), window.location.origin);
576
+ window.close();
577
+ }
578
+ }
579
+ }
580
+ handleOAuthRedirect() {
581
+ const url = new URL(window.location.href);
582
+ return this.googleProvider.handleOAuthRedirect(url);
583
+ }
584
+ async initialize(options) {
585
+ var _a, _b, _c;
586
+ const initPromises = [];
587
+ if ((_a = options.google) === null || _a === void 0 ? void 0 : _a.webClientId) {
588
+ initPromises.push(this.googleProvider.initialize(options.google.webClientId, options.google.mode, options.google.hostedDomain));
589
+ }
590
+ if ((_b = options.apple) === null || _b === void 0 ? void 0 : _b.clientId) {
591
+ initPromises.push(this.appleProvider.initialize(options.apple.clientId, options.apple.redirectUrl));
592
+ }
593
+ if ((_c = options.facebook) === null || _c === void 0 ? void 0 : _c.appId) {
594
+ initPromises.push(this.facebookProvider.initialize(options.facebook.appId));
595
+ }
596
+ await Promise.all(initPromises);
597
+ }
598
+ async login(options) {
599
+ switch (options.provider) {
600
+ case 'google':
601
+ return this.googleProvider.login(options.options);
602
+ case 'apple':
603
+ return this.appleProvider.login(options.options);
604
+ case 'facebook':
605
+ return this.facebookProvider.login(options.options);
606
+ default:
607
+ throw new Error(`Login for ${options.provider} is not implemented on web`);
608
+ }
609
+ }
610
+ async logout(options) {
611
+ switch (options.provider) {
612
+ case 'google':
613
+ return this.googleProvider.logout();
614
+ case 'apple':
615
+ return this.appleProvider.logout();
616
+ case 'facebook':
617
+ return this.facebookProvider.logout();
618
+ default:
619
+ throw new Error(`Logout for ${options.provider} is not implemented`);
620
+ }
621
+ }
622
+ async isLoggedIn(options) {
623
+ switch (options.provider) {
624
+ case 'google':
625
+ return this.googleProvider.isLoggedIn();
626
+ case 'apple':
627
+ return this.appleProvider.isLoggedIn();
628
+ case 'facebook':
629
+ return this.facebookProvider.isLoggedIn();
630
+ default:
631
+ throw new Error(`isLoggedIn for ${options.provider} is not implemented`);
632
+ }
633
+ }
634
+ async getAuthorizationCode(options) {
635
+ switch (options.provider) {
636
+ case 'google':
637
+ return this.googleProvider.getAuthorizationCode();
638
+ case 'apple':
639
+ return this.appleProvider.getAuthorizationCode();
640
+ case 'facebook':
641
+ return this.facebookProvider.getAuthorizationCode();
642
+ default:
643
+ throw new Error(`getAuthorizationCode for ${options.provider} is not implemented`);
644
+ }
645
+ }
646
+ async refresh(options) {
647
+ switch (options.provider) {
648
+ case 'google':
649
+ return this.googleProvider.refresh();
650
+ case 'apple':
651
+ return this.appleProvider.refresh();
652
+ case 'facebook':
653
+ return this.facebookProvider.refresh(options.options);
654
+ default:
655
+ throw new Error(`Refresh for ${options.provider} is not implemented`);
656
+ }
657
+ }
658
+ }
658
659
  SocialLoginWeb.OAUTH_STATE_KEY = 'social_login_oauth_pending';
659
660
 
660
661
  var web = /*#__PURE__*/Object.freeze({