本文介绍了如果用户未先单击Firebase身份验证发送的验证链接,如何防止用户登录android应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在制作一个android聊天应用程序.它以一个StartActivity页面打开,该页面通向Login或Register页面.我正在使用Firebase身份验证系统,即如果用户输入他的详细信息,然后单击RegisterActivity中的注册按钮,则他的详细信息将被推送到Firebase数据库,验证链接将发送到他的电子邮件,然后他将被移动到LoginPage.现在,需要他单击验证链接,对他的帐户进行验证,然后在LoginPage中输入他的详细信息,然后单击登录按钮.

I am making an android chat application. It opens up with a StartActivity page that leads to either of the Login or Register pages. I am using Firebase authentication system, i.e. if the user enter his details and then clicks on register button in the RegisterActivity, his details are pushed to the Firebase database, a verification link is sent to his email and he is moved to the LoginPage. Now, he is required to click on the verification link, get his account verified, and then enter his details in the LoginPage and click on login button.

  • 如果用户单击了验证链接,然后单击登录"按钮:一切都按预期进行.用户将移动到HomeActivity.如果他关闭该应用程序然后重新启动它,则将执行以下代码,并且超过了StartActivity.
@Override
    protected void onStart() {
        super.onStart();

        firebaseUser = FirebaseAuth.getInstance().getCurrentUser();

        //redirect if user is not null
        if (firebaseUser != null) {
            startActivity(new Intent(StartActivity.this, HomeActivity.class));
            finish();
        }
    }

  • 如果用户未点击验证链接:这就是一切出错的地方.如果他没有得到验证,但仍然单击登录"按钮,则显示未验证".显示Toast并且他没有登录(很好).但是,如果他关闭了该应用程序然后重新启动它,则超过了StartActivity并直接转到HomeActivity,而没有得到验证,这就是我想修复的问题.我尝试在StartActivity的onStart()代码中进行一些更改,但随后该应用程序打开并突然关闭,并显示NullPointer错误.
  • @Override
        protected void onStart() {
            super.onStart();
    
            firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    
            //redirect if user is not null
            if (Objects.requireNonNull(auth.getCurrentUser()).isEmailVerified()) {
                if (firebaseUser != null) {
                    startActivity(new Intent(StartActivity.this, HomeActivity.class));
                    finish();
                }
            } else {
                startActivity(new Intent(StartActivity.this, LoginActivity.class));
                Toast.makeText(this, "Verify your email id!", Toast.LENGTH_SHORT).show();
            }
        }
    

    这是我得到的错误.

    java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.auth.FirebaseUser com.google.firebase.auth.FirebaseAuth.getCurrentUser()' on a null object reference
            at com.smproductions.flingg.StartActivity.onStart(StartActivity.java:31)
            at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1425)
            at android.app.Activity.performStart(Activity.java:7825)
            at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3294)
            at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
            at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
            at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
            at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
            at android.os.Handler.dispatchMessage(Handler.java:107)
            at android.os.Looper.loop(Looper.java:214)
            at android.app.ActivityThread.main(ActivityThread.java:7356)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
    
    

    我还将附加StartActivity,RegisterActivity和LoginActivity代码以供参考.

    I am also attaching the StartActivity, RegisterActivity and LoginActivity codes for reference.

    StartActivity

    StartActivity

    public class StartActivity extends AppCompatActivity {
    
        MaterialButton goToLogin, goToRegister;
        ImageView banner;
    
        FirebaseUser firebaseUser;
        FirebaseAuth auth;
    
        @Override
        protected void onStart() {
            super.onStart();
    
            firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    
            //redirect if user is not null
            if (Objects.requireNonNull(auth.getCurrentUser()).isEmailVerified()) {
                if (firebaseUser != null) {
                    startActivity(new Intent(StartActivity.this, HomeActivity.class));
                    finish();
                }
            } else {
                startActivity(new Intent(StartActivity.this, LoginActivity.class));
                Toast.makeText(this, "Verify your email id!", Toast.LENGTH_SHORT).show();
            }
        }
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_start);
    
            goToLogin = findViewById(R.id.login);
            goToRegister = findViewById(R.id.register);
            banner = findViewById(R.id.start_banner);
    
            goToLogin.setOnClickListener(v -> {
                Intent intent = new Intent(StartActivity.this, LoginActivity.class);
                startActivity(intent);
            });
            goToRegister.setOnClickListener(v -> {
                Intent intent = new Intent(StartActivity.this, RegisterActivity.class);
                startActivity(intent);
            });
        }
    }
    

    RegisterActivity

    RegisterActivity

    public class RegisterActivity extends AppCompatActivity {
    
        TextInputEditText email, name, username, password;
        MaterialButton btnRegister;
        TextView txtBackToLogin;
    
        FirebaseAuth auth;
        DatabaseReference reference;
    
        ProgressDialog progressDialog;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_register);
    
            email = findViewById(R.id.register_email);
            name = findViewById(R.id.register_name);
            username = findViewById(R.id.register_username);
            password = findViewById(R.id.register_password);
            btnRegister = findViewById(R.id.register_btnRegister);
            txtBackToLogin = findViewById(R.id.register_txtBackToLogin);
    
            auth = FirebaseAuth.getInstance();
    
            txtBackToLogin.setOnClickListener(v -> {
                startActivity(new Intent(RegisterActivity.this, LoginActivity.class));
                finish();
            });
    
            btnRegister.setOnClickListener(v -> {
                String str_username = Objects.requireNonNull(username.getText()).toString();
                String str_name = Objects.requireNonNull(name.getText()).toString();
                String str_email = Objects.requireNonNull(email.getText()).toString();
                String str_password = Objects.requireNonNull(password.getText()).toString();
    
                if (TextUtils.isEmpty(str_email)) {
                    email.setError("Empty");
                    email.requestFocus();
                } else if (TextUtils.isEmpty(str_name)) {
                    name.setError("Empty");
                    name.requestFocus();
                } else if (str_name.contains("@") || str_name.contains("$") || str_name.contains("#") || str_name.contains("*") || str_name.contains("&")) {
                    name.setError("Invalid Characters present");
                    name.requestFocus();
                } else if (TextUtils.isEmpty(str_username)) {
                    username.setError("Empty");
                    username.requestFocus();
                } else if (str_username.contains("@") || str_username.contains("$") || str_username.contains("#") || str_username.contains("*") || str_username.contains("&") || str_username.contains(" ")) {
                    username.setError("Invalid Characters present");
                    username.requestFocus();
                } else if (TextUtils.isEmpty(str_password)) {
                    password.setError("Empty");
                    password.requestFocus();
                } else if (str_password.contains(" ")) {
                    password.setError("Password cannot contain space");
                    password.requestFocus();
                } else if (str_password.length() < 8) {
                    password.setError("Minimum 8 characters required");
                    password.requestFocus();
                } else {
                    progressDialog = new ProgressDialog(RegisterActivity.this);
                    progressDialog.setTitle("REGISTERING");
                    progressDialog.setMessage("Your new account is being created, please wait...");
                    progressDialog.setCanceledOnTouchOutside(false);
                    progressDialog.show();
    
                    userRegistration(str_email, str_name, str_username, str_password);
                }
            });
        }
    
        private void userRegistration(String email, String name, String username, String password) {
            auth.createUserWithEmailAndPassword(email, password)
                    .addOnCompleteListener(task -> {
                        if (task.isSuccessful()) {
                            Objects.requireNonNull(auth.getCurrentUser()).sendEmailVerification().addOnCompleteListener(task12 -> {
                                if (task12.isSuccessful()) {
                                    FirebaseUser firebaseUser = auth.getCurrentUser();
                                    assert firebaseUser != null;
                                    String userID = firebaseUser.getUid();
    
                                    reference = FirebaseDatabase.getInstance().getReference("Users").child(userID);
    
                                    HashMap<String, String> hashMap = new HashMap<>();
                                    hashMap.put("id", userID);
                                    hashMap.put("name", name);
                                    hashMap.put("username", username.toLowerCase());
                                    hashMap.put("search", name.trim().toLowerCase());
                                    hashMap.put("imageURL", "default");
    
                                    reference.setValue(hashMap).addOnCompleteListener(task1 -> {
                                        if (task1.isSuccessful()) {
                                            progressDialog.dismiss();
                                            Toast.makeText(RegisterActivity.this, "Verification link has been sent to your email!", Toast.LENGTH_SHORT).show();
                                            Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
                                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                            startActivity(intent);
                                            finish();
                                        } else {
                                            progressDialog.dismiss();
                                            FirebaseAuthException e = (FirebaseAuthException) task12.getException();
                                            assert e != null;
                                            Toast.makeText(RegisterActivity.this, "REGISTRATION FAILED: "+e.getMessage(), Toast.LENGTH_SHORT).show();
                                        }
                                    });
                                } else {
                                    progressDialog.dismiss();
                                    FirebaseAuthException f = (FirebaseAuthException) task12.getException();
                                    assert f != null;
                                    Toast.makeText(RegisterActivity.this, "REGISTRATION FAILED: "+f.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                            });
                        } else {
                            progressDialog.dismiss();
                            FirebaseAuthException g = (FirebaseAuthException)task.getException();
                            assert g != null;
                            Toast.makeText(RegisterActivity.this, "REGISTRATION FAILED: "+g.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
        }
    }
    

    LoginActivity

    LoginActivity

    public class LoginActivity extends AppCompatActivity {
    
        TextInputEditText email, password;
        MaterialButton btnLogin;
        TextView txtBackToRegister, txtForgotPassword;
    
        FirebaseAuth auth;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);
    
            email = findViewById(R.id.login_email);
            password = findViewById(R.id.login_password);
            btnLogin = findViewById(R.id.login_btnLogin);
            txtBackToRegister = findViewById(R.id.login_txtBackToRegister);
            txtForgotPassword = findViewById(R.id.login_txtForgotPassword);
    
            auth = FirebaseAuth.getInstance();
    
            txtBackToRegister.setOnClickListener(v -> {
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
                finish();
            });
    
            txtForgotPassword.setOnClickListener(v -> startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class)));
    
            btnLogin.setOnClickListener(v -> {
                String str_email = Objects.requireNonNull(email.getText()).toString();
                String str_password = Objects.requireNonNull(password.getText()).toString();
    
                if (TextUtils.isEmpty(str_email)) {
                    email.setError("Empty");
                    email.requestFocus();
                } else if (TextUtils.isEmpty(str_password)) {
                    password.setError("Empty");
                    password.requestFocus();
                } else if (str_password.contains(" ")) {
                    password.setError("Password cannot contain space");
                    password.requestFocus();
                } else if (str_password.length() < 8) {
                    password.setError("Minimum 8 characters required");
                    password.requestFocus();
                } else {
                    ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this);
                    progressDialog.setTitle("LOGGING IN");
                    progressDialog.setMessage("Just a flingg...");
                    progressDialog.setCanceledOnTouchOutside(false);
                    progressDialog.show();
    
                    auth.signInWithEmailAndPassword(str_email, str_password)
                            .addOnCompleteListener(task -> {
                                if (task.isSuccessful()) {
                                    if (Objects.requireNonNull(auth.getCurrentUser()).isEmailVerified()) {
                                        DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Users")
                                                .child(Objects.requireNonNull(auth.getCurrentUser()).getUid());
    
                                        reference.addValueEventListener(new ValueEventListener() {
                                            @Override
                                            public void onDataChange(@NonNull DataSnapshot snapshot) {
                                                progressDialog.dismiss();
                                                Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                                                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                                startActivity(intent);
                                                finish();
                                            }
    
                                            @Override
                                            public void onCancelled(@NonNull DatabaseError error) {
                                                progressDialog.dismiss();
                                            }
                                        });
                                    } else {
                                        progressDialog.dismiss();
                                        auth.signOut();
                                        Toast.makeText(this, "Verify your email first!", Toast.LENGTH_SHORT).show();
                                    }
                                } else {
                                    progressDialog.dismiss();
                                    FirebaseAuthException e = (FirebaseAuthException)task.getException();
                                    assert e != null;
                                    Toast.makeText(LoginActivity.this, "AUTHENTICATION FAILED: "+e.getMessage(), Toast.LENGTH_SHORT).show();
                                }
                            });
                }
            });
        }
    }
    

    我应该对代码进行哪些更改,以便用户无法先验证电子邮件就无法登录?

    WHAT CHANGES SHOULD I MAKE IN THE CODE, SO THAT THERE IS NO WAY THE USER CAN GET LOGGED IN WITHOUT GETTING HIS EMAIL VERIFIED FIRST?

    (这是我第一次对StackOverflow进行提问.我真的很希望得到一个答案:)

    (This is my first time questioning on StackOverflow. I am really hoping for an answer:)

    推荐答案

    NullPointerException 是由以下代码引起的:

    The NullPointerException is caused by this code:

    public class StartActivity extends AppCompatActivity {
    
        MaterialButton goToLogin, goToRegister;
        ImageView banner;
    
        FirebaseUser firebaseUser;
        FirebaseAuth auth;
    
        @Override
        protected void onStart() {
            super.onStart();
    
            firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    
            //redirect if user is not null
            if (Objects.requireNonNull(auth.getCurrentUser()).isEmailVerified()) {
    

    在调用 auth.getCurrentUser()之前,您永远不会初始化 auth ,这就是为什么您得到 NullPointerException 的原因.简单的解决方法是初始化 auth :

    You never initialize auth before the call to auth.getCurrentUser(), which is why you get a NullPointerException. The simple fix is to initialize auth:

    protected void onStart() {
        super.onStart();
    
        auth = FirebaseAuth.getInstance();
    
        firebaseUser = auth.getCurrentUser();
    
        //redirect if user is not null
        if (Objects.requireNonNull(auth.getCurrentUser()).isEmailVerified()) {
            ...
    

    但我也强烈建议您阅读什么是NullPointerException,以及如何解决?,因为这种类型的错误非常普遍,可以按照此处概述的方法轻松解决.

    But I also highly recommend reading What is a NullPointerException, and how do I fix it?, as this type of error is quite common and an easily be fixed by following the approach outlined there.

    这篇关于如果用户未先单击Firebase身份验证发送的验证链接,如何防止用户登录android应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    1403页,肝出来的..

09-06 15:46