如何在 Vb.net 中验证用户名密码和用户类型登录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20594917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 17:20:10  来源:igfitidea点击:

How to validate a username password and usertype login in Vb.net?

vb.net

提问by user3104431

How to validate a username and password to login and then also check the usertype, based on which different events can be triggered?

如何验证登录的用户名和密码,然后检查用户类型,根据哪些不同的事件可以触发?

for example admin has certain privileges and normal user has different privileges.

例如 admin 有一定的权限,普通用户有不同的权限。

Public Class Login

公开课登录

Dim con As New OleDb.OleDbConnection
'new connection to database
Dim dbprovider As String
'to gets the probider name
Dim dbsource As String
'to gets the database provider name
Dim ds As New DataSet
'dataset to table
Dim da As OleDb.OleDbDataAdapter
'databaseAdapter to dataset and database
Dim sql As String
'sql command
Dim usrname1, pswd1, usrtype As String
Dim maxrows, incdec As Integer
'string variables

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    'validation of username and password
    If txtb_uname.Text = usrname1 And txtb_pwd.Text = pswd1 Then
        If usrtype = "admin" Then

            Score.Show()
            Score.btn_delete.Enabled = False
            Score.btn_update.Enabled = False
            Score.Button2.Enabled = False
            Score.Button1.Enabled = False


            'username and password correct go to the netx page
        ElseIf txtb_uname.Text = usrname1 And txtb_pwd.Text = "" Then
            MsgBox("Enter Password")
            'blank password control
        ElseIf txtb_uname.Text = "" And txtb_pwd.Text = pswd1 Then
            MsgBox("Enter Username")
            'blank username control
        ElseIf txtb_uname.Text = usrname1 And txtb_pwd.Text <> pswd1 Then
            MsgBox("Invalid Password")
            'incorrect pasword
        ElseIf txtb_uname.Text <> usrname1 And txtb_pwd.Text = pswd1 Then
            MsgBox("Invalid Username")
            'incorrect username
        ElseIf txtb_uname.Text = "" And txtb_pwd.Text = "" Then
            MsgBox("enter Username")
            'blank username and password
        Else
            MsgBox("invalid usertype")
        End If
    Else
        MsgBox("Invalid Username & or Password")
        'incorrect username and password

    End If


End Sub

回答by Ron

Lets assume that your database has a table containing the username, password and a boolean which is called something like isAdmin and can be set on true or false, depending on the users rights.

让我们假设您的数据库有一个包含用户名、密码和一个布尔值的表,它被称为 isAdmin 之类的东西,可以根据用户权限设置为 true 或 false。

Now you have to use your DB connection to validate the username and the password. Here is a little example:

现在您必须使用您的数据库连接来验证用户名和密码。这是一个小例子:

