-
Notifications
You must be signed in to change notification settings - Fork 144
/
web.ts
99 lines (79 loc) · 2.76 KB
/
web.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import { WebPlugin } from '@capacitor/core';
import { GoogleAuthPlugin } from './definitions';
// @ts-ignore
import config from '../../../../../capacitor.config.json';
export class GoogleAuthWeb extends WebPlugin implements GoogleAuthPlugin {
constructor() {
super({
name: 'GoogleAuth',
platforms: ['web']
});
this.initialize();
}
initialize() {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.defer = true;
script.async = true;
script.onload = this.platformJsLoaded;
script.src = 'https://apis.google.com/js/platform.js';
head.appendChild(script);
}
platformJsLoaded() {
gapi.load('auth2', async () => {
const clientConfig: gapi.auth2.ClientConfig = {
client_id: (document.getElementsByName('google-signin-client_id')[0] as any).content
};
if (config.plugins.GoogleAuth != null && config.plugins.GoogleAuth.scopes != null) {
clientConfig.scope = config.plugins.GoogleAuth.scopes.join(' ');
}
gapi.auth2.init(clientConfig);
});
}
async signIn(): Promise<any> {
return new Promise(async (resolve, reject) => {
try {
const user: any = {};
var needsOfflineAccess = false;
try {
needsOfflineAccess = config.plugins.GoogleAuth.serverClientId != null;
} catch {
}
if (needsOfflineAccess) {
const offlineAccessResponse = await gapi.auth2.getAuthInstance().grantOfflineAccess();
user.serverAuthCode = offlineAccessResponse.code;
} else {
await gapi.auth2.getAuthInstance().signIn();
}
const googleUser = gapi.auth2.getAuthInstance().currentUser.get();
if (needsOfflineAccess) {
// HACK: AuthResponse is null if we don't do this when using grantOfflineAccess
await googleUser.reloadAuthResponse();
}
const authResponse = googleUser.getAuthResponse(true);
const profile = googleUser.getBasicProfile();
user.email = profile.getEmail();
user.familyName = profile.getFamilyName();
user.givenName = profile.getGivenName();
user.id = profile.getId();
user.imageUrl = profile.getImageUrl();
user.name = profile.getName();
user.authentication = {
accessToken: authResponse.access_token,
idToken: authResponse.id_token
}
resolve(user);
} catch (error) {
reject(error);
}
});
}
async signOut(): Promise<any> {
return gapi.auth2.getAuthInstance().signOut();
}
}
const GoogleAuth = new GoogleAuthWeb();
export { GoogleAuth };
import { registerWebPlugin } from '@capacitor/core';
registerWebPlugin(GoogleAuth);