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 GIS Implicit flow for web #259

Closed
wants to merge 2 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
43 changes: 12 additions & 31 deletions package-lock.json

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

8 changes: 4 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,7 +9,8 @@
"clean": "rm -rf ./dist",
"watch": "tsc --watch",
"prepublishOnly": "npm run build",
"prepare": "tsc"
"prepare": "tsc",
"prettier": "prettier -w src/*"
},
"author": "CodetrixStudio",
"license": "MIT",
Expand All @@ -19,8 +20,7 @@
"@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
11 changes: 11 additions & 0 deletions src/definitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,14 @@ export interface GoogleAuthPlugin {
* */
initialize(options?: Partial<InitOptions>): void;
}

export interface UserInfo {
sub: string;
name: string;
given_name: string;
family_name: string;
picture: string;
email: string;
email_verified: boolean;
locale: string;
}
159 changes: 83 additions & 76 deletions src/web.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import { WebPlugin } from '@capacitor/core';
import { GoogleAuthPlugin, InitOptions, User } from './definitions';
import { Authentication, GoogleAuthPlugin, InitOptions, User, UserInfo } from './definitions';

/**
* We use implicit flow as it doesn't require a backend platform (see https://developers.google.com/identity/oauth2/web/guides/choose-authorization-model#oauth_20_flow_comparison)
*/
export class GoogleAuthWeb extends WebPlugin implements GoogleAuthPlugin {
gapiLoaded: Promise<void>;
options: InitOptions;
private accessToken: string;

constructor() {
super();
Expand All @@ -14,7 +18,7 @@ export class GoogleAuthWeb extends WebPlugin implements GoogleAuthPlugin {
return;
}

const scriptId = 'gapi';
const scriptId = 'gsi';
const scriptEl = document?.getElementById(scriptId);

if (scriptEl) {
Expand All @@ -28,16 +32,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,
grantOfflineAccess: false, // Deprecated
}
) {
if (typeof window === 'undefined') {
Expand All @@ -54,101 +57,105 @@ export class GoogleAuthWeb extends WebPlugin implements GoogleAuthPlugin {
this.options = {
clientId,
grantOfflineAccess: _options.grantOfflineAccess ?? false,
scopes: _options.scopes || [],
scopes: _options.scopes || ['profile', 'email', 'openid'],
};

if (this.options.grantOfflineAccess) {
// @see https://developers.google.com/identity/oauth2/web/guides/migration-to-gis#library_quick_reference
// Stating "Remove, follow the authorization code flow."
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(' ');
async signIn(): Promise<User> {
return new Promise<User>(async (resolve, reject) => {
try {
const tokenClient = google.accounts.oauth2.initTokenClient({
client_id: this.options.clientId,
scope: this.options.scopes.join(' '),
error_callback: () => {
reject({ message: 'GoogleAuthPlugin - Popup skipped or not displayed' });
},
callback: (tokenResponse) => {
this.accessToken = tokenResponse.access_token;
const that = this;

const xhr = new XMLHttpRequest();
// See https://developers.google.com/identity/openid-connect/openid-connect#discovery for url
xhr.open('GET', 'https://openidconnect.googleapis.com/v1/userinfo');
xhr.setRequestHeader('Authorization', 'Bearer ' + this.accessToken);
xhr.onreadystatechange = function () {
if (this.readyState === XMLHttpRequest.DONE) {
if (this.status === 200) {
const user = that.getUserFrom(JSON.parse(xhr.responseText));
user.authentication = {
accessToken: that.accessToken,
idToken: '', // not provided in implicit flow
refreshToken: '', // not provided in implicit flow
};
resolve(user);
} else {
reject({ message: 'GoogleAuthPlugin - Wrong userinfo request' });
}
}
};
xhr.send();
},
});

// Request for popup to open
tokenClient.requestAccessToken();
} catch (error) {
reject(error);
}

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

async signIn() {
return new Promise<User>(async (resolve, reject) => {
refresh(): Promise<Authentication> {
return new Promise<Authentication>(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);
const tokenClient = google.accounts.oauth2.initTokenClient({
client_id: this.options.clientId,
scope: this.options.scopes.join(' '),
callback: (tokenResponse) => {
resolve({
accessToken: tokenResponse.access_token,
idToken: '', // not provided in implicit flow
refreshToken: '', // not provided in implicit flow
});
},
error_callback: () => {
reject(null);
},
});
// Request for popup to open
tokenClient.requestAccessToken();
} catch (error) {
reject(error);
}
});
}

async refresh() {
const authResponse = await gapi.auth2.getAuthInstance().currentUser.get().reloadAuthResponse();
return {
accessToken: authResponse.access_token,
idToken: authResponse.id_token,
refreshToken: '',
};
}

async signOut() {
return gapi.auth2.getAuthInstance().signOut();
}
signOut(): Promise<any> {
google.accounts.oauth2.revoke(this.accessToken, () => {});

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

private getUserFrom(googleUser: gapi.auth2.GoogleUser) {
getUserFrom(userJson: UserInfo): 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,
refreshToken: '',
};
user.email = userJson.email;
user.familyName = userJson.family_name;
user.givenName = userJson.given_name;
user.id = userJson.sub;
user.imageUrl = userJson.picture;
user.name = userJson.name;

return user;
}
Expand Down