### Install and Run Demo App Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/README.md Instructions to navigate to the demo app directory, install dependencies, and start the development server. ```bash cd examples/google-auth-demo pnpm install pnpm tauri dev ``` -------------------------------- ### Install JavaScript API Package Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/README.md Install the JavaScript API package using npm, yarn, or pnpm. ```bash npm install @choochmeque/tauri-plugin-google-auth-api # or yarn add @choochmeque/tauri-plugin-google-auth-api # or pnpm add @choochmeque/tauri-plugin-google-auth-api ``` -------------------------------- ### Build and Install Android App Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/ANDROID_SETUP.md Commands to build the Tauri Android application and install the generated APK on a device or emulator. ```bash npm run tauri android build ``` ```bash adb install path/to/your-app.apk ``` -------------------------------- ### Error Handling Example for Sign-In Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/README.md Demonstrates how to implement error handling for the `signIn` function using a try-catch block. This is crucial for gracefully managing authentication failures. ```typescript try { await signIn({ clientId: 'YOUR_CLIENT_ID', scopes: ['openid'] }); } catch (error) { console.error('Sign-in failed:', error); } ``` -------------------------------- ### TypeScript Example: Handling Token Response Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/types.md Demonstrates how to use the `signIn` function and access properties from the returned `TokenResponse` object. Includes logic to check token expiration. ```typescript const response = await signIn({ clientId: 'YOUR_CLIENT_ID', scopes: ['openid', 'email', 'profile'] }) // Access the tokens const accessToken = response.accessToken // Use for API calls const idToken = response.idToken // User info (JWT) const expiresAt = response.expiresAt // When to refresh const grantedScopes = response.scopes // What was granted // Check token expiration const now = Math.floor(Date.now() / 1000) const isExpired = expiresAt < now const expiresInMinutes = Math.floor((expiresAt - now) / 60) ``` -------------------------------- ### Desktop Token Refresh Example Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/api-reference/refresh-token.md Use this example to refresh a user's token on desktop applications. It requires the client ID and client secret. The response includes the new access token and expiration time, which should be stored. ```typescript import { refreshToken } from '@choochmeque/tauri-plugin-google-auth-api' async function refreshUserToken(storedRefreshToken) { try { const response = await refreshToken({ refreshToken: storedRefreshToken, clientId: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET' // Required for desktop }) console.log('New Access Token:', response.accessToken) console.log('Expires at:', new Date(response.expiresAt * 1000)) // Update stored tokens sessionStorage.setItem('accessToken', response.accessToken) sessionStorage.setItem('expiresAt', response.expiresAt.toString()) } catch (error) { console.error('Token refresh failed:', error) } } ``` -------------------------------- ### JavaScript/TypeScript Usage Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/ANDROID_SETUP.md Examples demonstrating how to use the signIn, signOut, and refreshToken functions from the plugin in your JavaScript or TypeScript code. ```APIDOC ## JavaScript/TypeScript Usage This section provides examples for using the plugin's core functions. ### Sign In Initiates the Google sign-in process. Supports both native and web flows. ```typescript import { signIn} from '@choochmeque/tauri-plugin-google-auth-api'; async function handleSignIn() { try { const tokens = await signIn({ clientId: 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com', scopes: ['email', 'profile'] }); console.log('Sign-in successful:', tokens); } catch (error) { console.error('Sign in failed:', error); } } ``` ### Sign Out Logs the user out of their Google session. ```typescript import { signOut} from '@choochmeque/tauri-plugin-google-auth-api'; async function handleSignOut() { try { await signOut(); console.log('User signed out'); } catch (error) { console.error('Sign out failed:', error); } } ``` ### Refresh Token Refreshes the access token, useful for maintaining user sessions. ```typescript import {refreshToken} from '@choochmeque/tauri-plugin-google-auth-api'; async function handleRefreshToken() { try { const tokens = await refreshToken({ clientId: 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com', scopes: ['email', 'profile'] }); console.log('Refreshed tokens:', tokens); } catch (error) { console.error('Token refresh failed:', error); } } ``` ``` -------------------------------- ### Install tauri-plugin-google-auth Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/iOS_SETUP.md Add the google-auth plugin to your Tauri project's dependencies using Cargo. ```bash # In your Tauri project root cargo add tauri-plugin-google-auth ``` -------------------------------- ### Native Flow Sign In and Refresh Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/ANDROID_SETUP.md Example usage of the signIn and refreshToken functions for the native authentication flow. Requires a Web Client ID and specified scopes. ```typescript const tokens = await signIn({ clientId: 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com', scopes: ['email', 'profile'] }); // Refresh (silent) const newTokens = await refreshToken({ clientId: 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com', scopes: ['email', 'profile'] }); ``` -------------------------------- ### Native Sign-In: Get Access Token Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/platform-specifics.md After obtaining an ID token, this step initiates the process to get an access token and granted scopes using the AuthorizationClient. This is part of the native Google Sign-In flow. ```kotlin val authorizationClient = Identity.getAuthorizationClient(activity) val tokenResponse = authorizationClient.getAccessToken(GetAccessTokenOption.Builder().setServerClientId(clientId).setAccessTokenRequestOptions(AccessTokenRequestOptions.Builder().setScopes(scopes).build()).build()) val accessToken = tokenResponse.accessToken val grantedScopes = tokenResponse.grantedScopes ``` -------------------------------- ### Sign-Out with Token Revocation Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/api-reference/sign-out.md This example demonstrates signing out a user and revoking their access token with Google. The token will become invalid after revocation. Local state is cleared regardless of revocation success. ```typescript async function logoutAndRevokeToken(accessToken) { try { // Sign out and revoke the token with Google // The user cannot use this token again after revocation await signOut({ accessToken: accessToken }) console.log('User signed out and token revoked') sessionStorage.clear() } catch (error) { console.error('Sign-out or revocation failed:', error) // Note: Local state is cleared regardless of revocation success/failure } } ``` -------------------------------- ### Platform-Specific Error Handling for Desktop Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/errors.md Handle authentication flows that require platform-specific configurations, such as including a client secret for desktop applications. This example demonstrates checking the platform and conditionally adding the secret. ```typescript import { signIn } from '@choochmeque/tauri-plugin-google-auth-api' import { platform } from '@tauri-apps/plugin-os' async function authenticateUser() { try { const plat = await platform() const options = { clientId: 'YOUR_CLIENT_ID', scopes: ['openid', 'email', 'profile'] } // Add platform-specific requirements if (plat === 'windows' || plat === 'macos' || plat === 'linux') { options.clientSecret = 'YOUR_CLIENT_SECRET' // Required for desktop } const response = await signIn(options) } catch (error) { const message = error instanceof Error ? error.message : String(error) if (message.includes('Client secret')) { console.log('Desktop platform requires client secret') } } } ``` -------------------------------- ### Store Tokens in Desktop OS Keychain Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/configuration.md After a successful sign-in, store the access token, refresh token, and expiration time in the operating system's secure storage. This example uses a hypothetical secure storage API. ```typescript import { secureStorage } from '@tauri-apps/plugin-secure-storage' // After sign-in const response = await signIn({ clientId, scopes }) await secureStorage.set('accessToken', response.accessToken) if (response.refreshToken) { await secureStorage.set('refreshToken', response.refreshToken) } await secureStorage.set('expiresAt', response.expiresAt.toString()) ``` -------------------------------- ### Basic Sign-In (Desktop) Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/api-reference/sign-in.md Demonstrates a basic sign-in flow for desktop applications, requiring client ID, client secret, and scopes. ```APIDOC ## signIn (Desktop Basic) ### Description Initiates the Google authentication flow for desktop applications. Requires client ID, client secret, and specified scopes. ### Method `signIn(options: { clientId: string, clientSecret: string, scopes: string[] }) => Promise` ### Parameters #### Request Body - **clientId** (string) - Required - Your Google OAuth2 client ID. - **clientSecret** (string) - Required - Your Google OAuth2 client secret (required for desktop). - **scopes** (string[]) - Required - An array of OAuth2 scopes to request (e.g., 'openid', 'email', 'profile'). ### Response #### Success Response (`TokenResponse`) - **idToken** (string) - Optional - JWT ID token (present if 'openid' scope was requested). - **accessToken** (string) - Required - OAuth2 access token for API calls. - **scopes** (string[]) - Required - List of scopes actually granted by the user. - **refreshToken** (string) - Optional - Refresh token for obtaining new access tokens. - **expiresAt** (number) - Optional - Unix timestamp in seconds when the access token expires. ### Request Example ```typescript import { signIn } from '@choochmeque/tauri-plugin-google-auth-api' async function authenticateUser() { try { const response = await signIn({ clientId: 'YOUR_CLIENT_ID.apps.googleusercontent.com', clientSecret: 'YOUR_CLIENT_SECRET', // Required for desktop scopes: ['openid', 'email', 'profile'] }) console.log('ID Token:', response.idToken) console.log('Access Token:', response.accessToken) console.log('Expires at:', new Date(response.expiresAt * 1000)) } catch (error) { console.error('Authentication failed:', error) } } ``` ``` -------------------------------- ### Basic Sign-In (Desktop) Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/api-reference/sign-in.md Use this for a standard sign-in flow on desktop applications. Requires `clientSecret`. ```typescript import { signIn } from '@choochmeque/tauri-plugin-google-auth-api' async function authenticateUser() { try { const response = await signIn({ clientId: 'YOUR_CLIENT_ID.apps.googleusercontent.com', clientSecret: 'YOUR_CLIENT_SECRET', // Required for desktop scopes: ['openid', 'email', 'profile'] }) console.log('ID Token:', response.idToken) console.log('Access Token:', response.accessToken) console.log('Expires at:', new Date(response.expiresAt * 1000)) } catch (error) { console.error('Authentication failed:', error) } } ``` -------------------------------- ### Basic Google Sign-In, Sign-Out, and Token Refresh Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/README.md Demonstrates the core functionalities of the plugin: signing in with Google, signing out, and refreshing access tokens. Ensure you replace placeholder client IDs and secrets with your actual credentials. The `clientSecret` is required for desktop platforms. ```typescript import { signIn, signOut, refreshToken } from '@choochmeque/tauri-plugin-google-auth-api'; // Sign in with Google async function authenticateUser() { try { const response = await signIn({ clientId: 'YOUR_GOOGLE_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', // Required for desktop platforms scopes: ['openid', 'email', 'profile'], hostedDomain: 'example.com', // Optional: restrict to specific domain loginHint: 'user@example.com', // Optional: pre-fill email redirectUri: 'http://localhost:8080', // Optional: specify custom redirect URI successHtmlResponse: '

Success!

' // Optional: custom success message (desktop) }) console.log('ID Token:', response.idToken); console.log('Access Token:', response.accessToken); console.log('Refresh Token:', response.refreshToken); console.log('Expires at:', new Date(response.expiresAt * 1000)); } catch (error) { console.error('Authentication failed:', error); } } // Sign out async function logout(accessToken?: string) { try { // With token revocation (recommended) await signOut({ accessToken }); // Or local sign-out only // await signOut(); console.log('Successfully signed out'); } catch (error) { console.error('Sign out failed:', error); } } // Refresh tokens async function refreshUserToken(storedRefreshToken: string) { try { const response = await refreshToken({ refreshToken: storedRefreshToken, clientId: 'YOUR_GOOGLE_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET' // Required for desktop }); console.log('New Access Token:', response.accessToken); } catch (error) { console.error('Token refresh failed:', error); } } ``` -------------------------------- ### Get Localized Error Description Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/platform-specifics.md Retrieves the user-friendly error message from an Error object using its localizedDescription property. This is a standard way to present errors to the user. ```swift error.localizedDescription ``` -------------------------------- ### Advanced Google Sign-In Configuration Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/README.md Illustrates advanced configuration options for the `signIn` function, including requesting additional scopes and specifying domain restrictions. The `clientSecret` is necessary for desktop environments. ```typescript import { signIn } from '@choochmeque/tauri-plugin-google-auth-api'; const response = await signIn({ clientId: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', // Required for desktop scopes: [ 'openid', 'email', 'profile', 'https://www.googleapis.com/auth/drive.readonly' ], hostedDomain: 'company.com', // Restrict to company domain loginHint: 'john.doe@company.com', // Pre-fill the email field redirectUri: 'http://localhost:9000' // Custom port (desktop only) }); ``` -------------------------------- ### Get Release SHA-1 Certificate Fingerprint Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/ANDROID_SETUP.md Retrieve the SHA-1 certificate fingerprint for your release keystore. This is necessary for Google Cloud Console verification for production builds. ```bash keytool -list -v -keystore your-release-key.keystore -alias your-key-alias ``` -------------------------------- ### Info.plist Configuration for Google Sign-In Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/iOS_SETUP.md Add these keys to your Info.plist to configure URL schemes and enable Google Sign-In. ```xml CFBundleURLTypes CFBundleURLSchemes com.googleusercontent.apps.YOUR_REVERSED_CLIENT_ID LSApplicationQueriesSchemes googlechrome safari ``` -------------------------------- ### Store Tokens in Android EncryptedSharedPreferences Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/configuration.md For Android applications, use EncryptedSharedPreferences for secure token storage. This example demonstrates creating an encrypted preferences instance and saving token details. ```kotlin // In native Android code val encryptedSharedPreferences = EncryptedSharedPreferences.create( context, "secret_shared_prefs", MasterKey.Builder(context).setKeyScheme(MasterKey.KeyScheme.AES256_GCM).build(), EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV, EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM ) encryptedSharedPreferences.edit().apply { putString("accessToken", token.accessToken) putString("refreshToken", token.refreshToken) putLong("expiresAt", token.expiresAt) apply() } ``` -------------------------------- ### signIn(options) Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/README.md Initiates the Google OAuth2 authentication flow to sign in a user. Requires configuration options specific to the platform. ```APIDOC ## signIn(options) ### Description Authenticates a user with Google OAuth2. ### Parameters * **options** (SignInOptions) - Required - Configuration options for the sign-in process. ### Platform Specific Configuration #### Desktop (macOS, Windows, Linux) **Required**: `clientId`, `clientSecret`, `scopes` **Optional**: `redirectUri`, `successHtmlResponse`, `hostedDomain`, `loginHint` **Flow**: Binds TCP listener, opens browser, listens for redirect, exchanges code for tokens. #### Android Native (Default) **Required**: `clientId`, `scopes` **Not needed**: `clientSecret`, `redirectUri` **Flow**: Uses Android Credential Manager and AuthorizationClient, platform handles UI. #### Android Web **Required**: `clientId`, `clientSecret`, `scopes`, `flowType: "web"` **Optional**: `redirectUri` **Flow**: Launches WebView, performs OAuth2 flow, exchanges code server-side. #### iOS **Required**: `clientId`, `scopes` **Not needed**: `clientSecret` **Flow**: Uses SimpleGoogleSignIn SDK, presents system UI. ``` -------------------------------- ### JavaScript/TypeScript Google Sign-In Usage Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/iOS_SETUP.md Use the signIn function to initiate the Google Sign-In flow. Provide your client ID and optional parameters like scopes, hostedDomain, and loginHint. ```typescript import { signIn, signOut, refreshToken } from '@choochmeque/tauri-plugin-google-auth-api'; // Sign in async function handleSignIn() { try { const tokens = await signIn({ clientId: 'YOUR_IOS_CLIENT_ID.apps.googleusercontent.com', scopes: ['email', 'profile'], // Optional additional scopes hostedDomain: 'example.com', // Optional: restrict to specific domain loginHint: 'user@example.com' // Optional: pre-fill email }); console.log('Sign-in successful:', tokens); console.log('ID Token:', tokens.idToken); console.log('Access Token:', tokens.accessToken); console.log('Refresh Token:', tokens.refreshToken); console.log('Expires At:', tokens.expiresAt); } catch (error) { console.error('Sign in failed:', error); } } // Sign out async function handleSignOut() { try { await signOut(); console.log('User signed out'); } catch (error) { console.error('Sign out failed:', error); } } // Refresh access token async function refreshUserToken(storedRefreshToken: string) { try { const tokens = await refreshToken({ refreshToken: storedRefreshToken, clientId: 'YOUR_IOS_CLIENT_ID.apps.googleusercontent.com' }); console.log('Refreshed tokens:', tokens); console.log('New Access Token:', tokens.accessToken); } catch (error) { console.error('Token refresh failed:', error); } } ``` -------------------------------- ### Native Sign-In: Get ID Token Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/platform-specifics.md Initiates the native Google Sign-In flow to obtain an ID token using the Credential Manager API. This is the first step in the native authentication process. ```kotlin val credentialManager = CredentialManager.create(activity) val googleIdOption = GetGoogleIdOption.Builder() .setFilterByAuthorizedAccounts(false) .setServerClientId(clientId) .setNonce(nonce) .build() val request = GetCredentialRequest.Builder() .addAccountHintKey(GoogleSignIn.DEFAULT_SIGN_IN) .setGoogleIdOption(googleIdOption) .build() try { val result = credentialManager.getCredential(request, activity) val idToken = result.data.getString("id_token") // ... process idToken } catch (e: Exception) { // ... handle exceptions } ``` -------------------------------- ### Get SHA-1 Certificate Fingerprint (Windows) Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/ANDROID_SETUP.md Use this command to retrieve the SHA-1 certificate fingerprint for your debug keystore on Windows. This is required for Android client ID verification in Google Cloud Console. ```bash # Windows keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android ``` -------------------------------- ### Desktop Sign-In Configuration Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/configuration.md Use this for desktop applications on macOS, Windows, or Linux. Requires clientId, clientSecret, and scopes. The redirectUri is optional and defaults to localhost. ```typescript const response = await signIn({ clientId: '123456-abc123.apps.googleusercontent.com', clientSecret: 'GOCSPX-abc123xyz', scopes: ['openid', 'email', 'profile'], redirectUri: 'http://localhost:8080' // Optional; OS assigns if not specified }) ``` -------------------------------- ### iOS Token Refresh Example Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/api-reference/refresh-token.md Refresh tokens for iOS applications using the SimpleGoogleSignIn library. This method requires the stored refresh token and client ID. The client secret is not needed for iOS. ```typescript // iOS uses the SimpleGoogleSignIn library const response = await refreshToken({ refreshToken: storedRefreshToken, clientId: 'YOUR_CLIENT_ID' // Client secret not needed for iOS }) console.log('New tokens:', response) ``` -------------------------------- ### Sign In with Google Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/README.md Initiates the Google Sign-In flow. Requires your Google OAuth client ID and optionally a client secret for desktop platforms. You can specify scopes, a hosted domain, login hint, and a custom redirect URI. ```APIDOC ## signIn ### Description Initiates the Google Sign-In flow with the specified options. ### Method `signIn` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **clientId** (string) - Required: Google OAuth client ID - **clientSecret** (string) - Optional: Required for desktop platforms and Android web flow - **scopes** (string[]) - Optional: OAuth scopes to request. Defaults to ['openid', 'email', 'profile']. - **hostedDomain** (string) - Optional: Restrict authentication to a specific domain. - **loginHint** (string) - Optional: Email hint to pre-fill in the sign-in form. - **redirectUri** (string) - Optional: Custom redirect URI (desktop: localhost only). - **successHtmlResponse** (string) - Optional: Custom HTML shown after auth (desktop only). - **flowType** (string) - Optional: Android only, default: 'native'. Can be 'native' or 'web'. ### Request Example ```typescript await signIn({ clientId: 'YOUR_GOOGLE_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', // Required for desktop platforms scopes: ['openid', 'email', 'profile'], hostedDomain: 'example.com', // Optional: restrict to specific domain loginHint: 'user@example.com', // Optional: pre-fill email redirectUri: 'http://localhost:8080', // Optional: specify custom redirect URI successHtmlResponse: '

