如果我使用Firebase简单用户名和密码身份验证,如何返回用户列表

不知道如果我做错了,但使用这个api https://www.firebase.com/docs/security/simple-login-email-password.html我可以成功地创建一个用户 – 根据返回的消息,但我无法在Forge控制台的任何位置看到该用户。 你怎么知道用户注册?

我是否应该使用返回的用户ID并在Firebase中创建自己的用户对象,或者不需要重复此操作。 我确实需要添加一些额外的用户属性,所以我需要这样做,无论如何。

在Firebase身份验证(以前称为Firebase SimpleLogin)中使用电子邮件/密码身份验证时,用户的电子邮件和密码组合将与实际存储在Firebase中的数据分开安全地存储。

Firebase中的数据与用户的电子邮件/密码哈希组合之间的这种障碍是设计的:我们希望使您更容易(1)开发应用程序,(2)防止任何意外的用户证书泄漏,以及(3 )仍然可以让您充分灵活地将您的用户数据存储在Firebase中。

这意味着我们只存储电子邮件地址/密码哈希组合,因此您可以决定如何将实际用户数据存储在您的Firebase中。 正如您所建议的那样,您应该获取用户标识并将这些数据存储在您的Firebase中的某个位置(如/ users / $ id)中,并使用Firebase 安全规则语言确定对该数据的读/写访问权限。 您的用户唯一的idemail已经在编写规则时使用的auth变量中。

在这里,我创建了一个Android程序来做Rob为Firebase初学者(像我)在那里所说的。这个程序首先存储signedUp或signedIn用户的用户名,然后将它们显示在listView

