2015-08-08 131 views
0

因此我有一个接受用户名和密码的登录表单。当输入用户名/密码并单击提交时,第一步是检查帐户是否存在并已启用。我已经完成了使用下面的代码。问题是,客户端可以通过浏览器控制台访问服务器端的方法,检查is_user_enabled。通常我可以做防止这种情况:防止客户端调用服务器端方法

my_method : function(doc) { 
    if (is_admin()) { 
     // Only admins can run this method. 
    } 
} 

但在is_user_enabled的情况下,用户没有登录。所以,我的问题是,处理这种情况的正确方法是什么?

我的代码:

客户端/ login.html的

{{#autoForm schema=get_login_form_schema id="login_form"}} 
    {{> flashMessages}} 
    <fieldset> 
     <!-- <legend>Create User</legend> --> 
     {{> afQuickField name="username" placeholder="schemaLabel" label=false}} 
     {{> afQuickField name="password" placeholder="schemaLabel" type="password" label=false}} 
     <div> 
      <button type="submit" class="btn btn-primary">Login</button> 
     </div> 
    </fieldset> 
{{/autoForm}} 

客户端/ lib目录/ helpers.js

AutoForm.hooks({ 
    login_form: { 
     onSubmit: function (insert_doc, update_doc, current_doc) { 
      Meteor.call("is_user_enabled", insert_doc, function(error, result) { 
       if (result) { 
        // Try to log user in via Meteor.loginWithPassword() 
       } 
      }); 
     } 
    } 
}); 

服务器/ lib目录/ methods.js

Meteor.methods({ 
    is_user_enabled : function(doc) { 
     // Used by the login form. Returns true if user exists and account is enabled. 
     check(doc, schemas.login); 
     var user = Meteor.users.findOne({username: doc.username}, {fields: {status: 1}}); 
     if (user.status === "enabled") { 
      return true; 
     } 
    } 
}); 

最终解决方案

客户端/ lib目录/ helpers.js

AutoForm.hooks({ 
    login_form: { 
     onSubmit: function (insert_doc, update_doc, current_doc) { 
      Meteor.loginWithPassword(insert_doc.username, insert_doc.password, function(error) { 
       // Called with no arguments on success 
       // or with a single Error argument on failure. 
       if (error) { 
        FlashMessages.sendError(error); 
        this.done(); 
       } else { 
        // Successful login. Redirect to /. 
        this.done(); 
        Router.go('/'); 
       } 
      }); 
      return false; // Prevent browser submit event. 
     }, 
    } 

服务器/ lib目录/ permissions.js

Accounts.validateLoginAttempt(function (info) { 
    if (info.user && info.user.status === "enabled") { 
     return true; 
    } else { 
     throw new Meteor.Error("Invalid credentials."); 
    } 
}); 

更多信息有关[Accounts.validateLoginAttempt][1]

回答

0

是的你可以阻止从客户端执行流星方法。这个连接只会在客户端调用它时在一个方法中设置。从服务器调用时,它将为空。你可以这样做:

serverOnlyMethod: function() { 
    if(this.connection) throw(new Meteor.Error(403, 'Forbidden.')); 
} 
相关问题