My Login Method for Access 2007 doesn't work - vba

This is my first try at VBA on the whole. So I'm not familiar with everything.
I'm trying to make a login for a database in Access 2007.
I have 2 Tables named TableLogin and TableUserLevel.
TableLogin has ID, Username, Password and UserLevel that is linked to TableUserLevel.
TableUserLevel has ID and UserLevel which has the levels of Admin and User.
I have a form named LoginForm that has 2 fields named txtUsername and txtPassword and a button named cmdLogin.
I'm pretty sure my DLookUp methods are wrong, but I don't know why. I'm using the first DLookUp to see if the username and password match one ID and if so it will then go to the second DLookUp method to see which userlevel security that particular user has.
Right now, I'm not sure the first DLookUp even works good. I'm not sure if it checks if both input came from one ID. I'm hoping it works like that and the last DLookUp method only return 0 and I don't know why.
The VBA code for the button is:
Private Sub cmdLogin_Click()
Dim UserLevel As Integer
Dim Username As String
If IsNull(Me.txtUsername) Or Me.txtUsername = "" Then
MsgBox "You must enter a Username.", vbOKOnly, "Required Data"
Me.txtUsername.SetFocus
Exit Sub
End If
'Check to see if data is entered into the password box
If IsNull(Me.txtPassword) Or Me.txtPassword = "" Then
MsgBox "You must enter a Password.", vbOKOnly, "Required Data"
Me.txtPassword.SetFocus
Exit Sub
End If
'Check value of username and password in tblLogin to see if this
If IsNull(DLookup("ID", "TableLogin", "Username = '" & Me.txtUsername.Value & "'") And DLookup("ID", "TableLogin", "Password = '" & Me.txtPassword.Value & "'")) Then
MsgBox "Password or Username invalid. Please Try Again", vbOKOnly, "Invalid Entry!"
Else
Username = Me.txtUsername.Value
If IsNull(DLookup("UserLevel", "TableLogin", "Username = '" & Me.txtUsername.Value & "'")) Then
MsgBox ("No security level")
Else
If UserLevel = 1 Then
MsgBox ("yes" & UserLevel)
Else
MsgBox ("No" & UserLevel)
End If
End If
'Close login form and open screen
DoCmd.Close acForm, "LoginForm", acSaveNo
End If
'If User Enters incorrect password 3 times database will shutdown
intLogonAttempts = intLogonAttempts + 1
If intLogonAttempts > 3 Then
MsgBox "You do not have access to this database. Please contact admin.", vbCritical, "Restricted Access!"
Application.Quit
End If
End Sub

Related

Runtime Error 15 - Type Mismatch for code to change a password in MS Access database

I get a Runtime Error 15 on the following line:
MyuserID = Me.txtfirstname.Value from the code below:
Option Compare Database
Option Explicit
Private Sub cmdchange_Click()
On Error Resume Next
If Trim(Me.txtnewpass & "") <> Trim(Me.txtconfirmpass & "") Then
MsgBox "Passwords do not match", vbExclamation + vbOKOnly, ""
Me.cmdchange.Enabled = False
Else
Me.cmdchange.Enabled = True
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("Select' From[User Registration Details] where [UserID]=" & MyuserID)
If Not rs.EOF And Not rs.BOF Then
rs.Edit
rs("Password") = txtconfirmpass
rs.Update
rs.Close
Set rs = Nothing
MsgBox "Your Password has been successfully changed", vbInformation, "Electporl"
DoCmd.Close acForm, "frmnewpassword", acSaveNo
DoCmd.OpenForm "frmlogin"
End If
End If
Given that I placed the code below on the button that takes the user to the changing password form.
Private Sub cmdproceed_Click()
If IsNull(Me.txtfirstname) Or Me.txtfirstname = "" Then
Me.mand1.Visible = True
Me.txtfirstname.SetFocus
End If
If IsNull(Me.txtemail) Or Me.txtemail = "" Then
Me.mand2.Visible = True
Me.txtemail.SetFocus
End If
Dim rs As Recordset
Set rs = CurrentDb.OpenRecordset("User Registration Details", dbOpenSnapshot, dbReadOnly)
rs.FindFirst ("Firstname='" & Nz(Me.txtfirstname, "") & "'")
If rs.NoMatch = True Then
Me.lbl1.Visible = True
Me.txtfirstname.SetFocus
Exit Sub
End If
If rs!Username <> Nz(Me.txtemail, "") Then
Me.lbl2.Visible = True
Me.txtemail.SetFocus
Exit Sub
End If
'MyuserID is publicly declared as Long in a module
MyuserID = Me.txtfirstname.Value
DoCmd.OpenForm " frmnewpassword"
DoCmd.Close acForm, Me.Name
End Sub
the second code is assigned to the button that redirects the user to the form that will enable him or her change the password after verifying his or her first name and email.
The second one now is assigned to the button that will help the user change the password by overwriting the old password.
Please pass the UserID value in your procedure.
In your cmdproceed_Click() procedure update the following section:
'MyuserID is publicly declared as Long in a module
MyuserID = rs("UserID")
In your cmdchange_Click() procedure update the following line:
Set rs = CurrentDb.OpenRecordset("Select * From [User Registration Details] where [UserID]=" & MyuserID)
From a logical point of view, you can have others with the same firstname, so doing the filter on the firstname only will introduce unexpected behaviors later in the life cycle of your application.
If you have two or more users with the first name 'Joshua' then your code will always select the first user with that first name. You need to update this logic to select a unique user.