SignInActivity.java

 public class SignInActivity extends BaseActivity implements View.OnClickListener,View.OnKeyListener{ private DatabaseReference mDatabase; public static FirebaseAuth mAuth; private static final String TAG = "MainActivity"; EditText usernameField; EditText passwordField; TextView changeSignUpModeTextView; Button signUpButton; ImageView logo; RelativeLayout relativeLayout; Boolean signUpModeActive; static ArrayList<String> userList = new ArrayList<>(); @Override public void onStart() { super.onStart(); // Check auth on Activity start if (mAuth.getCurrentUser() != null) { onAuthSuccess(mAuth.getCurrentUser()); } } @Override public boolean onKey(View view, int i, KeyEvent keyEvent) { if(i == keyEvent.KEYCODE_ENTER && keyEvent.getAction() == keyEvent.ACTION_DOWN){ signUpOrLogIn(view); } return false; } @Override public void onClick(View view) { if(view.getId() == R.id.changeSignUpMode){ if (signUpModeActive == true){ signUpModeActive = false; changeSignUpModeTextView.setText("Sign Up"); signUpButton.setText("Log In"); }else{ signUpModeActive = true; changeSignUpModeTextView.setText("Log In"); signUpButton.setText("Sign Up"); } }else if(view.getId() == R.id.logo || view.getId() == R.id.relativeLayout){ InputMethodManager inm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); inm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),0); } } public void signUpOrLogIn(View view) { showProgressDialog(); String email = usernameField.getText().toString().trim(); String password = passwordField.getText().toString().trim(); if (signUpModeActive == true) { mAuth.createUserWithEmailAndPassword(email,password) .addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { hideProgressDialog(); Toast.makeText(MainActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show(); // If sign in fails, display a message to the user. If sign in succeeds // the auth state listener will be notified and logic to handle the // signed in user can be handled in the listener. if (!task.isSuccessful()) { Toast.makeText(MainActivity.this, "Authentication failed." + task.getException().toString().substring(task.getException().toString().indexOf(" ")), Toast.LENGTH_SHORT).show(); Log.i("Error", task.getException().toString()); } else { onAuthSuccess(task.getResult().getUser()); showUserList(); } } }); } else { mAuth.signInWithEmailAndPassword(email,password) .addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { hideProgressDialog(); // If sign in fails, display a message to the user. If sign in succeeds // the auth state listener will be notified and logic to handle the // signed in user can be handled in the listener. if (!task.isSuccessful()) { // there was an error Toast.makeText(MainActivity.this, task.getException().toString(), Toast.LENGTH_LONG).show(); } else { onAuthSuccess(task.getResult().getUser()); showUserList(); } } }); } } public void showUserList(){ startActivity(new Intent(getApplicationContext(), UserList.class)); finish(); } private void onAuthSuccess(FirebaseUser user) { String username = usernameFromEmail(user.getEmail()); // Write new user writeNewUser(user.getUid(), username, user.getEmail()); // Go to MainActivity } private String usernameFromEmail(String email) { if (email.contains("@")) { return email.split("@")[0]; } else { return email; } } private void writeNewUser(String userId, String name, String email) { User user = new User(name, email); mDatabase.child("users").child(userId).setValue(user); ArrayList<String> userNames = new ArrayList<>(); userNames.add(name); mDatabase.child("usernamelist").setValue(userNames); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mAuth = FirebaseAuth.getInstance(); mDatabase = FirebaseDatabase.getInstance().getReference(); if(mAuth.getCurrentUser()!=null){ showUserList(); } usernameField = (EditText) findViewById(R.id.username); passwordField = (EditText) findViewById(R.id.password); changeSignUpModeTextView = (TextView) findViewById(R.id.changeSignUpMode); signUpButton = (Button) findViewById(R.id.signupbutton); logo = (ImageView)findViewById(R.id.logo); relativeLayout= (RelativeLayout)findViewById(R.id.relativeLayout); signUpModeActive = true; changeSignUpModeTextView.setOnClickListener(this); usernameField.setOnKeyListener(this); passwordField.setOnKeyListener(this); logo.setOnClickListener(this); relativeLayout.setOnClickListener(this); } } 

UserList.java

 public class UserList extends AppCompatActivity { private static final String TAG = "UserList" ; private DatabaseReference userlistReference; private ValueEventListener mUserListListener; ArrayList<String> usernamelist = new ArrayList<>(); ArrayAdapter arrayAdapter;; ListView userListView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_user_list); userlistReference = FirebaseDatabase.getInstance().getReference().child("usernamelist"); onStart(); userListView = (ListView) findViewById(R.id.userlistview); } @Override protected void onStart() { super.onStart(); final ValueEventListener userListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { usernamelist = new ArrayList<>((ArrayList) dataSnapshot.getValue()); usernamelist.remove(usernameOfCurrentUser()); Log.i(TAG, "onDataChange: "+usernamelist.toString()); arrayAdapter = new ArrayAdapter(UserList.this,android.R.layout.simple_list_item_1,usernamelist); userListView.setAdapter(arrayAdapter); } @Override public void onCancelled(DatabaseError databaseError) { Log.w(TAG, "onCancelled: ",databaseError.toException()); Toast.makeText(UserList.this, "Failed to load User list.", Toast.LENGTH_SHORT).show(); } }; userlistReference.addValueEventListener(userListener); mUserListListener = userListener; } public String usernameOfCurrentUser() { String email = MainActivity.mAuth.getCurrentUser().getEmail(); if (email.contains("@")) { return email.split("@")[0]; } else { return email; } } @Override public void onStop() { super.onStop(); // Remove post value event listener if (mUserListListener != null) { userlistReference.removeEventListener(mUserListListener); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.action_logout: FirebaseAuth.getInstance().signOut(); startActivity(new Intent(this, MainActivity.class)); finish(); return true; default: return super.onOptionsItemSelected(item); } } 

}

您可以使用Google Identity Toolkit API获取Firebase项目中所有已注册用户的列表,该API由Firebase CLI使用 ,可以通过运行Firebase firebase auth:export results-file来访问该API firebase auth:export results-file

确保Identity Toolkit API已启用

火力用户-list.js

 const serviceAccount = require('path/to/firebase-sdk-json-service-account'); const googleapis = require('googleapis'); const identitytoolkit = googleapis.identitytoolkit('v3'); const authClient = new googleapis.auth.JWT( serviceAccount.client_email, null, serviceAccount.private_key, ['https://www.googleapis.com/auth/firebase'], null ); authClient.authorize((err) => { if (err) { return console.error(err); } let nextPageToken = undefined; let users = []; const getAccounts = () => identitytoolkit.relyingparty.downloadAccount({ auth: authClient, resource: { targetProjectId: serviceAccount.project_id, maxResults: 200, nextPageToken: nextPageToken } }, (e, results) => { if (e) { return console.error(err); } users = users.concat(results.users); if (results.nextPageToken) { nextPageToken = results.nextPageToken; return getAccounts(); } else { console.log(users); } }); getAccounts(); }); 
Interesting Posts