refer to a cell in an access table - vba

I have a login form that requiers verification of username and password
I hashed the password in the access table (sha1)
I used the dlookup function to find the user but i didnt know how to compare the password entered only with the found username's password
If (IsNull(DLookup("UserName", "UserID", "UserName='" & Me.Userbox.Value & "'")))
i did this but when the username is found i dont know how to refer to its password saved as a hash
means that i want to know how to refer to a cell in an acess table.
thank you

It's best to open a recordset containing the username and password for the given user. If the username doesn't exist, the recordset will be empty.
Dim r As DAO.Recordset
Set r = CurrentDb().OpenRecordset("SELECT UserName, Password FROM UserID WHERE UserName='" & Userbox.Value & "'", dbOpenSnapShot)
If r.EOF Then
'Username does not exist
Exit Sub
End If
'Reaching this point means the username exists.
'Hash the given password and compare it with the one stored in the table.
'The password returned from the recordset can be obtained using r![Password]

Related

MS Access using TempVar for Login and permissions?

I'm attempting to setup a simple login with permissions level in my Access Database. I am trying to use TempVars but for some reason it seems to be just picking the first records permissions rather than the username from the login.
The table "Memberstbl" has the fields "Call Sign" (which is the user name), "Password" and "Permissions" (Numbers 1-3) set for user permissions.
There is a separate table for the Permissions where each number is identified
and a final table that dictates which PermissionID has access to which form, in this case just the "Admin Menu" form
The issue is when I login with the admin account it seems to keep picking up the Permission "1" which is what the first user in the Memberstbl is set to. I don't think it's connecting "Call Sign" with the "Permissions" level, and I'm not sure what I'm missing. I've never used TempVars before so I'm not sure if I'm using it correctly.
Any help would be greatly appreciated!
Code for Login:
Private Sub LogonBtn_Click()
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("Memberstbl")
'Username and Password Check
If IsNull(Me.Username) Then
MsgBox "Please Enter Login ID", vbInformation, "Login Required"
Me.Username.SetFocus
ElseIf IsNull(Me.Password) Then
MsgBox "Please Enter Password", vbInformation, "Password Required"
Me.Password.SetFocus
Else
If (IsNull(DLookup("[Call Sign]", "Memberstbl", "[Call Sign]='" & Me.Username.Value & "'"))) Or _
(IsNull(DLookup("Password", "Memberstbl", "Password='" & Me.Password.Value & "'"))) Then
MsgBox "Incorrect Username or Password"
Else
'DoCmd.OpenForm "MainMenu"
'DoCmd.Close acForm, "Logonfrm"
TempVars("Memberstbl") = rs!Permissions
End If
End If
End Sub
Code is opening an unfiltered recordset then later sets TempVar to value of field in first record so of course you always see the same value. Why open a recordset when all you want is a single value? Use another DLookup. Suggest you not use the table name as a TempVar name.
TempVars("PermCode") = DLookup("Permissions", "Memberstbl", "[Call Sign]= '" & Me.Username & "'")
If you really want to use recordset, still need to apply filter criteria with the user inputs. If recordset is empty then user inputs were not valid. If there is a record, then can reference recordset field for the Permissions value. None of the DLookups would be used with this approach.

')' expected in vb