Compare String with Table fields value

Hello to all programmers, I am very new to MS Access, but have some experience with Excel (including VBA). I've been searching for few days now and tested several suggestions with zero success so far. It's getting frustrating already and I decided to ask directly for my case.
From a loaded form I get the user to input password via Inputbox, I need my code to search for that string in my table Crewlist, field Password and criteria is another field Admin (Yes/No).
To facilitate the search I made a query table containing all people with field Admin (all are Yes) and field Password.
Looking forward for any particular solution. So far I have tried creating array & recordset.
Edit
(e.g as requested - table containing required info to be compared)
Field1 Field2 Field3("Admin")
Name1 password1 No
Name2 password2 Yes
Name3 password3 Yes
"If " statement comparing Inputbox string with Field2 where Admin=Yes
Dlookup will return the first result, ie Password2, but Name3 and password3 should also be looked and compared).
Recordset and simple SQL code will be required, I am now working on it.
I would suggest using a simple DLookup expression for this task, for example, assuming that the password entered by the user is stored in a variable pwd, you might use:
DLookup("Password","Crewlist","Admin = True and Password = '" & pwd & "'")
The DLookup function will return Null if no match is found, which you can test with an If statement and the IsNull function, e.g.:
If IsNull(DLookup("Password","Crewlist","Admin = True and Password = '" & pwd & "'")) Then
MsgBox "Invalid Password!"
Else
' Do Stuff
End If
Here, I only specify the Password field as the field to be looked up as DLookup requires a specific field whose value should be returned. You could instead use the DCount function and test whether the return is non-zero, e.g.:
If DCount("*","Crewlist","Admin = True and Password = '" & pwd & "'") > 0 Then
' Do Stuff
Else
MsgBox "Invalid Password!"
End If
Implemented in the event handler for a button, this might be written as:
Private Sub Command0_Click()
Dim pwd As String
pwd = InputBox("Enter Password:", "Password")
If pwd <> vbNullString Then
If IsNull(DLookup("Password", "Crewlist", "Admin = True and Password = '" & pwd & "'")) Then
MsgBox "Invalid Password!"
Else
MsgBox "Access Granted!"
End If
End If
End Sub
Note that this is only checking the password, hence, with only the above code, the user could specify the password for any Admin user and be granted access.
You could easily check the username with an additonal prompt:
Private Sub Command0_Click()
Dim usr As String
Dim pwd As String
usr = InputBox("Enter Username:", "Username")
If usr <> vbNullString Then
pwd = InputBox("Enter Password:", "Password")
If pwd <> vbNullString Then
If IsNull(DLookup("Password", "Crewlist", "Admin = True and Username = '" & usr & "' and Password = '" & pwd & "'")) Then
MsgBox "Invalid Username or Password!"
Else
MsgBox "Access Granted!"
End If
End If
End If
End Sub
However, this would be more professional if you were to design your own modal form containing a textbox or combobox for the username and a textbox in which the user may specify their password.
Aside, storing passwords in a database in plain text is bad practice: consider hashing the password using an appropriate hash function and storing the hash value. Then, apply the same hash function to the user input and use the resulting hash value to test for a match in your database.
This way, only the user has knowledge of the password - since hashing is a one-way process, not even the database admin has knowledge of user's passwords. If a user needs to change their password, they would either be supplied with a new temporary password that they could change or would provide a new password following some other authentication.
As a general rule, never trust any service that is able to send you your original password - this reveals that such a service is storing passwords without encryption/masking.
This is what I came with this morning after reading some examples about recordset and looping. My code in VBA
Sub Auto_Logo0_Dblclick
Dim AdmPass As String
AdmPass = Inputbox ("Admin password required")
'next part is taken from my guide book for Access
Dim Con1 As ADODB.Connection
Set Con1 = CurrentProject.Connection
Dim rcrdPass As New ADODB.Recordset
rcrdPass.Activeconnection = Con1
'SQL part
Dim mySQL as String
mySQL = "SELECT Crewlist.Surname, Crewlist.Password,"
mySQL = mySQL & " Crewlist.Admin"
mySQL = mySQL & " From Crewlist"
mySQL = mySQL & " Where (Crewlist.Admin = 'Yes')"
rcrdPass.Open mySQL
With rcrdPass
If Not .BOF And Not .EOF Then
.MoveFirst
.MoveLast
While (Not .EOF)
If AdmPass = rcrdPass.Fields("Password") Then
Call DoCmd.SelectObject(acTable,,True)
Else Msgbox ("Wrong password, try again")
End If
.MoveNext
Wend
End If
End With
rcrdPass.Close
Set rcrdPass = Nothing
Set Con1 = Nothing
End sub

