firebase google sign in result code is always 0 - android

I wanted to integrate google sign In in my app using firebase and I followed all the instructions from enabling google sign In in my firebase console and adding SHA-1 certificate fingerprint and adding the google-services.json file in the app directory.
But whenever I am trying to sign In after selecting the google account the response code is coming out be 0 always and hence unable to sign In.
Here is the Code:-
class SignInActivity : AppCompatActivity() {
private lateinit var googleSignInClient: GoogleSignInClient
private lateinit var auth:FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sign_in)
val gso= GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
googleSignInClient = GoogleSignIn.getClient(this,gso)
signInButton.setOnClickListener {
resultLauncher.launch(googleSignInClient.signInIntent)
}
}
private var resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){result->
Log.i("resultCode",result.resultCode.toString())
val intent=result.data
Log.i("intentData",intent.toString())
if(result.resultCode == Activity.RESULT_OK)
{
Log.i("resultCode","reachedHere")
val task = GoogleSignIn.getSignedInAccountFromIntent(intent)
handleSignInResult(task)
}
else{
Log.i("unsuccessfulSignIN",result.resultCode.toString())
}
}
private fun handleSignInResult(task: Task<GoogleSignInAccount>?) {
try{
val account= task?.getResult(ApiException::class.java)!!
Log.i("account","firebaseAuthWithGoogle:"+account.id)
firebaseAuthWithGoogle(account.idToken!!)
}catch (e : ApiException){
Log.i(ContentValues.TAG, "Google sign in failed", e)
}
}
private fun firebaseAuthWithGoogle(idToken: String) {
signInButton.visibility= View.GONE
progressBar.visibility= View.VISIBLE
val credential= GoogleAuthProvider.getCredential(idToken,null)
GlobalScope.launch(Dispatchers.IO) {
val auth=auth.signInWithCredential(credential).await()
val firebaseUser=auth.user
Log.i("user",firebaseUser.toString())
withContext(Dispatchers.Main){
updateUI(firebaseUser)
}
}
}
private fun updateUI(firebaseUser: FirebaseUser?) {
if(firebaseUser != null)
{
val intent= Intent(this,MainActivity::class.java)
startActivity(intent)
Log.i("intent","Intent Started")
// Toast.makeText(applicationContext,"Sign In Successful",Toast.LENGTH_SHORT).show()
finish()
}
else{
signInButton.visibility= View.VISIBLE
progressBar.visibility=View.GONE
Toast.makeText(this,"Sign In failed", Toast.LENGTH_SHORT).show()
}
}
}
Here is the logcat ( I have highlighted the result code that I logged)
I am very new to android development and this my first time working with firebase

Related

android - Firebase phone authentication recaptch

I'm working on an android app which require Firebase phone authentication, When I released my app, a recapture still required as in debug mode, I enabled Android Device Verification in google cloud console, also I added google play console SHA-256, SHA-1 to Firebase project setting.
Bellow my Kotlin code of Firebase authentication:
fun initFirebase() {
mAuth = FirebaseAuth.getInstance()
}
fun sendOtp(mobile: String, resend: Boolean) {
if (resend) resend(mobile)
else send(mobile)
}
private fun send(mobile: String) {
val options = PhoneAuthOptions.newBuilder(mAuth)
.setPhoneNumber(mobile)
.setTimeout(5L, TimeUnit.SECONDS)
.setActivity(requireActivity())
.setCallbacks(mCallbacks)
.build()
PhoneAuthProvider.verifyPhoneNumber(options)
}
Also at many time I get VerificationFailed without getting reason of this failure
private val mCallbacks = object : PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
override fun onVerificationCompleted(authCredential: PhoneAuthCredential) {}
override fun onVerificationFailed(e: FirebaseException) {
events.value = Constant.EVENT_SEND_FAILED
Log.v("TAG","VerificationFailed")
}
override fun onCodeSent(
verificationId: String,
forceResendingToken: PhoneAuthProvider.ForceResendingToken
) {
Log.v("TAG","Success")
}
and in verification fragment:
private lateinit var mAuth: FirebaseAuth
var mVerificationId: String = ""
fun verifyOtp(otp: String) {
val credential = PhoneAuthProvider.getCredential(
mVerificationId,
otp
)
mAuth.signInWithCredential(credential).addOnCompleteListener(requireActivity()) {
if (it.isSuccessful) {
mAuth.currentUser?.getIdToken(true)?.addOnCompleteListener { task ->
if (task.isSuccessful && task.result != null) {
val phoneVerificationToken = task.result.token
if (phoneVerificationToken != null) {
Log.v("TAG","Success")
}
} else {
Log.v("TAG","Error")
}
}
} else {
Log.v("TAG","Invalid code")
}
}
}