Success!

' // Optional: custom success message (desktop) }); ``` ### Response #### Success Response - **idToken** (string) - JWT ID token (requires 'openid' scope) - **accessToken** (string) - OAuth access token for API calls - **scopes** (string[]) - List of scopes granted with the access token - **refreshToken** (string) - Refresh token (when offline access is granted) - **expiresAt** (number) - Token expiration timestamp (seconds since epoch) #### Response Example ```json { "idToken": "eyJ...", "accessToken": "ya29.a0Af...", "scopes": ["openid", "email", "profile"], "refreshToken": "1//...", "expiresAt": 1678886400 } ``` ``` -------------------------------- ### Initialize Tauri Google Auth Plugin Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/configuration.md Initialize the Google Auth plugin within your Tauri application's Rust code. This sets up the plugin and registers its command handlers. ```rust use tauri_plugin_google_auth; #[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { tauri::Builder::default() .plugin(tauri_plugin_google_auth::init()) .run(tauri::generate_context!()) .expect("error while running tauri application"); } ``` -------------------------------- ### Git Workflow for Contributing Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/README.md Standard Git commands for forking a repository, creating a feature branch, committing changes, and opening a pull request. ```bash git checkout -b feature/amazing-feature git commit -m 'Add some amazing feature' git push origin feature/amazing-feature ``` -------------------------------- ### Get SHA-1 Certificate Fingerprint (macOS/Linux) Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/ANDROID_SETUP.md Use this command to retrieve the SHA-1 certificate fingerprint for your debug keystore on macOS or Linux. This is required for Android client ID verification in Google Cloud Console. ```bash # macOS/Linux keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android ``` -------------------------------- ### JavaScript Error Handling Example Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/errors.md Demonstrates how to catch and handle errors thrown by the plugin's asynchronous functions in JavaScript or TypeScript. All plugin errors are serialized to strings and appear as standard JavaScript Error objects. ```typescript try { await signIn({ clientId: 'test' }) } catch (error) { // error is an Error object with message property console.log(error.message) // e.g., "Authentication failed: ..." console.log(error instanceof Error) // true } ``` -------------------------------- ### signIn() Function Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/MANIFEST.txt Initiates the Google sign-in flow. This function handles the complete authentication process, including user interaction, token exchange, and credential management across different platforms. ```APIDOC ## signIn() ### Description Initiates the Google sign-in flow, managing user interaction and token exchange across various platforms. ### Method Not applicable (SDK function) ### Endpoint Not applicable (SDK function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "signIn()" } ``` ### Response #### Success Response - **TokenResponse** (object) - Contains access and refresh tokens upon successful authentication. #### Response Example ```json { "example": "{\"access_token\": \"...\", \"refresh_token\": \"...\", \"expires_in\": 3600}" } ``` ``` -------------------------------- ### Web Sign-In: Launch Activity Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/platform-specifics.md Launches a custom activity for web-based Google Sign-In using the OAuth2 authorization code flow. This activity typically hosts a WebView for the sign-in process. ```kotlin val intent = Intent(activity, GoogleSignInActivity::class.java) intent.putExtra("clientId", clientId) intent.putExtra("scopes", scopes.toTypedArray()) activity.startActivityForResult(intent, RC_SIGN_IN) ``` -------------------------------- ### Supported Parameters Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/ANDROID_SETUP.md Lists and describes the parameters available for the signIn and refreshToken functions. ```APIDOC ## Supported Parameters - `clientId`: Required - Your **Web Application** client ID - `clientSecret`: Required for web flow only - `scopes`: OAuth scopes to request - `flowType`: `"native"` (default) or `"web"` ``` -------------------------------- ### Usage of GoogleAuthExt in a Tauri Command Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/types.md Demonstrates how to use the GoogleAuthExt trait within a Tauri command to obtain a GoogleAuth instance and perform a sign-in operation. ```rust use tauri::AppHandle; use tauri_plugin_google_auth::GoogleAuthExt; fn my_command(app: AppHandle) -> Result { let google_auth = app.google_auth(); google_auth.sign_in(payload) } ``` -------------------------------- ### iOS Info.plist Configuration for Google Sign-In Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/README.md Required Info.plist entries for iOS to handle Google Sign-In URL schemes. Replace YOUR_REVERSED_CLIENT_ID with your actual reversed client ID. ```xml CFBundleURLTypes CFBundleURLSchemes YOUR_REVERSED_CLIENT_ID ``` -------------------------------- ### Initialize Google Auth Plugin for Tauri Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/platform-specifics.md Provides the C-decorated function required for Tauri to bind and initialize the Google Auth plugin on iOS. This function is the entry point for the plugin. ```swift @_cdecl("init_plugin_google_auth") func initPlugin() -> Plugin { return GoogleSignInPlugin() } ``` -------------------------------- ### Web Flow Sign In and Refresh Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/ANDROID_SETUP.md Demonstrates signing in and refreshing tokens using the web authentication flow. This flow requires a client secret and supports refresh tokens. ```typescript const tokens = await signIn({ clientId: 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com', clientSecret: 'YOUR_WEB_CLIENT_SECRET', scopes: ['email', 'profile'], flowType: 'web' }); // Refresh const newTokens = await refreshToken({ refreshToken: tokens.refreshToken, clientId: 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com', clientSecret: 'YOUR_WEB_CLIENT_SECRET', flowType: 'web' }); ``` -------------------------------- ### Sign-In with Custom Success Message (Desktop) Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/api-reference/sign-in.md Customize the HTML response shown to the user after successful authentication on desktop. ```typescript const response = await signIn({ clientId: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', scopes: ['openid', 'email', 'profile'], successHtmlResponse: `

