Is this kind of login possible in VBA? - ms-access

I work on Access Project, but I think there is nothing specific to Access in this question.
I have a form and it's possible to open it only if you are in the table of authenticated users (and I authenticate user by his windows username) - I know it is lame authentication.
Here's the code I've put into form open event:
Private Sub Form_Open(Cancel As Integer)
If DCount("User_Id", "Users", "[username]='" & (Environ$("Username")) & "'") Then
Else
MsgBox "Access Denied!"
DoCmd.Quit
End If
End Sub
What I want to accomplish is that when MsgBox "Access Denied!" is displayed, if I type certain word (something as password) before clicking on OK button, that DoCmd.Quit is not executed. I don't want to display anything, just type in the password.
I don't need this desperately, I just want to make this for fun. And I think it would be really cool if it's possible with VBA.

I tested this in Access 2007 and I think the logic is what you want, or at least it's close. Please consider using something like the WindowsUser() function below to get the Windows user name. I get that this is just for fun, so you don't care now. However, keep this point in mind for anything you do care about in the future. Environ("USERNAME") as a security measure is trivially easy to defeat.
Const cstrYourPassword As String = "let me in"
Dim blnGoodbye As Boolean
Dim lngButtons As Long
Dim strPrompt As String
Dim strPassword As String
strPrompt = "Access Denied!" & vbCrLf & vbCrLf & _
"Click Retry to try with password" & vbCrLf & _
"or Cancel to quit."
lngButtons = vbCritical + vbRetryCancel
If MsgBox(strPrompt, lngButtons) = vbRetry Then
strPassword = InputBox("Password:")
If strPassword = cstrYourPassword Then
MsgBox "Welcome " & WindowsUser
Else
blnGoodbye = True
End If
Else
blnGoodbye = True
End If
If blnGoodbye = True Then
MsgBox "That's all folks."
'DoCmd.Quit ' <- enable this when ready.
End If
Use this instead of Environ("USERNAME").
Public Function WindowsUser() As String
Static strUserName As String
If Len(strUserName) = 0 Then
strUserName = CreateObject("WScript.Network").Username
End If
WindowsUser = strUserName
End Function

The following should work, but you may want to modify it to set the password to something better or if you want more than one password. Anyone who knows how to read the code will be able to find out the password as well, so maybe it would be better to put it in the database somewhere?
Const sPassword As String = "PASSWORD"
Const sMESSAGE As String = "Please enter your password"
Const sTITLE As String = "Enter Password"
Dim sInput As String
sInput = InputBox(sMESSAGE, sTITLE)
If sInput <> Password Then
MsgBox "Access Denied!"
DoCmd.Quit
End If

Related

Unwanted Scientific Notation in MS Access

I'm encountering a very strange problem with MS Access. I have some VBA code used on a password reset form. The code hashes the input password and then saves the hash to a table of users. Here's a relevant snippit:
If newPW1 = newPW2 Then
MsgBox ("Passwords Match!")
hashPW = Encrypt(newPW1)
MsgBox ("HashedPW is " & hashPW)
updatePW = "UPDATE Users SET Password = " & hashPW & " WHERE Username = pwChangeUsrnm"
DoCmd.RunSQL (updatePW)
the MSGboxes are my debugging notes. I know the hash generates properly as a long string of numbers, all well and good. When I go into the datasheet for the Users table though, the number has always been converted into scientific notation.
Here's a screenshot of the data sheet. bob.smith is an example of what I end up with after the code runs, the other two are gibberish I entered manually. The field is formatted as a string, so I'm not sure why it would even try to convert the number into SN when as far as I can tell the item is always a string.
I'm thinking the error must creep in around the SQL query? If there's a better way of doing this then I'm all ears.
Thanks in advance for your help!
datasheet
design view
Complete code, just in case:
Option Compare Database
Private Sub Command84_Click()
Dim hashPW As String
Dim updatePW As String
Dim checkName As String
checkName = Nz(DLookup("Username", "Users", "Username = pwChangeUsrnm"), "aaa")
MsgBox ("checkName set to " & checkName)
If pwChangeUsrnm = checkName Then
MsgBox ("Username Found")
If newPW1 = newPW2 Then
MsgBox ("Passwords Match!")
hashPW = Encrypt(newPW1)
MsgBox ("HashedPW is " & hashPW)
updatePW = "UPDATE Users SET Password = " & hashPW & " WHERE Username = pwChangeUsrnm"
DoCmd.RunSQL (updatePW)
Else
MsgBox ("Passwords Do Not Match!")
End If
Else
MsgBox ("Username not found")
End If
End Sub
I think Andre has the right of it. I tried adjusting the hashing code to add a letter character and this worked, but then I needed to go back and add the single quote around the hashed PW value- which probably would have made the code work even without adding the letter:
If newPW1 = newPW2 Then
MsgBox ("Passwords Match!")
hashPW = Encrypt(newPW1)
MsgBox ("HashedPW is " & hashPW)
updatePW = "UPDATE Users SET Password = '" & hashPW & "' WHERE Username = pwChangeUsrnm"
DoCmd.RunSQL (updatePW)
A thanks to Zaph's second comment on security as well, I'll take that all into account. For the purposes of this database security isn't too much of a concern as it will be sitting behind existing security measures. The hashing of passwords is more just to avoid ever displaying the passwords in plain text. Nevertheless it's useful to know about these extra functions.

Docmd.acbrowsetoform where clause

Ok So here is my code. I think I'm close but when the frmCondition/Concerns Update form opens it ask for the strCBOProperty value. I know it is probably a syntax error, but I don't know what it is.
Private Sub btnLogin_Click()
Dim strCBOPassword As String
Dim strPassword As String
Dim strCBOProperty As String
Selectnull
strCBOProperty = Me.cboProperty.Column(0)
strCBOPassword = Me.cboProperty.Column(1)
strPassword = Me.txtPassword
If strCBOPassword = strPassword Then
MsgBox "Login Successful!"
DoCmd.BrowseTo acBrowseToForm, "frmCondition/Concerns Update", , "[Forms]![frmCondition/Concerns Update]!cbopropertyname = strCBOProperty"
Else
MsgBox "Invalid Password"
End If
End Sub
Private Sub Selectnull()
If IsNull(Me.cboProperty) Then
MsgBox "Please select a property", vbOKOnly
ElseIf IsNull(Me.txtPassword) Then
MsgBox "Please enter a password", vbOKOnly
End If
End Sub
I'd say you need something like this:
DoCmd.OpenForm "frmCondition", WhereCondition:="PropertyName='" & Me.cboProperty.Value & "'"
If not, tell us more about the contents of cboProperty and the data type of the property column in the conditions table.
If you have the value in a variable:
DoCmd.OpenForm "frmCondition", WhereCondition:="PropertyName='" & strCBOProperty & "'"
The variable must be outside of the string.
Using named parameters makes sure you get the parameter right. You have it on the FilterName position.

Troubles with code for login on Access

I am new to VB Scripting and Scripting of any kind but I am a fast learner.
I have with the help of various aids been developing an Access database where scripting is used.
I have developed the below script as part of a login screen.
Private Sub cmdLogin_Click()
Dim dbs As Database
Dim rstUserPwd As Recordset
Dim bFoundMatch As Boolean
Set dbs = CurrentDb
Set rstUserPwd = dbs.OpenRecordset("qryUserPwd")
bFoundMatch = False
If rstUserPwd.RecordCount > 0 Then
rstUserPwd.MoveFirst
' check for matching records
Do While rstUserPwd.EOF = True
If rstUserPwd![UserName] = frmLogin.txtUsername.Value And rstUserPwd![Password] = frmLogin.txtPassword.Value Then
bFoundMatch = True
Exit Do
End If
rstUserPwd.MoveNext
Loop
End If
If bFoundMatch = True Then
'Open the next form here and close this one
DoCmd.Close acForm, Me.Name
DoCmd.OpenForm "frmNavigation"
Else
'
MsgBox "Incorrect Username or Password"
End If
rstUserPwd.Close
End Sub
Even though I enter the correct username and password I get the "Incorrect Username or Password message pop up. Can anyone help by telling me what I have done wrong please. If needed I can add a copy of the database.
Carefully consider the logic in this line ...
Do While rstUserPwd.EOF = True
That says to VBA, "run the code in this block while the condition is True". However, when you first encounter that line, your recordset's current row is the first row (as a result of MoveFirst). And therefore EOF is False, and since False is not equal to True, the code in the Do While loop is not run.
My first guess is you want something like this to control the loop.
Do While Not rstUserPwd.EOF
That change might get your code working as you intend. However that approach is more complicated than necessary. Instead of opening a recordset and walking the rows to check for a user name and password match, you could use a DCount expression.
I asume the username and password are both string values and would suggest changing your code as following:
Dim sSql As String
Dim rstUserPwd As DAO.Recordset
Dim bFoundMatch As Boolean
sSql = "Select * from qryUserPwd Where UserName='" & Nz(frmLogin.txtUsername, "") & "' And Password = '" & Nz(frmLogin.txtPassword, "") & "'"
Set rstUserPwd = CurrentDb.OpenRecordset(sSql, dbOpenSnapshot)
If Not (rstUserPwd.BOF And rstUserPwd.EOF) Then
bFoundMatch = True
End If
rstUserPwd.Close: Set rstUserPwd = Nothing
If bFoundMatch = True Then
'Open the next form here and close this one
DoCmd.Close acForm, Me.Name
DoCmd.OpenForm "frmNavigation"
Else
'
MsgBox "Incorrect Username or Password"
End If
You could also use this 1 liner:
bFoundMatch = DCount("*", "qryUserPwd", "UserName = '" & frmLogin.txtUsername & "' And Password = '" & frmLogin.txtPassword & "'") > 0