google authentication pop up not working using firebase in android development

while doing a project...i did an authentication with a google account. but it's not working
MainActivity.kt in this activity I have implemented authentication uisng firebase but when i click the button no popup is showing
class MainActivity : AppCompatActivity() {
private lateinit var mAuth: FirebaseAuth
private lateinit var googleSignInClient: GoogleSignInClient
private lateinit var binding: ActivityMainBinding
companion object{
private const val RC_SIGN_IN = 120
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(R.layout.activity_main)
// Configure Google Sign In
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
googleSignInClient = GoogleSignIn.getClient(this, gso)
mAuth = FirebaseAuth.getInstance()
binding.gbutton.setOnClickListener{
signIn()
}
}
private fun signIn() {
val signInIntent = googleSignInClient.signInIntent
startActivityForResult(signInIntent, RC_SIGN_IN)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
val exception = task.exception
if(task.isSuccessful){
try {
// Google Sign In was successful, authenticate with Firebase
val account = task.getResult(ApiException::class.java)!!
Log.d("SignInActivity", "firebaseAuthWithGoogle:" + account.id)
firebaseAuthWithGoogle(account.idToken!!)
} catch (e: ApiException) {
// Google Sign In failed, update UI appropriately
Log.w("SignInActivity", "Google sign in failed", e)
}
}
else{
Log.w("SignInActivity", exception.toString())
}
}
}
private fun firebaseAuthWithGoogle(idToken: String) {
val credential = GoogleAuthProvider.getCredential(idToken, null)
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d("SignInActivity", "signInWithCredential:success")
val intent = Intent(this,ActivityGoogleSigninBinding::class.java)
startActivity(intent)
finish()
} else {
// If sign in fails, display a message to the user.
Log.d("SignInActivity", "signInWithCredential:failure", task.exception)
}
}
}
}
Gradle scripts and buttonID (using binding, XML file in layout) are done correctly
I have also checked logcat but couldn't found any error
Please help

Unable to integrate google sign in properly in android app

I wanted to add the sign in with google feature of firebase I connected my app to firebase then added the SHA-1 certificate fingerprint and wrote the below code.
Once I click on the sign in button the intent opens a chooser to select a google account but after selecting one account nothing happens even there is no exceptions or error in the logcat.
Code:
class SignInActivity : AppCompatActivity() {
private lateinit var googleSignInClient:GoogleSignInClient
private lateinit var auth:FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sign_in)
val gso= GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
googleSignInClient = GoogleSignIn.getClient(this,gso)
signInButton.setOnClickListener {
resultLauncher.launch(googleSignInClient.signInIntent)
}
}
private var resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
val intent=it.data
if(it.resultCode == Activity.RESULT_OK)
{
val task = GoogleSignIn.getSignedInAccountFromIntent(intent)
handleSignInResult(task)
}
}
private fun handleSignInResult(task: Task<GoogleSignInAccount>?) {
try{
val account= task?.getResult(ApiException::class.java)!!
Log.i("account","firebaseAuthWithGoogle:"+account.id)
firebaseAuthWithGoogle(account.idToken!!)
}catch (e : ApiException){
Log.i(TAG, "Google sign in failed", e)
}
}
private fun firebaseAuthWithGoogle(idToken: String) {
signInButton.visibility= View.GONE
progressBar.visibility=View.VISIBLE
val credential=GoogleAuthProvider.getCredential(idToken,null)
GlobalScope.launch(Dispatchers.IO) {
val auth=auth.signInWithCredential(credential).await()
val firebaseUser=auth.user
Log.i("user",firebaseUser.toString())
withContext(Dispatchers.Main){
updateUI(firebaseUser)
}
}
}
private fun updateUI(firebaseUser: FirebaseUser?) {
if(firebaseUser != null)
{
val intent=Intent(this,MainActivity::class.java)
startActivity(intent)
Log.i("intent","Intent Started")
// Toast.makeText(applicationContext,"Sign In Successful",Toast.LENGTH_SHORT).show()
finish()
}
else{
signInButton.visibility= View.VISIBLE
progressBar.visibility=View.GONE
Toast.makeText(this,"Sign In failed",Toast.LENGTH_SHORT).show()
}
}
}
Logcat:
I am very new to android development and this is my first time with firebase.