VBA Access Dlookup login and password from two tables

I'm having issues with a login menu that I am creating for my database. For this database I have the location of the User login email and password in two locations. After I solve this issue, i'll make validate where the login details originated from to dictate which forms open, for now I have one form to open,
For now I just want to confirm if the the user logins and passwords are valid from either table. However it can only validate the user Login and Password from from tblMembers. If I try to enter details from tblTrainers, I would keep getting a mismatch error. I am aware what this error but not too sure how it works here.
However if I get rid off the Or statement close the statement, it works but of course I cannot use login details from tblTrainers to login. Could anyone offer any suggestions please? Code found below.
Private Sub Command1_Click()
If IsNull(Me.txtLoginID) Then
MsgBox "Please Enter LoginID", vbInformation, "Required"
Me.txtLoginID.SetFocus
ElseIf IsNull(Me.txtPassword) Then
MsgBox "Please Enter A Password", vbInformation, "Required"
Me.txtPassword.SetFocus
Else
If (IsNull(DLookup("Member_Email", "tblMembers", "Member_Email = '" & Me.txtLoginID.Value & "' And Member_Password = '" & Me.txtPassword.Value & "'")) Or (DLookup("Trainer_Email", "tblTrainers", "Trainer_Email = '" & Me.txtLoginID.Value & "' And Trainer_Password = '" & Me.txtPassword.Value & "'"))) Then
MsgBox "Inccorect LoginID or Password"
Else
DoCmd.OpenForm "mnuMain_Menu"
DoCmd.Close acForm, "frmLogin"
End If
End If
End Sub
You can use CurrentDb.OpenRecordset to open recordsets based on SQL queries. You can use .EOF to check if the recordset is at the end of the file, thus contains 0 records.
If you want to query multiple tables at once, you can use a UNION query for that.
If CurrentDb.OpenRecordset("SELECT 1 FROM tblMembers WHERE Member_Email = '" & Me.txtLoginID.Value & "' And Member_Password = '" & Me.txtPassword.Value & "' UNION ALL SELECT 1 FROM tblTrainers WHERE Trainer_Email = '" & Me.txtLoginID.Value & "' And Trainer_Password = '" & Me.txtPassword.Value & "'").EOF Then
Note that this login code is at risk for SQL injection, and these kind of login forms are fundamentally insecure. You can easily demonstrate SQL injection by entering ' OR 1 = 1 OR '' = ' as a username, and entering a random character in the password field. That passes as a valid login if there are entries in the table. An easy fix for SQL injection is to use parameters.