✓ Authentication Successful

You can safely close this window and return to the application.

` }) ``` -------------------------------- ### Platform Abstraction using Conditional Compilation Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/architecture.md Demonstrates how Rust's conditional compilation (`#[cfg]`) is used to conditionally include platform-specific modules (desktop and mobile) and import their implementations. ```rust #[cfg(desktop)] mod desktop; #[cfg(mobile)] mod mobile; #[cfg(desktop)] use desktop::GoogleAuth; #[cfg(mobile)] use mobile::GoogleAuth; ``` -------------------------------- ### Web Flow Configuration Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/ANDROID_SETUP.md Instructions for setting up and using the web authentication flow, which utilizes OAuth 2.0 authorization code exchange. ```APIDOC ## Web Flow Uses OAuth 2.0 authorization code exchange. ```typescript const tokens = await signIn({ clientId: 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com', clientSecret: 'YOUR_WEB_CLIENT_SECRET', scopes: ['email', 'profile'], flowType: 'web' }); // Refresh const newTokens = await refreshToken({ refreshToken: tokens.refreshToken, clientId: 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com', clientSecret: 'YOUR_WEB_CLIENT_SECRET', flowType: 'web' }); ``` ``` -------------------------------- ### Sign-In with Custom Success Message (Desktop) Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/api-reference/sign-in.md Allows customization of the success message displayed to the user after authentication on desktop. ```APIDOC ## signIn (Desktop Custom Success) ### Description Initiates the Google authentication flow for desktop applications with a custom HTML response displayed upon successful authentication. ### Method `signIn(options: { clientId: string, clientSecret: string, scopes: string[], successHtmlResponse?: string }) => Promise` ### Parameters #### Request Body - **clientId** (string) - Required - Your Google OAuth2 client ID. - **clientSecret** (string) - Required - Your Google OAuth2 client secret (required for desktop). - **scopes** (string[]) - Required - An array of OAuth2 scopes to request. - **successHtmlResponse** (string) - Optional - Custom HTML content to display after successful authentication. ### Request Example ```typescript const response = await signIn({ clientId: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', scopes: ['openid', 'email', 'profile'], successHtmlResponse: `

