首页 > 解决方案 > 使用计数的 VB.NET 登录尝试

问题描述

我试图弄清楚这些逻辑。示例:如果用户输入错误的值 3 次,他将收到一条消息,例如尝试次数过多,并且应该在 10 秒内无法输入任何内容,之后他应该可以再次登录。我是 vb.net 的初学者,有点迷失在这里。我希望有人能帮助我解决我的问题

PS:我认为我的逻辑中可能的方法是使用 Timer 几秒钟,但不知道如何在我的代码下面构造它

 Private Sub btn_login_Click(sender As Object, e As EventArgs) Handles btn_login.Click

    Dim command As New SqlCommand("Select * from user_access where Username= @user AND Password= @pass", con)
    command.Parameters.Add("@user", SqlDbType.VarChar).Value = txt_username.Text
    command.Parameters.Add("@pass", SqlDbType.VarChar).Value = txt_password.Text
    con.Open()
    reader = command.ExecuteReader()
    Dim count As Integer = 0
    While (reader.Read())
        count = count + 1
    End While

    If (count = 1) Then
        MessageBox.Show("Login Successfully")
        LoginForm1.Hide()
        MainForm.ShowDialog()
    Else
        MessageBox.Show("Invalid Username/Password")

    End If
    If count = 3 Then
        MessageBox.Show("Too Many Logins")
    End If
    con.Close()

End Sub

标签: vb.netvisual-studio

解决方案


通过设计器或在类级别向您的代码添加一个计时器,并将其间隔设置为 10000(10 秒)。

在第三次失败时激活你的计时器,如下所示:

If count = 3 Then
    MessageBox.Show("Too Many Logins. Disabled for 10s")
    btn_login.Enabled = False
    LockoutTimer.Start()
End If

然后你需要处理定时器完成:

Private Sub LockoutTimer_Tick(sender As Object, e As EventArgs) Handles LockoutTimer.Tick
    LockoutTimer.Stop()
    btn_login.Enabled = True
    count = 0
End Sub

正如评论中提到的 muffi,您的逻辑已关闭以检查登录。目前,您检查有多少用户与给定的用户名和密码组合匹配。如果登录不成功,您需要检查是否存在并增加一个单独的变量:

Dim loginSuccess As Boolean = False
While (reader.Read())
    loginSuccess = True
End While

If (loginSuccess) Then
    count = 0
    MessageBox.Show("Login Successfully")
    LoginForm1.Hide()
    MainForm.ShowDialog()
Else
    count += 1
    If count = 3 Then
        MessageBox.Show("Too many invalid login attempts. Disabled for 10s")
        btn_login.Enabled = False
        LockoutTimer.Start()
    Else
        MessageBox.Show("Invalid Username/Password")
    End If 
End If

注意:count 变量需要在按钮单击时保持不变,因此将其设置为类中的字段并在成功登录时重置(如果需要)

Private count As Integer = 0

推荐阅读