Meteor,跟踪用户登录失败的尝试,并禁止他们在x次尝试后登录

时间:2015-12-13 07:51:11

标签: javascript meteor meteor-accounts

我试图阻止用户在3次尝试失败后登录,因为他们提供了正确的用户名,电子邮件和错误的密码。

Accounts.validateLoginAttempt(function(info){
    var user = info.user;
    var failAttemp = user.profile.loginFaileAttempt;
    if(failAttemp == 3){
        console.log('you need to contact the admin!')
        return false;
    }else{

        if(Meteor.Error == 'Incorrect password '){
            // incremnt the fail attempts
            failAttemp++;
            console.log(failAttemp);
        }
    }

    return true;
    // success login set to 0 
    failAttemp = 0;

});

但它无法正常工作,我做错了什么,是否有任何Meteor方式可以做到这一点?

感谢。

1 个答案:

答案 0 :(得分:3)

代码中的users集合中未更新失败的尝试计数。最后一行failAttemp = 0;将永远不会被执行,因为该函数已经返回。

此外,我看到您可能想要解决的一些问题: Meteor.Error不是检查输入的错误密码的正确方法。它将是未定义的,甚至更多它不会触发,因为密码错误'中有额外的空格。 使用error参数附带的info对象,并使用错误代码而不是消息。

来自未注册用户的登录尝试无论如何都会传递给Accounts.validateLoginAttempt。此类尝试中info.user将为空。除此之外,检查profile字段是否存在是最好的用户对象。

当用户有3次尝试失败并尝试第4次时,他没有被告知出了什么问题。他仍然看到密码错误'并且在服务器的控制台中显示'您需要联系管理员!'。 你可以抛出一个带有更多信息的Meteor.Error。

当用户有3次失败尝试时,他将留在“禁用”状态。州。我的意思是,即使他记得他的密码正确,他也不能再登录了。首先检查是否禁止尝试,然后检查失败的尝试次数。

当用户在尝试失败后输入正确的密码时,失败的尝试次数应该返回0,至少我认为您想要查看您的代码(最后一次无法访问的代码行)

以下是解决方案的示例:

  • 保存失败的尝试。
  • 根据错误代码而不是消息执行检查。
  • 尝试失败后有一条信息性消息。
  • 正确处理未注册的用户。
  • 让用户在尝试失败后登录,如果他们记住了密码。
  • 成功登录后重置失败的尝试次数。

<强>代码:

Accounts.validateLoginAttempt(function(info){
    var user = info.user;
    if (!user)
        return false;

    var failAttempt = 0;
    if (user.profile)
        failAttempt = user.profile.loginFaileAttempt;

    var loginAllowed = false;
    if(info.error && info.error.error == 403){
        if(failAttempt >= 3) {
            console.log('you need to contact the admin!');
            throw new Meteor.Error(403, 'you need to contact the admin!');
        }
        // increment the fail attempts
        failAttempt++;
        console.log(failAttempt);
        loginAllowed = false;
    } else {
        // success login set to 0
        failAttempt = 0;
        loginAllowed = true;
    }

    Meteor.users.update({_id: user._id}, {$set: {'profile.loginFaileAttempt': failAttempt}});

    return loginAllowed;
});