Skip to content

Google Authentication via Firebase

namnh-0652 edited this page Apr 3, 2023 · 9 revisions

Features

Installation

Prerequisites

Add library

From project build.gradle (or settings.gradle), add Jitpack maven

repositories {
    maven { url 'https://jitpack.io' }
}

Add these dependencies to your app/build.gradle

dependencies {
    implementation "com.github.sun-asterisk.tech-standard-android-auth:core:${latest_version}"
    implementation "com.github.sun-asterisk.tech-standard-android-auth:googlefirebaseauth:${latest_version}"
}

Usage

SignIn Google with Firebase Authentication

Setup your GoogleConfig

From Application class, call initGoogleAuth method

private fun setupGoogleFirebaseAuth() {
    initGoogleAuth(
        webClientId = getString(R.string.google_web_client_id),
    ) {
        enableOneTapSignIn = false
        enableFilterByAuthorizedAccounts = false // work only when enableOneTapSignIn is true
        // ... other configs
    }
}

Initialize activity/fragment with callbacks you want to get result.

fun initGoogleSignIn(activity: FragmentActivity) {
    GoogleFirebaseAuth.initialize(
        activity,
        signInCallback = object : SignInCallback<AuthResult> {
            override fun onResult(data: AuthResult?, error: Throwable?) {
                _signInState.value = SocialAuthResult(data = data, error = error)
            }
        },
    )
}

Important Note:

  • Because this client is designed follow LifecycleObserver, so call initialize method before Activity or Fragment falls in STARTED state.

Call signIn method

fun onClick(view: View) {
   GoogleFirebaseAuth.signIn()
}

Sequence diagram

sequenceDiagram
    autonumber
    participant Application
    participant GoogleFirebaseAuth
    note over GoogleFirebaseAuth: GoogleFirebaseAuth Module
    participant Google
    participant Firebase
    Application->>GoogleFirebaseAuth: check isSignedIn()
    GoogleFirebaseAuth->>Firebase: check SignIn status
    Firebase->>GoogleFirebaseAuth: response status
    alt is Signed In
        rect rgb(0, 0, 255, .1)
            break when is SignedIn
                GoogleFirebaseAuth-->>Application: 
            end
        end
    else is Not Signed In
        GoogleFirebaseAuth-->>Application: 
    end
    Application->>GoogleFirebaseAuth: send signIn() request
    GoogleFirebaseAuth-->>Application: launch SignIn UI
    Application->>Application: Input Account
    Application->>Google: request SignIn
    alt signIn process fails
        rect rgb(0, 0, 255, .1)
            break
                Google-->>GoogleFirebaseAuth: return error
                GoogleFirebaseAuth-->>Application: Callback error
            end
        end
    else signIn Success
        Google-->>GoogleFirebaseAuth: return SignIn Credentials
    end
    GoogleFirebaseAuth->>Firebase: request signIn Firebase with Google Credentials
    Firebase->>Firebase: Handle Request
    alt signIn process fails
        rect rgb(0, 0, 255, .1)
            break
                Firebase-->>GoogleFirebaseAuth: return error
                GoogleFirebaseAuth-->>Application: Callback error
            end
        end
    else signIn Success
        Firebase-->>GoogleFirebaseAuth: return AuthResult
        GoogleFirebaseAuth-->>Application: Callback AuthResult
    end
Loading

Check signed in status

To verify the current signed in status

fun isSignedIn(): Boolean {
    return GoogleFirebaseAuth.isSignedIn()
}

Gets signed in FirebaseUser

fun getUser(): FirebaseUser? {
    return GoogleFirebaseAuth.getUser()
}

SignOut current user

fun signOut() {
   GoogleFirebaseAuth.signOut(object : SignOutCallback {
       override fun onResult(error: Throwable?) {
           _signOutState.value = error
       }
   })
}

Gets Firebase Multiple Auth Providers UserInfo

You can allow users to sign in to your app using multiple authentication providers by linking auth provider credentials to an existing user account. Users are identifiable by the same Firebase user ID regardless of the authentication provider they used to sign in. For example, a user who signed in with a password can link a Google account and sign in with either method in the future. Or, an anonymous user can link a Facebook account and then, later, sign in with Facebook to continue using your app.

To get the UserInfo of linked account

fun getUserInfo(): UserInfo? {
    return GoogleFirebaseAuth.getLinkedAccounts(PROVIDER_GOOGLE)
}

Check and show OneTap UI

This module also supports OneTap Sign-in UI

Enable OneTap sign-in in config

initGoogleAuth(...) {
    enableOneTapSignIn = true
    enableFilterByAuthorizedAccounts = true
}

Check condition and call when needed

if (!viewModel.isSignedIn()) {
    GoogleFirebaseAuth.showOneTapSignIn()
}

Notes

  • If a user cancels several OneTap UI prompts in a row, the One Tap client will not prompt the user for the next 24 hours.
  • In development mode, you can reset the cooldown by clearing Google Play services' app storage.

Sequence diagram

sequenceDiagram
    autonumber
    participant Application
    participant GoogleFirebaseAuth
    note over GoogleFirebaseAuth: GoogleFirebaseAuth Module
    participant Google
    participant Firebase
    Application->>Application: onCreate
    Application-->>GoogleFirebaseAuth: lifecycle callback
    GoogleFirebaseAuth->>Firebase: check SignIn status
    Firebase->>GoogleFirebaseAuth: response status
    alt is Signed In
        rect rgb(0, 0, 255, .1)
            break when is SignedIn
                GoogleFirebaseAuth-->>Application: 
            end
        end
    else is Not Signed In
        GoogleFirebaseAuth-->>Application: launch OneTap UI
    end
    Application->>Application: Choose Account
    Application->>Google: request SignIn
    Google->>Google: Handle Request
    alt signIn process fails
        rect rgb(0, 0, 255, .1)
            break
                Google-->>GoogleFirebaseAuth: return error
                GoogleFirebaseAuth-->>Application: Callback error
            end
        end
    else signIn Success
        Google-->>GoogleFirebaseAuth: return SignIn Credentials
    end
    GoogleFirebaseAuth->>Firebase: request signIn Firebase with Google Credentials
    Firebase->>Firebase: Handle Request
    alt signIn process fails
        rect rgb(0, 0, 255, .1)
            break
                Firebase-->>GoogleFirebaseAuth: return error
                GoogleFirebaseAuth-->>Application: Callback error
            end
        end
    else signIn Success
        Firebase-->>GoogleFirebaseAuth: return AuthResult
        GoogleFirebaseAuth-->>Application: Callback AuthResult
    end
Loading

Documentation

Method / field Purpose
webClientId : String The web client id from Google Cloud console
enableOneTapSignIn: Boolean Config OneTap Sign-in, default true
enableFilterByAuthorizedAccounts: Boolean Config filter by authorized accounts, default true
enableLinkAccounts: Boolean Config link multiple Auth Providers, default false
Method Purpose
fun signIn(): Unit Start SignIn process
fun isSignedIn(): Boolean Check current SignIn status
fun signOut(): Unit SignOut current user
fun getUser(): FirebaseUser? Gets current user
fun getLinkedAccounts(provider: String): UserInfo? Gets Firebase Multiple Auth Providers UserInfo
fun showOneTapSignIn(): Unit Show OneTap SignIn UI