Public Shared Function Login(ByVal Name As String, ByVal Password As String) As Boolean

    Shared OleDbConString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" &   My.Settings.Netzwerkpfad & ";" 'you'll have to enter your own provider etc. I just copied it from another project
    Shared con As OleDbConnection = New OleDbConnection(OleDbConString) 'establish the connection
    Shared cmd As New OleDbCommand 'your sql statement
    Shared reader As OleDbDataReader 'Saving the data you'll get
    Dim Checkpassword String = "" 'The string where you'll put the password you get from the databse
    Dim isAdmin as boolean = False
    Try
        cmd.Connection = con
        cmd.CommandText = "SELECT Password, isAdmin FROM tbl_User WHERE Name = '" & Name & "';" 'tbl_User is just the table name, this may be different in your DB

        con.Open() 'opens the database connection

        reader = cmd.ExecuteReader 'executes your command

        Do While reader.Read
            Checkpassword = reader("Password") 'reader("Password") returns the column "Password" in your databse
            isAdmin = reader("isAdmin") 'Returns true or false depending on the users rights
        Loop

        If Password.Equals(Checkpassword ) Then 'Checks if the entered password is correct


          If isAdmin = True Then 'Check if Admin and based on the outcome call the functions or save the outcome            into global variables 

          Else

          End If
        Else

        End If

    Catch ex As Exception
        MessageBox.Show(ex.Message, "Error while trying to log in", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Return Nothing
    Finally
        con.Close()
    End Try
End Function

回答by Hardwell

Public Class frmAdminLoginpage

公共类 frmAdminLoginpage

Dim ErrorCount As Integer

Private Sub frmAdminLoginpage_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    ErrorCount = 0

End Sub

Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click

    MessageBox.Show("Are you sure you want to Exit?", "Exit", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation)
    Me.Close()

End Sub

Private Sub lblCreateAccount_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles lblCreateAccount.LinkClicked
    frmRegister.Show()
    Me.Hide()
End Sub
Private Sub lblForgotPassword_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles lblForgotPassword.LinkClicked

    frmForgotPassword.Show()
    Me.Hide()

End Sub

Sub ClearControls()
    txtLoginID.Text = ""
    txtLoginPassword.Text = ""
    txtLoginID.Focus()

End Sub

Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
    'Clear text
    ClearControls()

End Sub


Protected Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
    Dim strConnectionString As String
    Dim sqlCnn As SqlConnection
    Dim sqlCmd As SqlCommand
    Dim adapter As New SqlDataAdapter
    Dim ds As New DataSet
    Dim strSQL As String

    ' Check if ID or password is empty
    If txtLoginPassword.Text = "" Or txtLoginID.Text = "" Then
        MessageBox.Show("Please Enter your ID and Password.", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    Else
        ' Both fields was supply
        ' Check if user exist in database
        ' Connect to Database

        strConnectionString = "Data Source=LENOVO-PC; Initial Catalog=VB; Integrated Security=True"

        Try
            'Database records will verify the Staff ID, password and position from the Staff Database 
            strSQL = "Select * FROM Staff WHERE StaffID='" & txtLoginID.Text & "'And Password = '" & txtLoginPassword.Text & "'And Position='Administrator'"
            'strSQL = "Select * FROM Staff WHERE Position='Administrator'"

            sqlCnn = New SqlConnection(strConnectionString)
            'Open Database Connection

            sqlCnn.Open()
            sqlCmd = New SqlCommand(strSQL, sqlCnn)
            Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader

            If sqlReader.Read() Then

                frmSales_Admin.Show()
                Me.Hide()

            Else
                ' If user enter wrong ID and password
                ' Throw an error message
                MessageBox.Show("Incorrect User ID and Password..", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

                ErrorCount = ErrorCount + 1

                'Clear all fields
                txtLoginID.Text = ""
                txtLoginPassword.Text = ""

                'Focus on login ID field
                txtLoginID.Focus()

                'If login was not successful at the first time, the user will only have two more Login attempts left
                If (ErrorCount = 1) Then
                    lblNotify.Text() = "You have 2 login attempts left"

                    'If login was not successful for the second time, the user will only have one more Login attempts left
                ElseIf (ErrorCount = 2) Then
                    lblNotify.Text() = "You have 1 login attempt left"

                    'If login was not successful for the third time, the user will not have anymore attempts left
                ElseIf (ErrorCount = 3) Then
                    MessageBox.Show(" You have exceeded the maximum login attempts. System is now exiting. ", " Error! ", MessageBoxButtons.OK, MessageBoxIcon.Error)

                    'The system will then exit after the message box is closed
                    Application.Exit()

                End If

            End If

        Catch ex As Exception
            MessageBox.Show("Failed to connect to Database.", "Database Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try

    End If

End Sub

Private Sub chkShowPassword_CheckedChanged(sender As Object, e As EventArgs) Handles chkShowPassword.CheckedChanged
    'To Make Password Visible
    If chkShowPassword.Checked Then

        txtLoginPassword.PasswordChar = ""
    ElseIf chkShowPassword.Checked = False Then 'To make password not visible

        txtLoginPassword.PasswordChar = "*"

    End If

End Sub

Private Sub txtLoginID_DoubleClick(sender As Object, e As EventArgs) Handles txtLoginID.DoubleClick
    txtLoginID.Clear()
    txtLoginID.Focus()
End Sub

Private Sub btnBack_Click(sender As Object, e As EventArgs) Handles btnBack.Click
    'To go back to the main page of the app
    frmSmartBookStore.Show()
    Me.Hide()
End Sub

Private Sub txtLoginPassword_KeyDown(sender As Object, e As KeyEventArgs) Handles txtLoginPassword.KeyDown
    Dim strConnectionString As String
    Dim sqlCnn As SqlConnection
    Dim sqlCmd As SqlCommand
    Dim adapter As New SqlDataAdapter
    Dim ds As New DataSet
    Dim strSQL As String

    'If user press enter key on password textbox
    If e.KeyCode = Keys.Enter Then
        If txtLoginPassword.Text = "" Or txtLoginID.Text = "" Then
            MessageBox.Show("Please Enter your ID and Password.", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Else
            ' Both fields was supply
            ' Check if user exist in database
            ' Connect to Database

            strConnectionString = "Data Source=LENOVO-PC; Initial Catalog=VB; Integrated Security=True"

            Try
                strSQL = "Select * FROM Staff WHERE StaffID='" & txtLoginID.Text & "'And Password = '" & txtLoginPassword.Text & "'And Position='Administrator'"
                'strSQL = "Select * FROM Staff WHERE Position='Administrator'"

                sqlCnn = New SqlConnection(strConnectionString)
                'Open Database Connection

                sqlCnn.Open()
                sqlCmd = New SqlCommand(strSQL, sqlCnn)
                Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader

                If sqlReader.Read() Then

                    frmSales_Admin.Show()
                    Me.Hide()

                Else
                    ' If user enter wrong username and password combination
                    ' Throw an error message
                    MessageBox.Show("Incorrect User ID or Password..", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

                    ErrorCount = ErrorCount + 1

                    'Clear all fields
                    txtLoginID.Text = ""
                    txtLoginPassword.Text = ""

                    'Focus on login ID field
                    txtLoginID.Focus()

                    'If login was not successful at the first time, the user will only have two more Login attempts left
                    If (ErrorCount = 1) Then
                        lblNotify.Text() = "You have 2 login attempts left"

                        'If login was not successful for the second time, the user will only have one more Login attempts left
                    ElseIf (ErrorCount = 2) Then
                        lblNotify.Text() = "You have 1 login attempt left"

                        'If login was not successful for the third time, the user will not have anymore attempts left
                    ElseIf (ErrorCount = 3) Then
                        MessageBox.Show(" You have exceeded the maximum login attempts. System is now exiting. ", " Error! ", MessageBoxButtons.OK, MessageBoxIcon.Error)

                        'The system will then exit after the message box is closed
                        Application.Exit()

                    End If

                End If

            Catch ex As Exception
                MessageBox.Show("Failed to connect to Database.", "Database Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End If
    End If
End Sub

'if you have problems ask me at [email protected]'strong textEnd Class

'如果你有问题问我 [email protected]'强文本结束类