✓ Authentication Successful

You can safely close this window and return to the application.

` }) ``` ``` -------------------------------- ### Plugin Architecture Module Organization Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/architecture.md Illustrates the directory structure and key files within the tauri-plugin-google-auth project, highlighting the separation of concerns for different platforms and functionalities. ```tree tauri-plugin-google-auth/ ├── src/ │ ├── lib.rs # Plugin initialization, trait exports │ ├── models.rs # Request/response types (Serde) │ ├── error.rs # Error enum definition │ ├── commands.rs # Tauri command handlers │ ├── desktop.rs # Desktop (macOS/Windows/Linux) OAuth2 flow │ └── mobile.rs # Mobile (iOS/Android) bridge to native code ├── guest-js/ │ └── index.ts # TypeScript API exports ├── android/ │ └── src/main/java/ │ ├── GoogleSignInPlugin.kt # Android plugin implementation │ ├── GoogleSignInActivity.kt # Web flow WebView activity │ └── NativeSignInActivity.kt # Native flow activity ├── ios/ │ └── Sources/ │ └── GoogleSignInPlugin.swift # iOS plugin wrapper └── examples/ └── google-auth-demo/ # Demo application ``` -------------------------------- ### Basic Error Handling with Try-Catch Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/errors.md Use a standard try-catch block to gracefully handle any errors that occur during the signIn process. Log the error message for debugging. ```typescript try { const response = await signIn({ clientId: 'YOUR_CLIENT_ID', scopes: ['openid', 'email'] }) } catch (error) { if (error instanceof Error) { console.error('Error message:', error.message) } } ``` -------------------------------- ### ProGuard Rules for Google Sign-In Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/ANDROID_SETUP.md Add these ProGuard/R8 rules to your proguard-rules.pro file for release builds to prevent obfuscation of Google Sign-In related classes and Kotlin Coroutines. ```proguard # Google Sign-In -keep class com.google.android.gms.auth.** { *; } -keep class com.google.android.gms.common.** { *; } # Kotlin Coroutines -keepattributes Signature -keepattributes *Annotation* ``` -------------------------------- ### Google Sign-In Options Interface Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/README.md Defines the structure for options passed to the `signIn` function. Note that `clientSecret` is required for desktop and Android web flows, and `redirectUri` is restricted to localhost on desktop. ```typescript interface SignInOptions { clientId: string; // Required: Google OAuth client ID clientSecret?: string; // Required for desktop, Android web flow scopes?: string[]; // OAuth scopes to request hostedDomain?: string; // Restrict authentication to a specific domain loginHint?: string; // Email hint to pre-fill in the sign-in form redirectUri?: string; // Custom redirect URI (desktop: localhost only) successHtmlResponse?: string; // Custom HTML shown after auth (desktop only) flowType?: 'native' | 'web'; // Android only, default: 'native'. See ANDROID_SETUP.md } ``` -------------------------------- ### Initialize Credential Manager and Authorization Client Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/platform-specifics.md Initializes the AuthorizationClient for web flows and CredentialManager for native flows. These are essential for interacting with Google's authentication services on Android. ```kotlin authorizationClient = Identity.getAuthorizationClient(activity) credentialManager = CredentialManager.create(activity) ``` -------------------------------- ### iOS Sign-In Configuration Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/configuration.md Configure for iOS applications. Requires clientId and scopes. clientSecret is not needed as it's handled by the native SDK. Ensure URL schemes are configured in Info.plist. ```typescript const response = await signIn({ clientId: 'YOUR_CLIENT_ID.apps.googleusercontent.com', scopes: ['openid', 'email', 'profile'] }) ``` -------------------------------- ### Build Tauri iOS App Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/iOS_SETUP.md Build your Tauri application for iOS using the provided npm script. ```bash npm run tauri ios build ``` -------------------------------- ### Rust API Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/README.md These are the core Rust functions and traits for initializing and extending the plugin within your Tauri application. ```APIDOC ## Rust API ### Description Provides Rust functions and traits for integrating Google authentication into your Tauri application. ### Initialization - `fn init() -> TauriPlugin` - Description: Initializes the Google Auth plugin for your Tauri application. - Parameters: - `R` (Runtime) - The Tauri runtime generic type. - Returns: `TauriPlugin` - The initialized Tauri plugin. ### Trait - `trait GoogleAuthExt` - Description: Extends the Tauri runtime with Google Auth capabilities. - Methods: - (Details of methods within the trait are not provided in the source, but it's an extension point for the plugin.) ### Types - `TokenResponse` - Description: Represents the structure of the token response. - `SignInRequest` - Description: Represents the request payload for the sign-in command. - `SignOutRequest` - Description: Represents the request payload for the sign-out command. - `RefreshTokenRequest` - Description: Represents the request payload for the refresh token command. - `FlowType` - Description: Enum representing different OAuth2 flow types (e.g., desktop, mobile). - `Error` - Description: Enum defining possible errors that can occur within the plugin. - `Result` - Description: A type alias for `Result`, representing the success or failure of an operation. ``` -------------------------------- ### Native Sign-In: Authorization Request Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/platform-specifics.md Constructs and initiates an authorization request to obtain an access token and scopes using the AuthorizationClient. This is a key step in the native Google Sign-In flow. ```kotlin val authorizationClient = Identity.getAuthorizationClient(activity) val request = AuthorizationRequest.Builder() .setRequestedScopes(scopes) .build() authorizationClient.authorize(request) ``` -------------------------------- ### Register Plugin in Tauri App (Rust) Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/README.md Register the google-auth plugin in your Tauri app's main Rust file (lib.rs). Ensure the plugin is initialized before running the Tauri application. ```rust use tauri_plugin_google_auth; #[cfg_attr(mobile, tauri::mobile_entry_point)] pub fn run() { tauri::Builder::default() .plugin(tauri_plugin_google_auth::init()) .run(tauri::generate_context!()) .expect("error while running tauri application"); } ``` -------------------------------- ### Error Handling Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/api-reference/sign-in.md Provides guidance on how to handle potential errors during the sign-in process. ```APIDOC ## Error Handling ### Description This section outlines common errors that can occur during the sign-in process and provides examples of how to catch and handle them. ### Throws/Rejects - **`UserCancelled`**: User cancelled the authentication flow. - **`ConfigurationError`**: Invalid configuration (missing client ID, empty scopes, invalid redirect URI, missing client secret on desktop, or invalid endpoints). - **`AuthenticationFailed`**: OAuth2 authorization or token exchange failed. - **`NetworkError`**: Network-related errors. - **`InvalidClientId`**: Client ID is invalid or not recognized by Google. - **`NoUserSignedIn`**: Attempted operation requires a signed-in user. ### Error Handling Example ```typescript try { const response = await signIn({ clientId: 'YOUR_CLIENT_ID', scopes: ['openid', 'email'] }) } catch (error) { if (error instanceof Error) { if (error.message.includes('cancelled')) { console.log('User cancelled authentication') } else if (error.message.includes('Client secret')) { console.log('Client secret is required for this platform') } else if (error.message.includes('Configuration error')) { console.log('Invalid configuration:', error.message) } else { console.log('Authentication error:', error.message) } } } ``` ``` -------------------------------- ### Native Flow Configuration Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/ANDROID_SETUP.md Details on configuring and using the native authentication flow, which leverages Android's Credential Manager and AuthorizationClient. ```APIDOC ## Native Flow (default) Uses [Credential Manager](https://developer.android.com/identity/sign-in/credential-manager-siwg) and [AuthorizationClient](https://developer.android.com/identity/authorization). **Required Client IDs:** - **Web Client ID** - passed as `clientId` parameter, used as [ID token audience](https://developer.android.com/identity/sign-in/credential-manager-siwg#set-google) - **Android Client ID** - configured in [Google Cloud Console](https://console.cloud.google.com/apis/credentials) with your package name and SHA-1, matched automatically by the SDK ```typescript const tokens = await signIn({ clientId: 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com', scopes: ['email', 'profile'] }); // Refresh (silent) const newTokens = await refreshToken({ clientId: 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com', scopes: ['email', 'profile'] }); ``` ``` -------------------------------- ### Implementing Retry Logic with Exponential Backoff Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/errors.md Implement a robust sign-in function that automatically retries on transient errors using exponential backoff. Avoid retrying on user-initiated cancellations or configuration issues. ```typescript async function signInWithRetry(options, maxRetries = 3) { for (let attempt = 1; attempt <= maxRetries; attempt++) { try { return await signIn(options) } catch (error) { const message = error instanceof Error ? error.message : String(error) // Don't retry on user cancellation or configuration errors if (message.includes('cancelled') || message.includes('Configuration error')) { throw error } if (attempt === maxRetries) { throw error } // Exponential backoff: 1s, 2s, 4s const delay = Math.pow(2, attempt - 1) * 1000 await new Promise(resolve => setTimeout(resolve, delay)) } } } ``` -------------------------------- ### Android Web Flow Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/api-reference/sign-in.md Use the web sign-in flow for Android, which requires `clientSecret` and a `redirectUri`. ```typescript const response = await signIn({ clientId: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', // Required for web flow scopes: ['openid', 'email', 'profile'], flowType: 'web', redirectUri: 'https://your-redirect-domain.com/callback' }) ``` -------------------------------- ### iOS URL Scheme Configuration Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/configuration.md Add these URL schemes to your app's Info.plist file to handle authentication callbacks for iOS. ```xml CFBundleURLTypes CFBundleURLSchemes YOUR_REVERSED_CLIENT_ID ``` -------------------------------- ### Add Tauri Plugin Google Auth Dependency (Rust) Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/README.md Add the plugin to your Cargo.toml file to include it in your Rust project. ```toml [dependencies] tauri-plugin-google-auth = "0.5" ``` -------------------------------- ### Handle Google OAuth URL Callback Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/platform-specifics.md Delegates URL handling for deep-link callbacks from the Google OAuth flow to the SimpleGoogleSignIn library. Ensure your Info.plist is configured with the correct URL schemes. ```swift return SimpleGoogleSignIn.shared.handleURL(url) ``` -------------------------------- ### iOS URL Handling in AppDelegate Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/_autodocs/configuration.md Implement this method in your app delegate to handle incoming URLs from the Google authentication process on iOS. ```swift // SwiftUI/AppDelegate func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { SimpleGoogleSignIn.shared.handleURL(url) return true } ``` -------------------------------- ### Sign Out Options Interface Source: https://github.com/choochmeque/tauri-plugin-google-auth/blob/main/README.md Defines the optional parameters for the `signOut` function. Providing an `accessToken` will revoke the token with Google; otherwise, only a local sign-out occurs. ```typescript interface SignOutOptions { accessToken?: string; // Token to revoke (if not provided, local sign-out only) flowType?: 'native' | 'web'; // Android only, default: 'native' } ```