如果我使用Firebase简单用户名&amp ;;如何返回用户列表?密码验证

时间:2013-02-03 14:49:03

标签: firebase firebase-authentication

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

我应该在Firebase中获取返回的用户ID并创建我自己的用户对象,还是不需要复制。我确实需要添加一些额外的用户属性,因此无论如何我都需要这样做。

7 个答案:

答案 0 :(得分:69)

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

Firebase中的数据与用户的电子邮件/密码哈希组合之间的这种障碍是设计的:我们希望让您更轻松地(1)开发您的应用程序,(2)防止任何意外的用户凭据泄露, (3)仍然让您完全灵活地了解如何在Firebase中存储用户数据。

这意味着我们只存储电子邮件地址/密码哈希组合而不存储任何其他内容,因此您可以决定如何在Firebase中存储实际用户数据。根据您的建议,您应该获取用户ID并将该数据存储在Firebase中的位置(例如/ users / $ id),并使用Firebase Security Rules Language来确定对该数据的读/写访问权限。您的用户的唯一idemail已经在您编写规则时使用的auth变量中。

答案 1 :(得分:10)

在这里我创建了一个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);
    }
}

}

答案 2 :(得分:4)

您可以使用Google Identity Toolkit API获取Firebase项目中所有注册用户的列表,Firebase CLI使用此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();
});

答案 3 :(得分:1)

您可以使用admin.auth().listUsers

这是文档:https://firebase.google.com/docs/reference/admin/node/admin.auth.Auth.html#listusers

还有一个用法示例:https://firebase.google.com/docs/auth/admin/manage-users#list_all_users

function listAllUsers(nextPageToken) {
  // List batch of users, 1000 at a time.
  admin.auth().listUsers(1000, nextPageToken)
    .then(function(listUsersResult) {
      listUsersResult.users.forEach(function(userRecord) {
        console.log('user', userRecord.toJSON());
      });
      if (listUsersResult.pageToken) {
        // List next batch of users.
        listAllUsers(listUsersResult.pageToken);
      }
    })
    .catch(function(error) {
      console.log('Error listing users:', error);
    });
}
// Start listing users from the beginning, 1000 at a time.
listAllUsers();

答案 4 :(得分:0)

Python中的用户列表:

from firebase_admin import credentials, db, auth
cred = credentials.Certificate('\path\to\serviceAccountKey.json')
default_app = firebase_admin.initialize_app(cred, {
    "databaseURL": "https://data_base_url.firebaseio.com"
})
users = auth.list_users()

答案 5 :(得分:0)

可以使用云功能来获取用户列表(查看firebase上的文档)。注意,在下面的示例中,custom claims功能用于检查用户是否具有足够的特权。

// USERS: return full users list for admin
// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
import * as admin from 'firebase-admin'
import * as functions from 'firebase-functions'

export const listUsers = functions.https.onCall((data, context) => {
  // check if user is admin (true "admin" custom claim), return error if not
  const isAdmin = context.auth.token.admin === true
  if (!isAdmin) {
    return { error: `Unauthorized.` }
  }

  return admin
    .auth()
    .listUsers()
    .then((listUsersResult) => {
      // go through users array, and deconstruct user objects down to required fields
      const result = listUsersResult.users.map((user) => {
        const { uid, email, photoURL, displayName, disabled } = user
        return { uid, email, photoURL, displayName, disabled }
      })

      return { result }
    })
    .catch((error) => {
      return { error: 'Error listing users' }
    })
})

答案 6 :(得分:0)

我会尽可能简单地回答 只需使用以下代码将注册用户添加到您的数据库中

您还可以使用共享偏好设置将数据保存到本地,但其他用户将无法使用。

一旦您将用户列表保存在数据库中,只需使用适配器从那里检索它即可

FirebaseDatabase.getInstance().getReference().child("my_user")
                        .child(task.getResult().getUser().getUid())
                        .child("username").setValue(autoCompleteTextView1.getText().toString());