如何通过OTP验证对我的实时数据库进行用户验证? [英] How to validate user with respect to my Realtime Database along with OTP verification?

查看:106
本文介绍了如何通过OTP验证对我的实时数据库进行用户验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在Android Studio中创建了一个Android应用,并将其与Firebase Realtime数据库链接.我已使用Firebase的通过电话和通知服务进行身份验证"将OTP发送到CUG电话号码.然后进行验证(代码如下).

I have created an Android app in Android Studio and linked it with Firebase Realtime database. I have used Firebase's Authentication by phone and Notification Services to send OTP to the CUG phone no. and then verify it(The code is given below).

public class PhoneLogin extends AppCompatActivity {

private static final String TAG = "PhoneLogin";
private boolean mVerificationInProgress = false;
private String mVerificationId;
private PhoneAuthProvider.ForceResendingToken mResendToken;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
private FirebaseAuth mAuth;
TextView t1,t2;
ImageView i1;
EditText e1,e2;
Button b1,b2;

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

    e1 = (EditText) findViewById(R.id.Phonenoedittext); //Enter Phone no.
    b1 = (Button) findViewById(R.id.PhoneVerify);       //Send OTP button
    t1 = (TextView)findViewById(R.id.textView2Phone);   //Telling user to enter phone no.
    i1 = (ImageView)findViewById(R.id.imageView2Phone); //Phone icon
    e2 = (EditText) findViewById(R.id.OTPeditText);     //Enter OTP
    b2 = (Button)findViewById(R.id.OTPVERIFY);          //Verify OTP button
    t2 = (TextView)findViewById(R.id.textViewVerified); //Telling user to enter otp
    mAuth = FirebaseAuth.getInstance();
    mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
        @Override
        public void onVerificationCompleted(PhoneAuthCredential credential) {
            // Log.d(TAG, "onVerificationCompleted:" + credential);
            mVerificationInProgress = false;
            Toast.makeText(PhoneLogin.this,"Verification Complete",Toast.LENGTH_SHORT).show();
            signInWithPhoneAuthCredential(credential);
        }

        @Override
        public void onVerificationFailed(FirebaseException e) {
            // Log.w(TAG, "onVerificationFailed", e);
            Toast.makeText(PhoneLogin.this,"Verification Failed",Toast.LENGTH_SHORT).show();
            if (e instanceof FirebaseAuthInvalidCredentialsException) {
                // Invalid request
                Toast.makeText(PhoneLogin.this,"InValid Phone Number",Toast.LENGTH_SHORT).show();
                // ...
            } else if (e instanceof FirebaseTooManyRequestsException) {
            }
        }

        @Override
        public void onCodeSent(String verificationId,
                               PhoneAuthProvider.ForceResendingToken token) {
            // Log.d(TAG, "onCodeSent:" + verificationId);
            Toast.makeText(PhoneLogin.this,"Verification code has been sent",Toast.LENGTH_SHORT).show();
            // Save verification ID and resending token so we can use them later
            mVerificationId = verificationId;
            mResendToken = token;
            e1.setVisibility(View.GONE);
            b1.setVisibility(View.GONE);
            t1.setVisibility(View.GONE);
            i1.setVisibility(View.GONE);
            t2.setVisibility(View.VISIBLE);
            e2.setVisibility(View.VISIBLE);
            b2.setVisibility(View.VISIBLE);
            // ...
        }
    };

    b1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            PhoneAuthProvider.getInstance().verifyPhoneNumber(
                    e1.getText().toString(),
                    60,
                    java.util.concurrent.TimeUnit.SECONDS,
                    PhoneLogin.this,
                    mCallbacks);
        }
    });

    b2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, e2.getText().toString());
            // [END verify_with_code]
            signInWithPhoneAuthCredential(credential);
        }
    });


}

private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        // Log.d(TAG, "signInWithCredential:success");
                        startActivity(new Intent(PhoneLogin.this,NavigationDrawer.class));
                        Toast.makeText(PhoneLogin.this,"Verification Done",Toast.LENGTH_SHORT).show();
                        // ...
                    } else {
                        // Log.w(TAG, "signInWithCredential:failure", task.getException());
                        if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                            // The verification code entered was invalid
                            Toast.makeText(PhoneLogin.this,"Invalid Verification",Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            });
}
}

现在,我想添加另一个验证,以确认输入的CUG号.存在于我的数据库中,则仅应进行OTP身份验证.我的数据库如下所示:

Now I want to add another verification that the entered CUG no. exists in my database and then only the OTP authentication should take place. My database looks like this:

我的数据库

访问该数据库的代码可能是

and the code to access this database could be

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference phoneNumberRef = 
rootRef.child("Employees").child(PhoneNumberenteredByUser);
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
    if(dataSnapshot.exists()) {
        //do something
    } else {
        //do something else
    }
}

@Override
public void onCancelled(DatabaseError databaseError) {}
};
phoneNumberRef.addListenerForSingleValueEvent(eventListener);

此外,当我看到Firebase Realtime数据库的规则时,我注意到不应将其公开,但如果需要将其保持私有状态,则应首先对用户进行身份验证,因此我需要首先对用户进行身份验证通过OTP,然后检查用户CUG号是否正确.我的数据库中存在吗?

Also, when I saw about the rules of Firebase Realtime database I noticed that it shouldn't be left public but if I need to keep it private then the user should be authenticated first, so do I need to first authenticate the user by OTP and then check if the user CUG no. exists in my database?