GetToken failed with status code: ServiceDisabled

I am using Google Sign in to login into a app I am building to display calendars. Post Google Sign in - it also logs into Firebase where the user data is stored in the Realtime Database. While the whole app was working properly - suddenly it stopped syncing with the Google Calendar API and I get the below "Errors" in the Info. I am able to login and with new accounts just no sync - app works - no data. I have tried checking multiple issues and even reverted to old code - no diff. Firebase user data is also being displayed in the app. Can anybody please suggest an approach to solving this issue?
2021-01-04 09:59:21.021 2139-4708/com.google.android.gms.persistent W/Auth: [GetToken] GetToken failed with status code: ServiceDisabled
2021-01-04 09:59:21.022 10175-10254/ W/System.err: com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAuthIOException
2021-01-04 09:59:21.022 10175-10254/ W/System.err: at com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential$RequestHandler.intercept(GoogleAccountCredential.java:286)
2021-01-04 09:59:21.022 10175-10254/ W/System.err: at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:859)
2021-01-04 09:59:21.023 10175-10254/ W/System.err: at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
2021-01-04 09:59:21.023 10175-10254/ W/System.err: at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
2021-01-04 09:59:21.023 10175-10254/ W/System.err: at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
2021-01-04 09:59:21.023 10175-10254/ W/System.err: at .Fragments.Home$syncWholeCalendar$1.invokeSuspend(Home.kt:298)
Below is the code I use to get the user to sign in
private const val TAG = "WelcomeActivity"
class WelcomeActivity : AppCompatActivity() {
var firebaseUser: FirebaseUser? = null
//For Google Sign In
val RC_SIGN_IN: Int = 9001
private lateinit var mGoogleSignInClient: GoogleSignInClient
lateinit var mGoogleSignInOptions: GoogleSignInOptions
private lateinit var firebaseAuth: FirebaseAuth
private var firebaseUserID : String = ""
private lateinit var refUsers : DatabaseReference
//get data from google signin in handlesigninresult
private var googleId = ""
private var googleFirstName = ""
private var googleLastName = ""
private var googleEmail = ""
private var googleProfilePicURL = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_welcome)
// //For google sign in
// configureGoogleSignIn()
// setupUI()
firebaseAuth = FirebaseAuth.getInstance()
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken("896894788293-oe0enptjj2hltdde9isemuf89gtkb7u4.apps.googleusercontent.com")
.requestEmail()
.build()
mGoogleSignInClient = GoogleSignIn.getClient(this, gso)
google_login.setOnClickListener {
signIn()
}
login_welcome.setOnClickListener {
val intent = Intent(this#WelcomeActivity, LoginActivity::class.java)
startActivity(intent)
finish()
}
}
private fun signIn() {
val signInIntent = mGoogleSignInClient.signInIntent
startActivityForResult(signInIntent, RC_SIGN_IN)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == RC_SIGN_IN) {
val task =
GoogleSignIn.getSignedInAccountFromIntent(data)
handleSignInResult(task)
}
}
private fun handleSignInResult(completedTask: Task<GoogleSignInAccount>) {
try {
val account = completedTask.getResult(
ApiException::class.java
)
// Signed in successfully
googleId = account?.id ?: ""
Log.i("Google ID", googleId)
googleFirstName = account?.givenName ?: ""
Log.i("Google First Name", googleFirstName)
googleLastName = account?.familyName ?: ""
Log.i("Google Last Name", googleLastName)
googleEmail = account?.email ?: ""
Log.i("Google Email", googleEmail)
val googleIdToken: String = account?.idToken ?: ""
Log.i("Google ID Token", googleIdToken)
googleProfilePicURL = account?.photoUrl.toString()
Log.i("Google Profile Pic URL", googleProfilePicURL)
firebaseAuthWithGoogle(googleIdToken)
} catch (e: ApiException) {
// Sign in was unsuccessful
Log.e(
"failed code=", e.statusCode.toString()
)
}
}
private fun firebaseAuthWithGoogle(idToken: String) {
val credential = GoogleAuthProvider.getCredential(idToken, null)
firebaseAuth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success")
firebaseUserID = firebaseAuth.currentUser!!.uid
refUsers = FirebaseDatabase.getInstance().reference.child("Users").child(
firebaseUserID
)
refUsers.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(p0: DataSnapshot) {
if (p0.exists()) {
val user: Users? = p0.getValue(Users::class.java)
//Check if user exists in the database
if (user!!.getFirstName() != null) {
val intent = Intent(
this#WelcomeActivity,
IntroSplashScreen::class.java
)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
finish()
} else {
val usersHashMap = HashMap<String, Any>()
usersHashMap["uid"] = firebaseUserID
usersHashMap["firstname"] = googleFirstName
usersHashMap["surname"] = googleLastName
usersHashMap["profile"] = googleProfilePicURL
usersHashMap["primaryEmail"] = googleEmail
usersHashMap["search"] =
googleFirstName.toLowerCase(Locale.ROOT)
refUsers.updateChildren(usersHashMap)
.addOnCompleteListener {
if (task.isSuccessful) {
val intent = Intent(
this#WelcomeActivity,
IntroSplashScreen::class.java
)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
finish()
}
}
}
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.exception)
// ...
}
// ...
}
}
private fun refreshIdToken() {
// Attempt to silently refresh the GoogleSignInAccount. If the GoogleSignInAccount
// already has a valid token this method may complete immediately.
//
// If the user has not previously signed in on this device or the sign-in has expired,
// this asynchronous branch will attempt to sign in the user silently and get a valid
// ID token. Cross-device single sign on will occur in this branch.
mGoogleSignInClient.silentSignIn()
.addOnCompleteListener(
this
) { task -> handleSignInResult(task) }
}
override fun onStart() {
super.onStart()
//Checks if the Google IDToken has expired, if yes it refreshes by SilentSign in and generates new Firebase Token
refreshIdToken()
//Checks if user is logged in to firebase
firebaseUser = FirebaseAuth.getInstance().currentUser
//If logged in then sends to MainActivity
if(firebaseUser!=null){
startActivity(IntroSplashScreen.getLaunchIntent(this))
finish()
}
}
override fun onResume() {
super.onResume()
refreshIdToken()
}
}
Needed to create a Beta Test Program, as anybody who was not associated/listed was blocked from accessing data.

