Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: CodetrixStudio/CapacitorGoogleAuth
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: 3.4.0-rc.1
Choose a base ref
...
head repository: CodetrixStudio/CapacitorGoogleAuth
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: master
Choose a head ref
  • 11 commits
  • 8 files changed
  • 7 contributors

Commits on Apr 29, 2024

  1. fix: revert iOS changes

    reslear authored Apr 29, 2024

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature.
    Copy the full SHA
    56c4e6e View commit details

Commits on Apr 30, 2024

  1. Update package.json

    reslear authored Apr 30, 2024

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature.
    Copy the full SHA
    f613415 View commit details

Commits on May 1, 2024

  1. Custom scopes for different requirements (Android and iOS) (#269)

    * Moved google auth initialize methods from the load function to the initialize function for users to add scopes on the fly
    
    * custom scopes for ios
    
    * update readme
    
    * update readme
    AlvinTCH authored May 1, 2024

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature.
    Copy the full SHA
    f5fa8d9 View commit details
  2. v3.4.0-rc.4

    reslear authored May 1, 2024

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature.
    Copy the full SHA
    6bda60c View commit details

Commits on May 2, 2024

  1. Update README.md (#360)

    Add additional description for custom scopes in initialize
    AlvinTCH authored May 2, 2024

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature.
    Copy the full SHA
    b91b485 View commit details

Commits on May 30, 2024

  1. Update README.md (#368)

    Use with updated firebase@^10.11
    mw-ferretti authored May 30, 2024

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature.
    Copy the full SHA
    fdee173 View commit details

Commits on Aug 1, 2024

  1. refactor: Improvement/bump gms google auth version (#382)

    * allow supplying play services auth version & set default to 21.2.0
    
    * update package.lock json to match current version
    
    * check for nullclients on sign-in & sign-out
    
    * correctly return void after nullClient errors
    selcuk-sahin authored Aug 1, 2024

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature.
    Copy the full SHA
    e808d9e View commit details

Commits on Aug 15, 2024

  1. Update README.md for changes introduced in #269 (#390)

    * Update README.md
    
    * Update README.md
    
    * Update README.md
    riderx authored Aug 15, 2024

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature.
    Copy the full SHA
    7d525b0 View commit details

Commits on Aug 28, 2024

  1. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature.
    Copy the full SHA
    4212948 View commit details

Commits on Sep 2, 2024

  1. Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature.
    Copy the full SHA
    3e69246 View commit details

Commits on Oct 11, 2024

  1. Update README.md (#401)

    riderx authored Oct 11, 2024

    Verified

    This commit was created on GitHub.com and signed with GitHub’s verified signature.
    Copy the full SHA
    43125e4 View commit details
Showing with 130 additions and 55 deletions.
  1. +35 −24 README.md
  2. +2 −1 android/build.gradle
  3. +43 −11 android/src/main/java/com/codetrixstudio/capacitor/GoogleAuth/GoogleAuth.java
  4. +8 −2 ios/Plugin/Plugin.m
  5. +36 −12 ios/Plugin/Plugin.swift
  6. +3 −3 package-lock.json
  7. +2 −2 package.json
  8. +1 −0 tsconfig.json
59 changes: 35 additions & 24 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
> [!WARNING]
> This plugin is now in low maintainance mode, for new feature like Credential manager or Privacy manifest please use: https://github.com/Cap-go/capacitor-social-login
<h1 align="center">CapacitorGoogleAuth</h1>
<p align="center"><strong><code>@codetrix-studio/capacitor-google-auth</code></strong></p>
<p align="center"><strong>CAPACITOR 6</strong></p>
@@ -9,6 +12,10 @@ Capacitor plugin for Google Auth.
<a href="https://www.npmjs.com/package/@codetrix-studio/capacitor-google-auth"><img alt="npm" src="https://img.shields.io/npm/v/@codetrix-studio/capacitor-google-auth"></a> <a href="https://www.npmjs.com/package/@codetrix-studio/capacitor-google-auth"><img alt="npm" src="https://img.shields.io/npm/dt/@codetrix-studio/capacitor-google-auth"></a> <a href="https://www.npmjs.com/package/@codetrix-studio/capacitor-google-auth"><img alt="npm" src="https://img.shields.io/npm/dw/@codetrix-studio/capacitor-google-auth"></a> <a href="https://libraries.io/npm/@codetrix-studio%2Fcapacitor-google-auth"><img alt="Dependents (via libraries.io)" src="https://img.shields.io/librariesio/dependents/npm/@codetrix-studio/capacitor-google-auth"></a> <a href="https://packagephobia.com/result?p=@codetrix-studio/capacitor-google-auth"><img alt="install size" src="https://packagephobia.com/badge?p=@codetrix-studio/capacitor-google-auth"></a>
</p>

## Breaking change in V6

In the v6 version, `clientId` in the initialize method is used in priority over other places you could set up. If before you were using this only on the web, unset it on mobile. Or set it conditionally to replicate old behavior.

## Contributions

PRs are welcome and much appreciated that keeps this plugin up to date with Capacitor and official Google Auth platform library feature parity.
@@ -99,14 +106,20 @@ initializeApp() {
sign in function

```ts
import { GoogleAuth } from "@codetrix-studio/capacitor-google-auth";
import { Auth, GoogleAuthProvider, signInWithCredential } from '@angular/fire/auth';

async googleSignIn() {
let googleUser = await GoogleAuth.signIn();

/*
If you use Firebase you can forward and use the logged in Google user like this:
*/
const credential = auth.GoogleAuthProvider.credential(googleUser.authentication.idToken);
return this.afAuth.auth.signInAndRetrieveDataWithCredential(credential);
constructor(private auth: Auth){}

const googleUser = await GoogleAuth.signIn();
const _credential = GoogleAuthProvider.credential(googleUser.authentication.idToken);
return signInWithCredential(this.auth, _credential);
}
```

@@ -137,33 +150,30 @@ or see more [CapacitorGoogleAuth-Vue3-example](https://github.com/reslear/Capaci
2. Add **identifier** `REVERSED_CLIENT_ID` as **URL schemes** to `Info.plist` from **iOS URL scheme**<br>
(Xcode: App - Targets/App - Info - URL Types, click plus icon)

3. Set **Client ID** one of the ways:
1. Set in `capacitor.config.json`
- `iosClientId` - specific key for iOS
- `clientId` - or common key for Android and iOS
2. Download `GoogleService-Info.plist` file with `CLIENT_ID` and copy to **ios/App/App** necessarily through Xcode for indexing.

plugin first use `iosClientId` if not found use `clientId` if not found use value `CLIENT_ID` from file `GoogleService-Info.plist`
3. Set **Client ID** one of the ways (by order of importance in the plugin):
1. Set `clientId` in initialize method
2. Set `iosClientId` in `capacitor.config.json`
3. Set `clientId` in `capacitor.config.json`
4. Set `CLIENT_ID` in `GoogleService-Info.plist`

### Android

Set **Client ID** :

1. In `capacitor.config.json`

- `androidClientId` - specific key for Android
- `clientId` - or common key for Android and iOS

2. or set inside your `strings.xml`

plugin first use `androidClientId` if not found use `clientId` if not found use value `server_client_id` from file `strings.xml`
Set **Client ID** (by order of importance in the plugin):
1. Set `clientId` in initialize method
2. Set `androidClientId` in `capacitor.config.json`
3. Set `clientId` in `capacitor.config.json`
4. Set `server_client_id` in `strings.xml`

```xml
<resources>
<string name="server_client_id">Your Web Client Key</string>
</resources>
```

Changing Play Services Auth version (Optional) :

This plugin uses `com.google.android.gms:play-services-auth:21.2.0` by default, you can override it providing `gmsPlayServicesAuthVersion` at `variables.gradle`

**Refresh method**

This method should be called when the app is initialized to establish if the user is currently logged in. If true, the method will return an accessToken, idToken and an empty refreshToken.
@@ -225,6 +235,7 @@ const config: CapacitorConfig = {

export default config;
```
#### Note: scopes can be configured under <code><a href="#initialize">initialize</a></code> function.

## API

@@ -301,11 +312,11 @@ Signs out the user and returns a Promise.

#### InitOptions

| Prop | Type | Description | Default | Since |
| ------------------------ | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------ | ----- |
| **`clientId`** | <code>string</code> | The app's client ID, found and created in the Google Developers Console. Common for Android or iOS. The default is defined in the configuration. | | 3.1.0 |
| **`scopes`** | <code>string[]</code> | Specifies the scopes required for accessing Google APIs The default is defined in the configuration. | | |
| **`grantOfflineAccess`** | <code>boolean</code> | Set if your application needs to refresh access tokens when the user is not present at the browser. In response use `serverAuthCode` key | <code>false</code> | 3.1.0 |
| Prop | Type | Description | Default | Since |
| ------------------------ | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------ | ---------- |
| **`clientId`** | <code>string</code> | The app's client ID, found and created in the Google Developers Console. Common for Android or iOS. The default is defined in the configuration. | | 3.1.0 |
| **`scopes`** | <code>string[]</code> | Specifies the scopes required for accessing Google APIs The default is defined in the configuration. | | 3.4.0-rc.4 |
| **`grantOfflineAccess`** | <code>boolean</code> | Set if your application needs to refresh access tokens when the user is not present at the browser. In response use `serverAuthCode` key | <code>false</code> | 3.1.0 |


#### User
3 changes: 2 additions & 1 deletion android/build.gradle
Original file line number Diff line number Diff line change
@@ -3,6 +3,7 @@ ext {
androidxAppCompatVersion = project.hasProperty('androidxAppCompatVersion') ? rootProject.ext.androidxAppCompatVersion : '1.6.1'
androidxJunitVersion = project.hasProperty('androidxJunitVersion') ? rootProject.ext.androidxJunitVersion : '1.1.5'
androidxEspressoCoreVersion = project.hasProperty('androidxEspressoCoreVersion') ? rootProject.ext.androidxEspressoCoreVersion : '3.5.1'
gmsPlayServicesAuthVersion = project.hasProperty('gmsPlayServicesAuthVersion') ? rootProject.ext.gmsPlayServicesAuthVersion : '21.2.0'
}

buildscript {
@@ -57,5 +58,5 @@ dependencies {
testImplementation "junit:junit:$junitVersion"
androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
implementation 'com.google.android.gms:play-services-auth:18.+'
implementation "com.google.android.gms:play-services-auth:$gmsPlayServicesAuthVersion"
}
Original file line number Diff line number Diff line change
@@ -53,23 +53,15 @@ public class GoogleAuth extends Plugin {

private GoogleSignInClient googleSignInClient;

@Override
public void load() {
String clientId = getConfig().getString("androidClientId",
getConfig().getString("clientId",
this.getContext().getString(R.string.server_client_id)));

boolean forceCodeForRefreshToken = getConfig().getBoolean("forceCodeForRefreshToken", false);

public void loadSignInClient (String clientId, boolean forceCodeForRefreshToken, String[] scopeArray) {
GoogleSignInOptions.Builder googleSignInBuilder = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(clientId)
.requestEmail();
.requestIdToken(clientId)
.requestEmail();

if (forceCodeForRefreshToken) {
googleSignInBuilder.requestServerAuthCode(clientId, true);
}

String[] scopeArray = getConfig().getArray("scopes", new String[] {});
Scope[] scopes = new Scope[scopeArray.length - 1];
Scope firstScope = new Scope(scopeArray[0]);
for (int i = 1; i < scopeArray.length; i++) {
@@ -81,8 +73,15 @@ public void load() {
googleSignInClient = GoogleSignIn.getClient(this.getContext(), googleSignInOptions);
}

@Override
public void load() {}

@PluginMethod()
public void signIn(PluginCall call) {
if(googleSignInClient == null){
rejectWithNullClientError(call);
return;
}
Intent signInIntent = googleSignInClient.getSignInIntent();
startActivityForResult(call, signInIntent, "signInResult");
}
@@ -160,6 +159,10 @@ public void refresh(final PluginCall call) {

@PluginMethod()
public void signOut(final PluginCall call) {
if(googleSignInClient == null){
rejectWithNullClientError(call);
return;
}
googleSignInClient.signOut()
.addOnSuccessListener(getActivity(), new OnSuccessListener<Void>() {
@Override
@@ -177,6 +180,31 @@ public void onFailure(Exception e) {

@PluginMethod()
public void initialize(final PluginCall call) {
// get data from config
String configClientId = getConfig().getString("androidClientId",
getConfig().getString("clientId",
this.getContext().getString(R.string.server_client_id)));
boolean configForceCodeForRefreshToken = getConfig().getBoolean("forceCodeForRefreshToken", false);
// need to get this as string so as to standardize with data from plugin call
String configScopeArray = getConfig().getString("scopes", new String());

// get client id from plugin call, fallback to be client id from config
String clientId = call.getData().getString("clientId", configClientId);
// get forceCodeForRefreshToken from call, fallback to be from config
boolean forceCodeForRefreshToken = call.getData().getBoolean("grantOfflineAccess", configForceCodeForRefreshToken);
// get scopes from call, fallback to be from config
String scopesStr = call.getData().getString("scopes", configScopeArray);
// replace all the symbols from parsing array as string
// leaving only scopes delimited by commas
String replacedScopesStr = scopesStr
.replaceAll("[\"\\[\\] ]", "")
// this is for scopes that are in the form of a url
.replace("\\", "");

// scope to be in the form of an array
String[] scopeArray = replacedScopesStr.split(",");

loadSignInClient(clientId, forceCodeForRefreshToken, scopeArray);
call.resolve();
}

@@ -237,4 +265,8 @@ private static String fromStream(InputStream is) throws IOException {
reader.close();
return sb.toString();
}

private void rejectWithNullClientError(final PluginCall call) {
call.reject("Google services are not ready. Please call initialize() first");
}
}
10 changes: 8 additions & 2 deletions ios/Plugin/Plugin.m
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
#import <Foundation/Foundation.h>
#import <Capacitor/Capacitor.h>

// Define the plugin using the CAP_PLUGIN Macro
CAP_PLUGIN(GoogleAuth, "GoogleAuth")
// Define the plugin using the CAP_PLUGIN Macro, and
// each method the plugin supports using the CAP_PLUGIN_METHOD macro.
CAP_PLUGIN(GoogleAuth, "GoogleAuth",
CAP_PLUGIN_METHOD(signIn, CAPPluginReturnPromise);
CAP_PLUGIN_METHOD(refresh, CAPPluginReturnPromise);
CAP_PLUGIN_METHOD(signOut, CAPPluginReturnPromise);
CAP_PLUGIN_METHOD(initialize, CAPPluginReturnPromise);
)
48 changes: 36 additions & 12 deletions ios/Plugin/Plugin.swift
Original file line number Diff line number Diff line change
@@ -14,34 +14,56 @@ public class GoogleAuth: CAPPlugin {
var forceAuthCode: Bool = false;
var additionalScopes: [String]!;


public override func load() {
func loadSignInClient (
customClientId: String,
customScopes: [String]
) {
googleSignIn = GIDSignIn.sharedInstance;

let serverClientId = getServerClientIdValue();

guard let clientId = getClientIdValue() else {
NSLog("no client id found in config")
return;
}

googleSignInConfiguration = GIDConfiguration.init(clientID: clientId, serverClientID: serverClientId)
googleSignInConfiguration = GIDConfiguration.init(clientID: customClientId, serverClientID: serverClientId)

// these are scopes granted by default by the signIn method
let defaultGrantedScopes = ["email", "profile", "openid"];

// these are scopes we will need to request after sign in
additionalScopes = (getConfig().getArray("scopes") as? [String] ?? []).filter {
additionalScopes = customScopes.filter {
return !defaultGrantedScopes.contains($0);
};

forceAuthCode = getConfig().getBoolean("forceCodeForRefreshToken", false)

NotificationCenter.default.addObserver(self, selector: #selector(handleOpenUrl(_ :)), name: Notification.Name(Notification.Name.capacitorOpenURL.rawValue), object: nil);
}


public override func load() {
}

@objc
func initialize(_ call: CAPPluginCall) {
// get client id from initialize, with client id from config file as fallback
guard let clientId = call.getString("clientId") ?? getClientIdValue() as? String else {
NSLog("no client id found in config");
call.resolve();
return;
}

// get scopes from initialize, with scopes from config file as fallback
let customScopes = call.getArray("scopes", String.self) ?? (
getConfigValue("scopes") as? [String] ?? []
);

// get force auth code from initialize, with config from config file as fallback
forceAuthCode = call.getBool("grantOfflineAccess") ?? (
getConfigValue("forceCodeForRefreshToken") as? Bool ?? false
);

// load client
self.loadSignInClient(
customClientId: clientId,
customScopes: customScopes
)
call.resolve();
}

@@ -96,7 +118,9 @@ public class GoogleAuth: CAPPlugin {
@objc
func signOut(_ call: CAPPluginCall) {
DispatchQueue.main.async {
self.googleSignIn.signOut();
if self.googleSignIn != nil {
self.googleSignIn.signOut();
}
}
call.resolve();
}
6 changes: 3 additions & 3 deletions package-lock.json

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

4 changes: 2 additions & 2 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.4.0-rc.1",
"version": "3.4.0-rc.4",
"description": "Google Auth plugin for capacitor.",
"main": "dist/esm/index.js",
"types": "dist/esm/index.d.ts",
@@ -66,4 +66,4 @@
"url": "https://github.com/CodetrixStudio/CapacitorGoogleAuth/issues"
},
"prettier": "@ionic/prettier-config"
}
}
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -11,6 +11,7 @@
"noUnusedParameters": true,
"outDir": "dist/esm",
"sourceMap": true,
"skipLibCheck": true,
"target": "es2017"
},
"files": ["src/index.ts"]