-
Notifications
You must be signed in to change notification settings - Fork 2
/
AuthGoogle.ts
61 lines (49 loc) · 1.88 KB
/
AuthGoogle.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
import { AuthMethodKey } from './auth.model';
import { IAuth } from './IAuth';
import { googleConfig } from '../../services/google.config';
import { loadGapiInsideDOM, loadAuth2WithProps } from 'gapi-script';
export class AuthGoogle implements IAuth {
public type: AuthMethodKey = 'GOOGLE';
private instance: gapi.auth2.GoogleAuthBase | undefined;
constructor(){
console.log('starting auth google');
this.initialize()
}
public signIn = async () => {
console.log('signIn google');
if(!this.instance) await this.initialize();
await this.instance?.attachClickHandler(document.body, {}, this.onSuccess, this.onFailure);
};
public signOut = async () => {
console.log('signOut google');
if(!this.instance) await this.initialize();
this.instance?.signOut();
};
public isAuthenticated = async () => {
if(!this.instance) await this.initialize();
return await (!!this.instance && this.instance.isSignedIn.get());
};
public getUser = async () => {
if(!this.instance) await this.initialize();
if(this.instance?.isSignedIn.get()) {
const googleUser = this.instance?.currentUser.get();
return {
username: googleUser.getBasicProfile().getName(),
email: googleUser.getBasicProfile().getEmail(),
photo: googleUser.getBasicProfile().getImageUrl(),
}
}
return undefined;
}
private initialize = async () => {
await loadGapiInsideDOM();
this.instance = await loadAuth2WithProps(gapi, googleConfig);
}
private onSuccess = (googleUser: gapi.auth2.GoogleUser) => {
// Do something on success authentication
}
private onFailure = (error: string) => {
// Do something on failure authentication
alert(JSON.stringify(error));
}
}