2015-08-08 101 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.')); 
} 
相關問題