簡體   English   中英

Android Java - 如何僅當用戶手機號碼已在 Firebase 實時數據庫中時生成和驗證 OTP

[英]Android Java - How do I generate and verify OTP only when user mobile number is already in Firebase Realtime Database

我正在制作一個項目,只有當用戶數據已經在 Firebase 實時數據庫中時才應該登錄,不需要注冊新用戶,我只需要與預先存在的用戶一起工作。 無論用戶手機號碼是否已經存在,我當前的代碼都會生成並驗證 OTP。 那么我該如何修改以達到我的目的呢?

這是我的代碼:

package com.lalbhaibrokers.lalbhaibrokerspvtltd;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.TaskExecutors;
import com.google.android.material.textfield.TextInputEditText;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthProvider;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.concurrent.TimeUnit;

public class LoginActivity extends AppCompatActivity {

    //Variables
    TextInputEditText mobileNumber, otp;
    TextView forgotPassword, errorMessage, sendOtp, verifyOtpAndLogin;
    Context context = this;
    String verificationCode;
    boolean isVerified;
    FirebaseDatabase database;
    DatabaseReference reference;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        //Hooks
        mobileNumber = (TextInputEditText) findViewById(R.id.mobile_no_editText);
        otp = (TextInputEditText) findViewById(R.id.otp_editText);
        errorMessage = (TextView) findViewById(R.id.error_message_textView);
        sendOtp = (TextView) findViewById(R.id.send_otp_btn);
        verifyOtpAndLogin = (TextView) findViewById(R.id.verify_otp_and_login);

        verifyOtpAndLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String userCode = otp.getText().toString();
                if (!userCode.isEmpty()) {
                    verifyCode(userCode); //verifying the code Entered by user
                }
            }
        });
    }

    //method for start the OTP process
    public void sendOtp(View view){
        if(mobileNumber.getText().toString().equals("")){
            errorMessage.setText("Please Enter phone number");
            errorMessage.setVisibility(View.VISIBLE);
        }else if(mobileNumber.getText().toString().length() != 10){
            errorMessage.setText("PhoneNumber is Invalid"); //we can only accept phoneNumbers with 10 digits
            errorMessage.setVisibility(View.VISIBLE);
        }else{
            String phoneNum= "+91"+mobileNumber.getText().toString(); //we have to add country code in order to receive OTP

            //method that will send the OTP to given number
            PhoneAuthProvider.getInstance().verifyPhoneNumber( //sending message
                    phoneNum,        // Phone number to verify
                    60,                 // Timeout duration
                    TimeUnit.SECONDS,   // Unit of timeout
                    TaskExecutors.MAIN_THREAD,    // Activity (for callback binding)
                    mCallbacks);        // OnVerificationStateChangedCallbacks
            Toast.makeText(context, "OTP send to"+phoneNum, Toast.LENGTH_SHORT).show();
            verifyOtpAndLogin.setVisibility(View.VISIBLE);
        }
    }

    //method that verify the OTP received or not
    private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
        @Override
        public void onCodeSent(@NonNull String s, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
            super.onCodeSent(s, forceResendingToken);
            verificationCode = s;   //verification code that should be received by phoneNumber
        }

        @Override
        public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {
            String code = phoneAuthCredential.getSmsCode(); //verification code that actually received by phoneNumber
            if (code != null) {
                verifyCode(code);
            }
        }

        @Override
        public void onVerificationFailed(@NonNull FirebaseException e) {
            Toast.makeText(context, "Verification Failed: OTP not received", Toast.LENGTH_SHORT).show();
        }
    };

    //verifying the OTP
    public void verifyCode(String code) {
        PhoneAuthCredential credential = PhoneAuthProvider.getCredential(verificationCode, code); //comparing both verification code
        signin(credential);
    }

    //signing in the User to update in database
    private void signin(PhoneAuthCredential credential) {
        FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
        firebaseAuth.signInWithCredential(credential).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    Toast.makeText(context, "Verification Complete", Toast.LENGTH_SHORT).show();
                    isVerified=true;
                    Intent intent = new Intent(context, UserDashboard.class);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(context, "Verification Faild: OTP wrong", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

設置一個方法來驗證已驗證用戶的 UID 是否已存在於您的數據庫中

                if (task.isSuccessful()) {
                //verify UID here
                    Toast.makeText(context, "Verification Complete", Toast.LENGTH_SHORT).show();
                    isVerified=true;
                    Intent intent = new Intent(context, UserDashboard.class);
                    startActivity(intent);
                    finish();
                } else {
                    Toast.makeText(context, "Verification Faild: OTP wrong", Toast.LENGTH_SHORT).show();
                }
            }
        });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM