Created
March 25, 2021 15:06
-
-
Save siddhantkushwaha/01447a9df313ac5923a10c6dd55d39d5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.siddhantkushwaha.falcon.common | |
import android.app.Activity | |
import android.util.Log | |
import com.google.android.gms.auth.api.signin.GoogleSignIn | |
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.GoogleAuthProvider | |
import com.siddhantkushwaha.falcon.R | |
import com.siddhantkushwaha.falcon.activity.ActivityBase | |
object FirebaseGoogleAuth { | |
private val tag = javaClass.toString() | |
private fun getGoogleSignInClient(activity: Activity): GoogleSignInClient { | |
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) | |
.requestIdToken(activity.getString(R.string.default_web_client_id)).requestEmail() | |
.build() | |
return GoogleSignIn.getClient(activity, gso) | |
} | |
private fun signIn(activity: Activity, idToken: String, callback: (Boolean) -> Unit) { | |
val credential = GoogleAuthProvider.getCredential(idToken, null) | |
val fireBaseAuth = FirebaseAuth.getInstance() | |
fireBaseAuth.signInWithCredential(credential).addOnCompleteListener(activity) { task -> | |
if (task.isSuccessful) { | |
callback(true) | |
} else { | |
Log.w(tag, "Sign in failed.", task.exception) | |
callback(false) | |
} | |
} | |
} | |
public fun getEmail(): String? { | |
val fireBaseAuth = FirebaseAuth.getInstance() | |
return fireBaseAuth.currentUser?.email | |
} | |
public fun startLogin(activity: ActivityBase, callback: (Boolean) -> Unit) { | |
val signInIntent = getGoogleSignInClient(activity).signInIntent | |
activity.startActivityForResult(signInIntent, RequestCodes.REQUEST_CODE_SIGN_IN) { data -> | |
val task = GoogleSignIn.getSignedInAccountFromIntent(data) | |
try { | |
val account = task.getResult(ApiException::class.java)!! | |
val token = account.idToken!! | |
signIn(activity, token, callback) | |
} catch (e: ApiException) { | |
Log.e(tag, "Firebase log in failed.", e) | |
callback(false) | |
} | |
} | |
} | |
public fun signOut() { | |
val fireBaseAuth = FirebaseAuth.getInstance() | |
fireBaseAuth.signOut() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment