2013-12-15 2 views
-1

Как подтвердить имя пользователя и пароль для входа в систему, а затем также проверить тип пользователя, на основе которого могут запускаться различные события?Как подтвердить пароль пользователя и имя пользователя в Vb.net?

например, администратор имеет определенные привилегии, а обычный пользователь имеет разные привилегии.

Public Class Войти

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 
+1

По используя операторы = и/или <>. –

ответ

0

Давайте предположим, что база данных содержит таблицу, содержащую имя пользователя, пароль и булево, который называется что-то вроде IsAdmin и может быть установлен на истинным или ложным, в зависимости от прав пользователей ,

Теперь вы должны использовать свое DB-соединение для проверки имени пользователя и пароля. Вот небольшой пример:

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 
0

Открытый класс 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 

'если у вас есть проблемы, спросите меня в [email protected]' сильный текст End класса

+1

над публичным классом, используйте Imports System.Data (нажмите enter) Imports System.Data.SqlClient (нажмите ввод) Импорт System.Drawing.Printing (нажмите enter) – Hardwell

Смежные вопросы