Save query results as a string vb.net - sql

I am creating a forgot password feature for a login form. If the users username and email match whats in the database then an email containing their password needs to be sent to their email address. Once my select statements grabs the password I do not know how to convert that over into the body of the email.
cmd2.CommandText = "Select Password from tblLogin where Username = '" & UsernameTextBox.Text & "' and EmailAddress = '" & EmailAddressTextBox.Text & "'"
pass = cmd2.ExecuteReader
If pass.HasRows Then
Do While pass.Read()
EmailMessage.Body = "Here is your password:"
Loop
Else
Console.WriteLine("No rows found.")
End If
The only thing I can think of doing is this:
EmailMessage.Body = ("Here is your password: " & pass)
However I still need to figure out how I can convert pass into a string containing the query result.

EmailMessage.Body = "Here is your password: " & pass.Item(0)

Since you only want the one value from the DB, look at ExecuteScalar instead of ExecuteReader.
However, as Alex commented, unencrypted passwords is really not a good idea.

Related

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.

How do I get a login form to reject entries with wrong capitalization?

I have the following code so far for a login form taking data from a database:
Dim myconnection As New SqlConnection("server=classified;database=classified")
myconnection.Open()
Dim theQuery As String = " SELECT Username, Password FROM Accounts WHERE (Username = '" & TextBox1.Text & "' ) AND (Password = '" & TextBox2.Text & "')"
Dim repeatChecker As SqlCommand = New SqlCommand(theQuery, myconnection)
'mycommand.ExecuteNonQuery()
Using reader As SqlDataReader = repeatChecker.ExecuteReader()
If reader.HasRows Then
' User already exists
While reader.Read()
If reader("Password") = TextBox2.Text.ToString And reader("Username").ToString = TextBox1.Text Then
MessageBox.Show("Logged in successfully as " & TextBox1.Text, "", MessageBoxButtons.OK, MessageBoxIcon.Information)
Firs.Show()
Me.Close()
'Clear all fields
End If
End While
Else
MessageBox.Show("Invalid username or password.", MsgBoxStyle.Critical)
End If
End Using
myconnection.Close()
If I put in the correct login info but with wrong capitalization, I don't get an acceptance or a rejection, the program just sits there and does nothing. How can I get a denial of a login when the capitalization is wrong?
As written, you really can't discern just a case-mismatch from a query as you've illustrated in this code. If a database is set up for case-sensitivity, a query will fail if two strings don't match even for the difference of a single mismatched character, but it doesn't retain that as a reason for the mismatch anymore than it would for, say "Apple" not matching "Banana."
Please note that, as the commentators of your question stated:
You're vulnerable to SQL-Injection attacks.
You should never store passwords in clear text in your DataBase. Once the DB gets cracked, all credentials are compromised. Not to mention evil DB-admins that might get tempted to misuse those credentials...
Case-Sensitivity in a password is a good thing.
With those things mentioned, if you want to provide your users with the comfort of a not case-sensitive username, just cast the TextBox1.Text as well as the query result for the Username to upper case by changing (Username = '" & TextBox1.Text & "' ) to (UPPER(Username) = '" & TextBox1.Text.ToUpper() & "')

Concatenate database query result to a string

I am trying to take the single result from a SQL query and concatenate it to a string. Using SQL Server and Visual Studios.
Dim Password As SqlDataReader
cmd.CommandText = "Select Password from tblLogin where Username = '" & UsernameTextBox.Text & "' and EmailAddress = '" & EmailAddressTextBox.Text & "'"
Password = cmd.ExecuteReader
EmailMessage.Body = ("Your password is: " & Password)
The error I am getting is that I cannot use the operator & with Password.
The Password variable in your code is a SQLDataReader object, not a string. It can have many values, so you need to get the part you want out of it. (https://msdn.microsoft.com/en-us/library/haa3afyz(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2)
If Password.HasRows Then
Do While Password.Read()
EmailMessage.Body = ("Your password is: " & Password.GetString(0))
Loop
Else
Console.WriteLine("No rows found.")
End If
I would also recommend changing the Password SQLDataREader to a different name, just to make it less confusing.

How to Update Password

I'm trying to change a password. Can you look for this and tell what's wrong? Some times I get a Syntax error in the UPDATE statement or even it is working the password didn't change in database. Here's my code:
Dim sqlquery As String = "UPDATE tblLogin SET pword = ? WHERE pword = '" & txtnewpass.Text & "' "
Dim sqlcmd As New OleDbCommand(sqlquery, con)
sqlcmd.Parameters.AddWithValue("#pword", txtnewpass.Text)
con.Open()
sqlcmd.ExecuteNonQuery()
con.Close()
MessageBox.Show("Your password has been changed", "Change Password", MessageBoxButtons.OK, MessageBoxIcon.Information)
Thank you for your help
I don't know VB and VB SQL Syntax by heart, but a Quick Look at your code shows that there are at least two mistakes.
"UPDATE tblLogin SET pword = ?
should be
"UPDATE tblLogin SET pword = #pword
The
WHERE pword = '" & txtnewpass.Text & "' "
should be
WHERE pword = '" & txtoldpass.Text & "' "
Or make it with #param as well. You are trying to change password which doesn't exists yet.
Besides that, passwords should be encrypted in the database, and you shouldn't match (where clause) just by password. What if 2 users have the same password? You will change both user's passwords;)