Microsoft Access, vbYesNo can't get record to save

Question on Access, I've created a vbYesNo on the save record button which asks me if is a new record, if it is a yes it saves as a new record, otherwise I need it to Update the existing record.
Private Sub btnSaveDetails_Click()
Dim Response As Integer
Response = MsgBox("Do you wish to create a new record?", vbYesNo, "Continue?")
If IsNull(txtLocation) Then
MsgBox "Please Enter Location Details"
Else
If Response = vbYes Then
DoCmd.RunCommand acCmdSaveRecord
DoCmd.GoToRecord , , acNewRec
Me.Refresh
Me.cboSelectLocation = ""
txtLocation.SetFocus
Else
DoCmd.RunCommand acCmdUndo
End If
End If
End Sub
The Problem basically is that on the Save button it asks if it is a new record, if it is a vbNo I need it to update the current record.
Different method to yours, but this is how I do mine:
If CloseResponse = vbNo Then
Exit Sub
Else
CurrentDb.Execute "UPDATE tbl_Suggestions_Historic SET [Status] = 'Closed By User', [ReasonClosed] = '" & ClosedWhy & "' WHERE ID = '" & ID & "'"

ms access query to create a new login id, each time i wish to add a new user through a user details form

I have a Login table containing user information like, login id, username, password and access level. So i created a form called user details form where i can add new users into the database.
each time i open the user details form, a new id is generated by running a query.
this is what i typed in the field of the query to generate a new id,
new_login_ID: "LI" & Right([Login_ID],2)+1
the problem is, in my login form, i try to login with the following code:
Private Sub LoginBtn_Click()
'Check to see if data is entered into the UserName combo box
Dim lngMyEmpID As Long
If IsNull(Me.cboEmployee) Or Me.cboEmployee = "" Then
MsgBox "You must enter a User Name.", vbOKOnly, "Required Data"
Me.cboEmployee.SetFocus
Exit Sub
End If
lngMyEmpID = Me.cboEmployee.Value
'Check to see if data is entered into the password box
If IsNull(Me.txtPassword) Or Me.txtPassword = "" Then
MsgBox "You must enter a Password.", vbOKOnly, "Required Data"
Me.txtPassword.SetFocus
Exit Sub
End If
'Check value of password in tblAdmins to see if this matches value chosen in combo box
If Me.txtPassword.Value <> DLookup("Password", "tbl_login", "[Login_ID]=" & lngMyEmpID) Then
MsgBox "Password Invalid. Please Try Again", vbOKOnly, "Invalid Entry!"
Me.txtPassword.SetFocus
Me.txtPassword = Null
intLogonAttempts = intLogonAttempts + 1
'If User Enters incorrect password 3 times database will shutdown
If intLogonAttempts >= 3 Then
MsgBox "You do not have access to this database. Please contact your system administrator.", vbCritical, "Restricted Access!"
Application.Quit
End If
Else
Me.txtPassword = Null
'Open correct form
Dim strAccessLevel As String
strAccessLevel = DLookup("[Access]", "tbl_login", "[Login_ID]=" & lngMyEmpID)
If strAccessLevel = "Admin" Then
MsgBox "Welcome " & DLookup("Username", "tbl_login", "Login_ID=" & lngMyEmpID)
DoCmd.Close
DoCmd.OpenForm "frm_Admin"
ElseIf strAccessLevel = "Manager" Then
'MsgBox "Welcome " & DLookup("Username", "tbl_login", "Login_ID")
MsgBox "Welcome " & DLookup("Username", "tbl_login", "Login_ID=" & lngMyEmpID)
DoCmd.Close
DoCmd.OpenForm "frm_main_menu"
End If
End If
End Sub
I get a runtime error saying "mismatch" and when i debug, it points to this line of my login code - lngMyEmpID = Me.cboEmployee.Value
I dont know how to fix this, can someone please explain where i've gone wrong and how i can fix this problem.. thanks in advance :)
This line you have written in the comments should be corrected to this (since lngMyEmpID is now a string) :
If Me.txtPassword.Value <> DLookup("Password", "tbl_login", "[Login_ID]='" & lngMyEmpID & "'")
Same goes for every line you use DLookup and the ID in this manner.