Skip to content

Instantly share code, notes, and snippets.

@shank03
Created July 22, 2020 05:07
Show Gist options
  • Save shank03/fb197b2def589283230cc8052ab37c36 to your computer and use it in GitHub Desktop.
Save shank03/fb197b2def589283230cc8052ab37c36 to your computer and use it in GitHub Desktop.
Simplifying the overall implementation when signing in a User using Firebase Authentication
/*
* Copyright (c) 2020, Shashank Verma <shashank.verma2002@gmail.com> [@shank03]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*/
import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.GoogleAuthProvider
/**
* FirebaseAuthHelper
*
* Simplifying the overall implementation when signing in a User
*
* @param activity Used for startingActivity for result and handling result
* @param defaultWebClientId Base implementation requirement
* @param auth [FirebaseAuth] for final sign in
* @param onStart Block to be executed before starting sign in
* @param onSignInComplete Block to be executed when sign in complete
* @param onSignInFailed Block to be executed when sign in failed or cancelled
*
* IMPORTANT ! You have to create instance of this class on OnCreate, else get ready for crashes
*/
class FirebaseAuthHelper(private val activity: AppCompatActivity, defaultWebClientId: String, private val auth: FirebaseAuth,
val onStart: () -> Unit = {},
val onSignInComplete: (account: GoogleSignInAccount, user: FirebaseUser) -> Unit = { _, _ -> },
val onSignInFailed: (err: String?) -> Unit = {}) {
companion object {
// Request Code for auth
private const val RC_SIGN_IN = 111
// Signing out user
@JvmStatic
fun signOutUser(context: Context, defaultWebClientId: String) {
getSignInClient(context, defaultWebClientId).signOut()
}
private fun getSignInClient(context: Context, defaultWebClientId: String): GoogleSignInClient = GoogleSignIn.getClient(context, GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(defaultWebClientId)
.requestEmail()
.build())
}
private val googleSignInClient = getSignInClient(activity, defaultWebClientId)
/**
* Call this when you need to start sign in process
* Such as onClick
*/
fun signIn() {
onStart()
googleSignInClient.signOut()
activity.startActivityForResult(googleSignInClient.signInIntent, RC_SIGN_IN)
}
/**
* This method should be called on [AppCompatActivity.onActivityResult] in your activity, to handle the result
* Otherwise nothing will happen.
*
* @param requestCode It's the requestCode param from [AppCompatActivity.onActivityResult]
* @param data It's the [Intent] param from [AppCompatActivity.onActivityResult]
*/
fun passOnActivityResult(requestCode: Int, data: Intent?) {
if (requestCode == RC_SIGN_IN) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
try {
val account = task.getResult(ApiException::class.java)
if (account != null) {
auth.signInWithCredential(GoogleAuthProvider.getCredential(account.idToken, null)).addOnCompleteListener {
if (task.isSuccessful) {
val user = auth.currentUser
if (user != null) onSignInComplete(account, user)
} else onSignInFailed(task.exception?.message)
}
}
} catch (e: ApiException) {
e.printStackTrace()
onSignInFailed(e.message)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment