[英]How get firebase auth uid if I'm using facebook for authentication?
[英]How do I save user session using SharedPreferences in Cloud Firestore when I'm not using Firebase authentication?
當用戶在我的Android應用程序中注冊時,他們的數據存儲在一個集合中,其中文檔ID是幫助查找用戶的電子郵件地址。 密碼也存儲在文檔中。
因此,當用戶登錄時,將根據與該電子郵件匹配的文檔ID來檢查他們輸入的電子郵件,如果存在,它將登錄並顯示用戶控制面板。
現在,登錄后,我需要以某種方式創建用戶會話,以便用戶在注銷之前永遠無法返回登錄屏幕。 萬一應用程序崩潰或網絡連接丟失,保存的用戶會話將非常有用。
這是我用於登錄活動的代碼:
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);
}
}
為了獲得最佳實踐,請添加以下課程
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
PrefUtilities.with(this).setUserLogin(false);
您還可以在PrefUtilities
類中添加其他方法來保存用戶電子郵件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.