已验证任何编号的已编辑代码.即使它不在我的数据库中:

Edited code which is authenticating any no. even if it's not in my database:

public class PhoneLogin extends AppCompatActivity {
private static final String TAG = "PhoneLogin";
private boolean mVerificationInProgress = false;
private String mVerificationId;
private PhoneAuthProvider.ForceResendingToken mResendToken;
private PhoneAuthProvider.OnVerificationStateChangedCallbacks mCallbacks;
private FirebaseAuth mAuth;
TextView t1,t2;
ImageView i1;
EditText e1,e2;
Button b1,b2;

//DBA1
private DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
private DatabaseReference phoneNumberRef;
String mobno;
//DBA1 End

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

    e1 = (EditText) findViewById(R.id.Phonenoedittext);
    b1 = (Button) findViewById(R.id.PhoneVerify);
    t1 = (TextView) findViewById(R.id.textView2Phone);
    i1 = (ImageView) findViewById(R.id.imageView2Phone);
    e2 = (EditText) findViewById(R.id.OTPeditText);
    b2 = (Button) findViewById(R.id.OTPVERIFY);
    t2 = (TextView) findViewById(R.id.textViewVerified);

    mobno=e1.getText().toString();

    //DBA2
    phoneNumberRef = rootRef.child("Employees").child(mobno);
    ValueEventListener eventListener = new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                mAuth = FirebaseAuth.getInstance();
                mCallbacks = new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {


                    @Override
                    public void onVerificationCompleted(PhoneAuthCredential credential) {
                        // Log.d(TAG, "onVerificationCompleted:" + credential);
                        mVerificationInProgress = false;
                        Toast.makeText(PhoneLogin.this,"Verification Complete",Toast.LENGTH_SHORT).show();
                        signInWithPhoneAuthCredential(credential);
                    }

                    @Override
                    public void onVerificationFailed(FirebaseException e) {
                        // Log.w(TAG, "onVerificationFailed", e);
                        Toast.makeText(PhoneLogin.this,"Verification Failed",Toast.LENGTH_SHORT).show();
                        if (e instanceof FirebaseAuthInvalidCredentialsException) {
                            // Invalid request
                            Toast.makeText(PhoneLogin.this,"InValid Phone Number",Toast.LENGTH_SHORT).show();
                            // ...
                        } else if (e instanceof FirebaseTooManyRequestsException) {
                        }

                    }

                    @Override
                    public void onCodeSent(String verificationId,
                                           PhoneAuthProvider.ForceResendingToken token) {
                        // Log.d(TAG, "onCodeSent:" + verificationId);
                        Toast.makeText(PhoneLogin.this,"Verification code has been sent",Toast.LENGTH_SHORT).show();
                        // Save verification ID and resending token so we can use them later
                        mVerificationId = verificationId;
                        mResendToken = token;
                        e1.setVisibility(View.GONE);
                        b1.setVisibility(View.GONE);
                        t1.setVisibility(View.GONE);
                        i1.setVisibility(View.GONE);
                        t2.setVisibility(View.VISIBLE);
                        e2.setVisibility(View.VISIBLE);
                        b2.setVisibility(View.VISIBLE);
                        // ...
                    }
                };

                b1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PhoneAuthProvider.getInstance().verifyPhoneNumber(
                                e1.getText().toString(),
                                60,
                                java.util.concurrent.TimeUnit.SECONDS,
                                PhoneLogin.this,
                                mCallbacks);
                    }
                });

                b2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, e2.getText().toString());
                        // [END verify_with_code]
                        signInWithPhoneAuthCredential(credential);
                    }
                });



            } else {
                Toast.makeText(getApplicationContext(),"Incorrect CUG",Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    };
    phoneNumberRef.addListenerForSingleValueEvent(eventListener);
    //DBA2 End


}
private void signInWithPhoneAuthCredential(PhoneAuthCredential credential) {
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        startActivity(new Intent(PhoneLogin.this,NavigationDrawer.class));
                        Toast.makeText(PhoneLogin.this,"Verification Done",Toast.LENGTH_SHORT).show();
                        // Log.d(TAG, "signInWithCredential:success");
                        //startActivity(new Intent(PhoneLogin.this,NavigationDrawer.class));
                        Toast.makeText(PhoneLogin.this,"Verification Done",Toast.LENGTH_SHORT).show();
                        // ...
                    } else {
                        // Log.w(TAG, "signInWithCredential:failure", task.getException());
                        if (task.getException() instanceof FirebaseAuthInvalidCredentialsException) {
                            // The verification code entered was invalid
                            Toast.makeText(PhoneLogin.this,"Invalid Verification",Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            });
}
}

推荐答案

很简单,

编辑您的

b2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, e2.getText().toString());
                    // [END verify_with_code]
                    signInWithPhoneAuthCredential(credential);
                }
            });

具有:

b2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//Write your database reference and check in the database for entered mobno.
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    if(dataSnapshot.child(mobno).exists()){
                        PhoneAuthCredential credential = PhoneAuthProvider.getCredential(mVerificationId, e2.getText().toString());
                    // [END verify_with_code]
                    signInWithPhoneAuthCredential(credential);
                    }
                    else{
                        Toast.makeText(PhoneLogin.this,"No such CUG No. found",Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

这篇关于如何通过OTP验证对我的实时数据库进行用户验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