How do I check if a user has a certain role in their profile?

Good-day,
I need some help. I'm trying to query my MySQL database to see if the currently logged on user to my application has certain rights/role. If the queried value does exist, then I want to enable a certain menu item.
I checked out most of the similar questions as I was typing my question, but they mostly deal with ASP and JSP so that confuses me even further (as I haven't studied those yet). I'm still learning VB.Net and MySQL.
Your help would be greatly appreciated.
Here's my code - what am I not doing right?:
Public Sub checkAccessLevel()
Dim dbConn As New MySqlConnection(String.Format("Server={0};Port={1};Uid={2};Password={3};Database=parts", FormLogin.ComboBoxServerIP.SelectedItem, My.Settings.DB_Port, My.Settings.DB_UserID, My.Settings.DB_Password))
Dim dbQuery As String = "SELECT Level FROM users WHERE username = '" & FormLogin.TextBoxUsername.Text & "'"
Dim dbAdapter As New MySqlDataAdapter(dbQuery, dbConn)
Dim dbData As MySqlDataReader
Try
dbConn.Open()
dbData = dbAdapter.SelectCommand.ExecuteReader
dbData.Read()
While dbData.Read
Select Case UCase(dbData(0).ToString)
Case Is = "Admin"
TSMenuItemOptions.Enabled = True
Case Is = "Manager"
TSMenuItemOptions.Enabled = True
Case Is = "User"
TSMenuItemOptions.Enabled = False
End Select
End While
dbData.Close()
Catch ex As Exception
MessageBox.Show("A DATABASE ERROR HAS OCCURED" & vbCrLf & vbCrLf & ex.Message & vbCrLf & _
vbCrLf + "Please report this to the IT/Systems Helpdesk at Ext 131.")
Finally
dbAdapter.Dispose()
dbConn.Close()
End Try
End Sub
I managed to resolve my own question as follows;
By modifying the Select Case statement....
ORIGINAL (Incorrect):
Select Case UCase(dbData(0).ToString)
MODIFIED (Correct):
Select Case dbData(0).ToString

Creating a login form in Microsoft Access using macros, without VBA.

I've looked around for ages and I haven't found an answer to my problem so I was hoping someone here could help me.
I am creating a system using Microsoft Access where I have a members table containing a username and password and various other fields such as date of birth, etc.
I want to create a form where users can enter a username and password. By clicking a button on this form, these details will then be checked against the usernames and passwords in the members table. If the details match, a message will be displayed saying they have logged in. If the details are not found in the table, a message saying the details are incorrect will show.
How can I do this without using VBA?
I have started by creating a form called loginform with two text boxes loginusername and loginpassword.
Where should I go from here?
The VBA solution shouldn't be that complicated. A quick and dirty solution:
Dim Result as Variant
Result=Dlookup("Password","tblMembers","UserName='" & nz(loginusername.value,"") & "'")
If nz(Result,"")<>nz([login password].value,"") Then
MsgBox "Invalid password"
Else
MsgBox "Password correct"
End If
'set the variables
Dim UN As String
Dim PW As String
Dim user, pass As Boolean
'make sure none of the fields are null, or blank
UN = Text
PW = Text
If IsNull(Username) Then
MsgBox "You must enter a username."
Username.SetFocus
Else
'assign true to user
user = True
End If
If IsNull(Password) Then
MsgBox "You must enter a password."
Password.SetFocus
Else
pass = True
End If
If user = True And pass = True Then
UN = DLookup("[Username]", "LoginTable", "[Username]= '" & Me.Username & "'")
PW = DLookup("[Password]", "LoginTable", "[Password] = '" & Me.Password & "'")
End If
If Me.DummyUser = Me.Username And Me.DummyPass = Me.Password Then
MsgBox "Access granted."
Else
MsgBox "Access denied."
End If