Meteor 在客户端和服务器上的 createUser 运行

Meteor's createUser running on client and server

我对 Meteor 还很陌生,并试图掌握它的概念。我在下面有一个客户端代码可以触发 Meteor 方法来创建新用户:

Template["signup-team"].onRendered(function(){
    var validator = $('.signup-team-form').validate({
        submitHandler: function(event){
            var email = $('[name=email]').val();
            var password = $('[name=password]').val();
            Meteor.call('addNewUser', email, password, "team-captain", function(error, result) {
                if (error){
                    return alert(error.reason);
                }
                Router.go("complete-signup");
            });
        }
    });
});

该方法在客户端和服务器上都定义为 运行。当 运行 在服务器上时,我希望它创建用户并将角色添加到帐户。在客户端,我想登录用户。

Meteor.methods({
    addNewUser: function(email, password, role) {
        check(email, String);
        check(password, String);

        if(Meteor.isClient){
            Accounts.createUser({
                email: email,
                password: password,
                profile: {
                    completed: false
                }
            }, function(error){
                if(error){
                    console.log(error); // Output error if registration fails
                } else {
                    console.log(Meteor.userId());
                }
            });
        } else {
            var id = Accounts.createUser({
                email: email,
                password: password,
                profile: {
                    completed: false
                }
            });
            console.log(id);
            Roles.addUsersToRoles(id, role);            
        }
    }
});

服务器部分 运行 正常,新用户已创建,但在客户端出现错误 Error: No result from call to createUser 并且用户未自动登录。

我认为问题是我不需要在客户端上 运行 createUser 而是使用 Meteor.loginWithPassword 但我真的很想知道这背后的理论。谢谢

不要这样做。您正在重写核心代码并产生不必要的安全问题。

不使用您的 addNewUser 方法,只需调用 Accounts.createUser on the client. Have a onCreateUser 回调句柄添加角色。

在您的代码中,您将用户密码以明文形式发送到服务器。当您在发送到服务器之前调用 Accounts.createUser, the password is hashed 时。它还负责为您登录新用户。

虽然添加角色有一个问题,但您将无法在 onCreateUser 回调中使用 Roles.addUsersToRoles(id, role),因为用户对象尚未添加到数据库中,并且不有一个_id。但是,您可以像这样直接将角色添加到建议的用户对象:

Accounts.onCreateUser(function(options, user) {
  user.roles = ['team-captain']  
  return user;
})

话说回来,也许你不希望所有用户都是队长!