@capgo/capacitor-social-login 1.2.6 → 6.0.1

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