Skip to content

Commit

Permalink
Listener for user state change
Browse files Browse the repository at this point in the history
  • Loading branch information
fullstackduck committed Feb 15, 2020
1 parent a9a5101 commit 0c3e2ee
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 26 deletions.
8 changes: 6 additions & 2 deletions demo/src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,21 @@ export class AppComponent implements OnInit {

ngOnInit() {
SplashScreen.hide();

GoogleAuth.addListener('userChange', (googleUser) => {
console.log("userChange:", googleUser);
});
}

async signIn() {
let googleUser = await GoogleAuth.signIn();
this.username = googleUser.name;
console.log(googleUser);
console.log("signIn:", googleUser);
}

async refreshToken() {
let response = await GoogleAuth.refresh();
console.log(response);
console.log("refresh:", response);
}

async signOut() {
Expand Down
17 changes: 17 additions & 0 deletions src/user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
export interface User {
id: string;
email: string;

name: string;
familyName: string;
givenName: string;
imageUrl: string;

serverAuthCode: string;
authentication: Authentication;
}

export interface Authentication {
accessToken: string;
idToken: string;
}
76 changes: 52 additions & 24 deletions src/web.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,34 @@
import { WebPlugin } from '@capacitor/core';
import { GoogleAuthPlugin } from './definitions';
import { User, Authentication } from './user';

// @ts-ignore
import config from '../../../../../capacitor.config.json';

export class GoogleAuthWeb extends WebPlugin implements GoogleAuthPlugin {

gapiLoaded: Promise<void>;

get webConfigured(): boolean {
return document.getElementsByName('google-signin-client_id').length > 0;
}

constructor() {
super({
name: 'GoogleAuth',
platforms: ['web']
});

if (this.webConfigured)
if (!this.webConfigured)
return;

this.gapiLoaded = new Promise(resolve => {
// HACK: Relying on window object, can't get property in gapi.load callback
(window as any).gapiResolve = resolve;
this.initialize();
}
});

get webConfigured(): boolean {
return document.getElementsByName('google-signin-client_id').length > 0;
this.addUserChangeListener();
}

initialize() {
Expand All @@ -30,7 +43,7 @@ export class GoogleAuthWeb extends WebPlugin implements GoogleAuthPlugin {
}

platformJsLoaded() {
gapi.load('auth2', async () => {
gapi.load('auth2', () => {
const clientConfig: gapi.auth2.ClientConfig = {
client_id: (document.getElementsByName('google-signin-client_id')[0] as any).content
};
Expand All @@ -40,15 +53,16 @@ export class GoogleAuthWeb extends WebPlugin implements GoogleAuthPlugin {
}

gapi.auth2.init(clientConfig);
(window as any).gapiResolve();
});
}

async signIn(): Promise<any> {
return new Promise(async (resolve, reject) => {
try {
const user: any = {};

var serverAuthCode: string;
var needsOfflineAccess = false;

try {
needsOfflineAccess = config.plugins.GoogleAuth.serverClientId != null;
} catch {
Expand All @@ -57,7 +71,7 @@ export class GoogleAuthWeb extends WebPlugin implements GoogleAuthPlugin {

if (needsOfflineAccess) {
const offlineAccessResponse = await gapi.auth2.getAuthInstance().grantOfflineAccess();
user.serverAuthCode = offlineAccessResponse.code;
serverAuthCode = offlineAccessResponse.code;
} else {
await gapi.auth2.getAuthInstance().signIn();
}
Expand All @@ -69,29 +83,16 @@ export class GoogleAuthWeb extends WebPlugin implements GoogleAuthPlugin {
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
}

const user = this.getUserFrom(googleUser);
user.serverAuthCode = serverAuthCode;
resolve(user);
} catch (error) {
reject(error);
}
});
}

async refresh(): Promise<any> {
async refresh(): Promise<Authentication> {
const authResponse = await gapi.auth2.getAuthInstance().currentUser.get().reloadAuthResponse()
return {
accessToken: authResponse.access_token,
Expand All @@ -102,6 +103,33 @@ export class GoogleAuthWeb extends WebPlugin implements GoogleAuthPlugin {
async signOut(): Promise<any> {
return gapi.auth2.getAuthInstance().signOut();
}

private async addUserChangeListener() {
await this.gapiLoaded;
gapi.auth2.getAuthInstance().currentUser.listen(googleUser => {
this.notifyListeners("userChange", googleUser.isSignedIn() ? this.getUserFrom(googleUser) : null);
});
}

private getUserFrom(googleUser: gapi.auth2.GoogleUser): User {
const user = {} as User;
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();

const authResponse = googleUser.getAuthResponse(true);
user.authentication = {
accessToken: authResponse.access_token,
idToken: authResponse.id_token
}

return user;
}
}

const GoogleAuth = new GoogleAuthWeb();
Expand Down

0 comments on commit 0c3e2ee

Please sign in to comment.