Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Google GIS for web. #257

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 28 additions & 33 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 7 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@codetrix-studio/capacitor-google-auth",
"version": "3.2.2",
"version": "3.3.0",
"description": "Google Auth plugin for capacitor.",
"main": "dist/esm/index.js",
"types": "dist/esm/index.d.ts",
Expand All @@ -9,18 +9,21 @@
"clean": "rm -rf ./dist",
"watch": "tsc --watch",
"prepublishOnly": "npm run build",
"prepare": "tsc"
"prepare": "tsc",
"prettier": "prettier -w src/*"
},
"author": "CodetrixStudio",
"license": "MIT",
"dependencies": {
"jose": "^4.11.2"
},
"devDependencies": {
"@capacitor/android": "^4.0.1",
"@capacitor/cli": "^4.0.1",
"@capacitor/core": "^4.0.1",
"@capacitor/ios": "^4.0.1",
"@ionic/prettier-config": "^2.0.0",
"@types/gapi": "0.0.42",
"@types/gapi.auth2": "0.0.56",
"@types/google.accounts": "^0.0.5",
"prettier": "^2.7.1",
"typescript": "^4.7.4"
},
Expand Down
115 changes: 46 additions & 69 deletions src/web.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { WebPlugin } from '@capacitor/core';
import { GoogleAuthPlugin, InitOptions, User } from './definitions';
import { Authentication, GoogleAuthPlugin, InitOptions, User } from './definitions';
import { decodeJwt } from 'jose';
import { JWTPayload } from 'jose';

export class GoogleAuthWeb extends WebPlugin implements GoogleAuthPlugin {
gapiLoaded: Promise<void>;
Expand Down Expand Up @@ -28,16 +30,15 @@ export class GoogleAuthWeb extends WebPlugin implements GoogleAuthPlugin {
script.defer = true;
script.async = true;
script.id = scriptId;
script.onload = this.platformJsLoaded.bind(this);
script.src = 'https://apis.google.com/js/platform.js';
script.src = 'https://accounts.google.com/gsi/client';
head.appendChild(script);
}

initialize(
_options: Partial<InitOptions> = {
clientId: '',
scopes: [],
grantOfflineAccess: false,
scopes: [], // Deprecated
grantOfflineAccess: false, // Deprecated
}
) {
if (typeof window === 'undefined') {
Expand All @@ -57,96 +58,72 @@ export class GoogleAuthWeb extends WebPlugin implements GoogleAuthPlugin {
scopes: _options.scopes || [],
};

if (this.options.grantOfflineAccess) {
console.warn('GoogleAuthPlugin - grantOfflineAccess true is deprecated');
}

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

this.addUserChangeListener();
}

platformJsLoaded() {
gapi.load('auth2', () => {
// https://github.com/CodetrixStudio/CapacitorGoogleAuth/issues/202#issuecomment-1147393785
const clientConfig: gapi.auth2.ClientConfig & { plugin_name: string } = {
client_id: this.options.clientId,
plugin_name: 'CodetrixStudioCapacitorGoogleAuth',
};

if (this.options.scopes.length) {
clientConfig.scope = this.options.scopes.join(' ');
}

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

async signIn() {
async signIn(): Promise<User> {
return new Promise<User>(async (resolve, reject) => {
try {
let serverAuthCode: string;
const needsOfflineAccess = this.options.grantOfflineAccess ?? false;

if (needsOfflineAccess) {
const offlineAccessResponse = await gapi.auth2.getAuthInstance().grantOfflineAccess();
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 user = this.getUserFrom(googleUser);
user.serverAuthCode = serverAuthCode;
resolve(user);
google.accounts.id.initialize({
client_id: this.options.clientId,
callback: (response: google.accounts.id.CredentialResponse) => {
const jwtPayload = decodeJwt(response.credential);
const user = this.getUserFrom(jwtPayload);
resolve(user);
},
});

// Request for popup to open
google.accounts.id.prompt((notification) => {
if (notification.isNotDisplayed()) {
reject({ message: 'Not Displayed' });
}
if (notification.isSkippedMoment()) {
reject({ message: 'Skipped' });
}
});
} catch (error) {
reject(error);
}
});
}

async refresh() {
const authResponse = await gapi.auth2.getAuthInstance().currentUser.get().reloadAuthResponse();
async refresh(): Promise<Authentication> {
// Doesn't look to be used with GIS
return {
accessToken: authResponse.access_token,
idToken: authResponse.id_token,
accessToken: '',
idToken: '',
refreshToken: '',
};
}

async signOut() {
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);
});
async signOut(): Promise<any> {
// Doesn't look to be used with GIS
return new Promise(null);
}

private getUserFrom(googleUser: gapi.auth2.GoogleUser) {
private getUserFrom(jwtPaylod: JWTPayload) {
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();
user.email = jwtPaylod.email as string;
user.familyName = jwtPaylod.family_name as string;
user.givenName = jwtPaylod.given_name as string;
user.id = jwtPaylod.sub as string;
user.imageUrl = jwtPaylod.picture as string;
user.name = jwtPaylod.name as string;

const authResponse = googleUser.getAuthResponse(true);
// Todo: also deprecated ?
user.authentication = {
accessToken: authResponse.access_token,
idToken: authResponse.id_token,
accessToken: '', // was authResponse.access_token
idToken: '', // was authResponse.id_token
refreshToken: '',
};

Expand Down