I am trying to create a login form using Visual Basic and MS Access as my database source but I keep getting error as ')'expected. Please find my code below and help me solve this, because I have spent the entire day trying to find solution to this error.
sql =("SELECT Username,Password from tblLogin")
Where Username= '" & Trim(txtUsername.text) & "'
And Password='" & trim(txtPassword.text) & "')';
NEVER concatenate user inputs into any SQL statement, use proper parameters instead.
This means your SQL should look like this:
sql = "SELECT [UserName], [Password] FROM tblLogin WHERE [UserName]=? AND [Password]=?;"
Note that there is no need to track whether a column wants single quotes or not, which makes things much more robust, not to mention much more secure. Also the unbalanced parentheses issue becomes irrelevant.
The sql string should be used in some ADO Command or DAO (? ...not really familiar with Access) QueryDef object, as the command's CommandText or the querydef's definition.
Then you add Parameters to the ADO command and supply their values in the order they appear in the SQL command string, or set the named querydef parameters' respective Value accordingly.
Exactly how that's done depends on what type of Connection you're working with; this answer shows how you can use DAO QueryDefs in Access to do this, and this answer shows how you can use ADO to do the same with a Command and Parameter objects.
As a security note, I need to mention that storing password in plain text in a database is a very bad idea. Best practice would be to salt+hash the passwords, and only store the resulting hashes in the database; login is successful not when the user input matches the stored password, but when the salted user input produces the same hash value as the one stored for the claimed login: neither the code, the database, nor the developer actually needs to know anyone's passwords. This is important, because humans have this tendency to reuse passwords elsewhere, so if weak security isn't a problem for this particular application, it becomes a problem when a user decides to reuse their Facebook login for it, or to reuse their password for [other app whose security is actually important].
Try with:
sql ="SELECT Username, [Password] from tblLogin " & _
"Where Username = '" & Trim(txtUsername.Text) & "' " & _
"And [Password] = '" & Trim(txtPassword.Text) & "'";
Password is a reserved word.
Try replacing your line with this one instead:
sql = "SELECT Username,Password from tblLogin Where Username= '" &
Trim(txtUsername.text) & "'" & " And Password= '" &
trim(txtPassword.text) & "'"

Is there a simple code to allow certain user(s) access to see command buttons?

