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

时间:2015-11-05 10:13:33

标签: javascript meteor meteor-accounts

我对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,但我真的想知道这背后的理论。感谢

1 个答案:

答案 0 :(得分:1)

不要这样做。您正在重写核心代码并不必要地创建安全问题。

不要使用addNewUser方法,只需在客户端上调用Accounts.createUser即可。添加角色的onCreateUser回调句柄。

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

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

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

然后,也许你不希望所有用户成为队长!

相关问题