当我不使用Firebase身份验证时,如何使用Cloud Firestore中的SharedPreferences保存用户会话? [英] How do I save user session using SharedPreferences in Cloud Firestore when I'm not using Firebase authentication?

查看:117
本文介绍了当我不使用Firebase身份验证时,如何使用Cloud Firestore中的SharedPreferences保存用户会话?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户在我的Android应用程序中注册时,他们的数据存储在一个集合中,其中文档ID是帮助查找用户的电子邮件地址.密码也存储在文档中.

When a user registers in my Android app, their data is stored inside a collection, where the document ID is their email address which helps find a user. The password is stored inside the document as well.

因此,当用户登录时,将根据与该电子邮件匹配的文档ID来检查他们输入的电子邮件,如果存在,它将登录并显示用户控制面板.

So when a user logins, their entered email is checked against a document ID matching that email, if it exists it will log in and display user control panel.

现在登录后,我需要以某种方式创建用户会话,以便用户在注销之前永远无法返回登录屏幕.如果应用程序崩溃或网络连接丢失,保存的用户会话将非常有用.

Now after the login, I need to somehow create a user session, so that the user can never go back to the login screen until he logouts. In case the app crashes or lost network connection, a saved user session would be very useful.

这是我用于登录活动的代码:

Here's my code for the login activity:

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Patterns;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.basgeekball.awesomevalidation.AwesomeValidation;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;

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

import static com.basgeekball.awesomevalidation.ValidationStyle.BASIC;

public class SLogin extends AppCompatActivity
{
public static final String STUDENT_EMAIL = "student_email";
private EditText tEmail;
private EditText tPassword;
private String email = "";

private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference dbUsers;

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

    tEmail= findViewById(R.id.Email);
    tEmail.addTextChangedListener(new TextWatcher()
    {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after)
        {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count)
        {
            email = s.toString();
        }

        @Override
        public void afterTextChanged(Editable s)
        {

        }
    });
    tPassword=findViewById(R.id.Password);

    // Here you simply set saveEmail to empty string because at this moment when activity is
    // created (onCreate) tEmail field is empty. To update this field dynamically you need set
    // addTextChangedListener on tEmail.
    // saveEmail=tEmail.getText().toString();

    dbUsers = db.collection("Students");
}

//Validation Method
private boolean validate()
{
    AwesomeValidation mAwesomeValidation = new AwesomeValidation(BASIC);
    mAwesomeValidation.addValidation(tEmail, Patterns.EMAIL_ADDRESS, "Invalid Email Address");
    String regexPassword = "(?=.*[a-z])(?=.*[A-Z])(?=.*[\\d])(?=.*[~`!@#\\$%\\^&\\*\\(\\)\\-_\\+=\\{\\}\\[\\]\\|\\;:\"<>,./\\?]).{6,}";
    mAwesomeValidation.addValidation(tPassword, regexPassword, "Use 6 or more characters with a mix of upper & lower letters, numbers & symbols");
    return mAwesomeValidation.validate();
}

//Method to check password matching or not
private void passCheck(@NonNull DocumentSnapshot snapshot)
{
    final String uPass = tPassword.getText().toString();
    final String storedPass = snapshot.getString("password");
    if (storedPass != null && storedPass.equals(uPass))
    {
        Intent intent = new Intent(SLogin.this, StudentCP.class);
        intent.putExtra(STUDENT_EMAIL, email);
        startActivity(intent);
    }
    else
    {
        Toast.makeText(SLogin.this, "Invalid Password!", Toast.LENGTH_LONG).show();
    }
}

public void sLogin(View v)
{
    if (validate())
    {
        DocumentReference dbDocs = dbUsers.document(email);
        dbDocs.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>()
        {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task)
            {
                if (task.isSuccessful())
                {
                    DocumentSnapshot document = task.getResult();
                    if (document != null && document.exists())
                    {
                        //Toast.makeText(SLogin.this, "You are registered", Toast.LENGTH_LONG).show();

                        // Improved password checking because at first glance I
                        // don't see why you call db fetch again to get document
                        // because if we are here that means we got matching data
                        // and now we only need to check if password match. No need
                        // to call get on db again.
                        //
                        // It's possible to even more optimize calls to DB in case
                        // of wrongly typed password. We can cache input email and
                        // returned password for that email so in case if user
                        // doesn't change email, but types only password again we
                        // can compare newly typed password with cached password
                        // from previous request so we don't make again new DB
                        // request to simply get again same saved password.
                        //
                        // Currently I haven't implemented caching. It's only idea
                        // to think about in future.
                        passCheck(document);
                    }
                    else
                    {
                        Toast.makeText(SLogin.this, "You are not registered", Toast.LENGTH_LONG).show();
                    }
                }
                else
                {
                    Toast.makeText(SLogin.this, "Unable to connect to database", Toast.LENGTH_LONG).show();
                }
            }
        });
    }
}
public void nUser(View v)
{
    Intent intent = new Intent(SLogin.this, RegisterActivity.class);
    startActivity(intent);
}
}

推荐答案

为获得最佳实践,请添加以下类

For best practice add the following class

public class PrefUtilities {

private SharedPreferences preferences;
Context context;


private PrefUtilities(Context context) {
    preferences = PreferenceManager.getDefaultSharedPreferences(context);
    this.context = context;
}


public static PrefUtilities with(Context context){
    return new PrefUtilities(context);
}


public void setUserLogin(boolean isUserLogedin){

    preferences.edit().putBoolean(context.getString(R.string.pref_key_user_status),isUserLogedin).apply();

}

public boolean isUserLogedin(){
    return preferences.getBoolean(context.getString(R.string.pref_key_user_status),false);
}


}

onCreate方法内检查登录状态

if(PrefUtilities.with(this).isUserLogedin()){

   Intent intent = new Intent(SLogin.this, StudentCP.class);
        intent.putExtra(STUDENT_EMAIL, email);
        startActivity(intent);
}

passCheck方法内保存登录状态

private void passCheck(@NonNull DocumentSnapshot snapshot)
{
    final String uPass = tPassword.getText().toString();
    final String storedPass = snapshot.getString("password");
    if (storedPass != null && storedPass.equals(uPass))
    {

         PrefUtilities.with(this).setUserLogin(true);       

        Intent intent = new Intent(SLogin.this, StudentCP.class);
        intent.putExtra(STUDENT_EMAIL, email);
        startActivity(intent);
    }
    else
    {
        Toast.makeText(SLogin.this, "Invalid Password!", Toast.LENGTH_LONG).show();
    }
}

用户注销时,使用波纹管方法更改SharedPreferences

When user logout use bellow method to change SharedPreferences

PrefUtilities.with(this).setUserLogin(false);

您还可以在PrefUtilities类中添加其他方法来保存用户电子邮件

You can also add other methods in PrefUtilities class saving user Email

这篇关于当我不使用Firebase身份验证时,如何使用Cloud Firestore中的SharedPreferences保存用户会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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