Login with google work from android studio but don't work from google play

I built an app with google login.
When I connect the device to the android studio the log in work perfect, But when I download my app from google play it fails to connect for some reason...
I tried to find a solution and I couldn't find one...
That's the code ... I would love if anyone has any idea what the problem is..
Thanks for your time!
class firstActivity : AppCompatActivity(){
private lateinit var auth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
auth = FirebaseAuth.getInstance()
val acct = GoogleSignIn.getLastSignedInAccount(this)
if (acct != null) {
val personName = acct.displayName
val personGivenName = acct.givenName
val personFamilyName = acct.familyName
val personEmail = acct.email
val personId = acct.id
}
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_idd))
.requestEmail()
.build()
val mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
signinButtonGoogle.setOnClickListener {
val signInIntent: Intent = mGoogleSignInClient.getSignInIntent()
startActivityForResult(signInIntent, Companion.RC_SIGN_IN)
}
}
public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
GoogleSignInApi.getSignInIntent(...);
if (requestCode == Companion.RC_SIGN_IN) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
try {
val account = task.getResult(ApiException::class.java)
firebaseAuthWithGoogle(account!!)
} catch (e: ApiException) {
Toast.makeText(applicationContext, "Google sign in failed", Toast.LENGTH_SHORT)
.show()
}
}
}
private fun firebaseAuthWithGoogle(acct: GoogleSignInAccount) {
val progressDialog = ProgressDialog(this)
progressDialog.setMessage("Connecting...")
progressDialog.setCancelable(false)
progressDialog.show()
val credential = GoogleAuthProvider.getCredential(acct.idToken, null)
auth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
val user = auth.currentUser
signinButtonGoogle.visibility = View.VISIBLE
Handler().postDelayed({ progressDialog.dismiss() }, 0)
val leagueIntent = Intent(this, homeActivity::class.java)
startActivity(leagueIntent)
} else {
Toast.makeText(applicationContext, "Authentication Failed.", Toast.LENGTH_SHORT).show()
signinButtonGoogle.visibility = View.VISIBLE
Handler().postDelayed({ progressDialog.dismiss() }, 0)
}
}
}
companion object {
const val RC_SIGN_IN = 123
}
}
because google play have another SH1 for relase , so you can find it like image and goto firbase manger for your prokect then add new one ,
image

Categories

Resources