Okay, I am having difficulties coding security behind my user form. Let me give you guys the rundown. I created this make table "tblPermissionTypes" that basically has two field in there "ID" & "EmployeeType_ID". The ID field represents Security level of access 0 through 2, and EmployeeType_ID is the title: 0 = Requestor, 1 = Admin, and 2 = Printer.
With that being said I have another table "tblEmployees" with the same field "EmployeeType_ID", I manually set the 0s, 1s, & 2s. This table also contains all employees UserNames
Finally, I have another table "tblPermission" that contains three fields "EmployeeType_ID", "FormName", and "HasAccess"
My end result is being whenever this tblPermission has a Checkbox under the field HasAccess I want to grant access based on the EmployeeType_ID field to communicate back to the table "tblEmployees", but in this case I want them to only be able to see a button that contains that certain form.
Private Sub cmdClick_Click()
Dim strSQL As String
Dim permission As String
If permission = ("fOSUserName") = True Then
Run strSQL
strSQL = "SELECT * FROM tblEmployees WHERE "
strSQL = strSQL & "tblEmployees.Five2 =" & ("fOSUserName") & """, = False
Then
MsgBox "You do not have permission!", vbExclamation
Else'
cmdButton.Visible True
End If
NOTE: fOSUserName, is a function I created basically the same thing as
Environ("UserName")
Debug.Print strSQL
Function calls should not be within quote marks. You construct an SQL statement but then don't properly use it. You declare and use variable permission but don't set the variable - it is an empty string. Need form name as a search criteria. Couple of other syntax errors but they will go away with this suggested code. Run this code in form Open event to disable button and don't even give unauthorized users opportunity to click. Don't annoy them with a popup message that emphasizes their lowly status in hierarchy.
You need to build a query that joins tblEmployees to tblPermission so that UserName, FormName, HasAccess fields are all available then reference that query in search for permission.
A DLookup could serve here.
Me.buttonNameHere.Visible = Nz(DLookup("HasAccess", "queryNameHere", _
"UserName='" & fOSUserName & "' AND FormName='FormNameHere'"), 0)

How to compare encrypted password in database with newly entered password during login?

Im doing a registration and login form where I already encrypted the password when user entered the password in registration phase. So for login I know that I need to compare the encrypted password in database with the newly entered encrypted password during login. I dont know if im missing some code or im writing the wrong code. I know that this question have been asked few times but I hope I can get some help here. The error that im getting is just a message where Failed to Connect to Database
I already found the solution C# encrypted Login and try to follow the code but still, it have error.
If PasswordTextBox1.Text = "" Or UsernameTextBox2.Text = "" Then
MessageBox.Show("Please fill-up all fields!", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
'Clear all fields
PasswordTextBox1.Text = ""
UsernameTextBox2.Text = ""
'Focus on Username field
UsernameTextBox2.Focus()
Else
'Connect to DB
Dim conn As New System.Data.OleDb.OleDbConnection()
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + "C:\Users\user1\Documents\Visual Studio 2010\Projects\Crypto\Crypto\crypto.accdb"
Try
'Open Database Connection
conn.Open()
Dim sql As String = "SELECT Password FROM registration WHERE Username='" & Encrypt(UsernameTextBox2.Text) & "'"
Dim cmd As OleDbCommand = New OleDbCommand(sql, conn)
Dim sqlRead As OleDbDataReader = cmd.ExecuteReader()
Dim password As String = cmd.ExecuteScalar().ToString().Replace("", "")
If (password = Encrypt(PasswordTextBox1.Text)) Then
PasswordTextBox1.Clear()
UsernameTextBox2.Clear()
'Focus on Username field
UsernameTextBox2.Focus()
Me.Hide()
Mainpage.Show()
Else
LoginAttempts = LoginAttempts + 1
If LoginAttempts >= 3 Then
End
Else
' If user enter wrong username or password
MessageBox.Show("Sorry, wrong username or password", "Authentication Failure", MessageBoxButtons.OK, MessageBoxIcon.Error)
'Clear all fields
PasswordTextBox1.Text = ""
UsernameTextBox2.Text = ""
'Focus on Username field
UsernameTextBox2.Focus()
End If
End If
Catch ex As Exception
MessageBox.Show("Failed to connect to Database", "Database Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
'Clear all fields
PasswordTextBox1.Text = ""
UsernameTextBox2.Text = ""
End Try
End If
End Sub
I expecting that the encrypted password in database can be matched with the newly entered password so that user can login into the system.
Here's what usually happens. When the user registers, you get them to provide a user name and a password, as well as confirming the password. The idea of the confirmation is that the password is usually masked and you want to ensure that they don't lock themselves out of their account by saving a typo. You then hash the password provided with salt and save the user name with the salt and hash. When the user logs in, you get the salt for that user and hash the password provided with that, then compare that to the hash stored in the database. If the hashes match, the user is successfully authenticated.
Hashing is considered preferable to encryption because it is one-way, so no one can reverse-engineer a password from a hash except by brute force. The salt provides extra security because two users with the same password will still not have the same hash. This means that, if the user forgets his password, the system cannot send the existing password to him because it doesn't know what it is. The user has to create a new password in that case. If you use the forgotten password feature of a web site or the like and they tell you what your current password is, they are using inferior security. If they make you create a new password then they are almost certainly using hashing.
There is lots of information about hashing and salting on the web. It's also worth noting that ASP.NET Identity (which can be used outside ASP.NET apps if you want) has password hashing built right in.

VBA Excel Workbook with Database connection to SQL server need login information

I have an Excel VBA workbook that I have created. It has a control panel page with a button installed to run the VB/ASP script that runs against our SQL Database. I have created text boxes for entry for dates and have used these as input for the VB/ASP script that pulls the individual sheets(Reports). Now, I want to declare the username from ENVIRON ("UserName") then evaluate the username against a list of usernames and return the user_id (aka UserNumber) to the text box on the control panel page (user_id in sql database).
Example: if sjones is logged into windows then evaluate list of Usernames=165?, then
Var1 = Var1 & "OR ( pd.created_by = '" + Sheets("Control Panel").UserNumber.Text + "' ) ) " & vbCrLf
I want to pull reports based on the person logged into Windows at the time to keep others from running the report for anyone but themselves. The worksheet location is open to all users but I want them to only run the reports for the user logged in? There is probably an easier way to do this but I am very weak in VB/ASP. Please help. TIA Conya
Get username first and execute a sql query to get a userID associated with that. The code might looks like:
Public UName, UID as String
Public Sub GetUName()
UName = Environ("USERNAME")
End Sub
Public Sub GetUID()
strSQL = "Select UID from table1 where username=" & "'" UName & "'"
UID = oConn.Execute strSQL
End Sub