VB Login form ASP.NET with membership or similar - sql

need some minor help with declaring a new array that could read the sql username of the user (if logged in) and store it for later use, either to use it for pages that only authorized users could see (with simple if commands) or lockdown the whole site with web.config authorization system that would allow roles only for admins.
My code is this
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
If Page.IsValid Then
' check for username & password in the database
Dim conn As New SqlConnection("Data Source=.;Initial Catalog=SoftCoD;User ID=sa;Password=fouf")
' Get the row corresponding the given username and password
Dim strSQL As String = "Select * From users Where Name='" + txtUname.Text + "' and Password = '" + txtPassword.Text + "'"
'I recommend not to use * in querys
Dim dsc As New SqlClient.SqlCommand(strSQL, conn)
conn.Open()
Dim dr As SqlDataReader
dr = dsc.ExecuteReader()
If dr.HasRows = True Then
dr.Read()
*g_sUser=Name????MsgBox(g_sUser)*
Response.Redirect("Default.aspx")
Else
Response.Redirect("login.aspx")
End If
conn.Close()
End If
End Sub

You can use any of the following method for holding the username for future use
Session
QueryString
Method 1 : Session
dr = dsc.ExecuteReader()
If dr.HasRows = True Then
dr.Read()
session("user")= g_sUser
Response.Redirect("Default.aspx")
Else
Response.Redirect("login.aspx")
End If
Method 2 : QueryString
dr = dsc.ExecuteReader()
If dr.HasRows = True Then
dr.Read()
Response.Redirect("Default.aspx?username=g_sUser")
Else
Response.Redirect("login.aspx")
End If

Related

a beginner in vb.net.. working on a login form

Imports MySql.Data.MySqlClient
Public Class Form1
Dim cmd As New MySqlCommand
Dim da As New MySqlDataAdapter
Dim con As MySqlConnection = JOKENCONN()
Public Function JOKENCONN() As MySqlConnection
Return New MySqlConnection("server=localhost; user id=root; password=; database =studentdb")
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
GroupBox1.Enabled = False
End Sub
Private Sub LBLLOGIN_CLICK(sender As Object, e As EventArgs) Handles lbllogin.Click
lbllogin.Text = "Login"
lbllogin.Text = "Login"
lblname.Text = "Hi, Guest"
If lbllogin.Text = "Login" Then
GroupBox1.Enabled = True
End If
End Sub
Private Sub BTNOK_CLICK(sender As Object, e As EventArgs) Handles btnok.Click
Dim Sql As String
Dim publictable As New DataTable
Try
If txtusername.Text = "" And txtpass.Text = "" Then
MsgBox("Password or username is incorrect!")
Else
Sql = "select ' from tbluseraccount where username='" & txtusername.Text & "' and userpassword='" & txtpass.Text & "'"
With cmd
.Connection = con
End With
da.SelectCommand = cmd
da.Fill(publictable)
If publictable.Rows.Count > 0 Then
Dim user_type As String
user_type = publictable.Rows(0).Item(4)
Name = publictable.Rows(0).Item(1)
If user_type = "Admin" Then
MsgBox("Welcome " & Name & "you login as Administrator")
lbllogin.Text = "logout"
lblname.Text = "Hi, " & Name
GroupBox1.Enabled = False
txtusername.Text = ""
txtpass.Text = ""
ElseIf user_type = "cetakoradi2" Then
MsgBox("Welcome " & Name & "you login as cetakoradi2")
lbllogin.Text = "logout"
lblname.Text = "Hi, " & Name
GroupBox1.Enabled = False
txtusername.Text = ""
txtpass.Text = ""
Else
End If
Else
MsgBox("contact administrator to register")
txtusername.Text = ""
txtpass.Text = ""
End If
da.Dispose()
End If
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
End Sub
End Class
this the error i received
ExecuteReader CommandText property has not been properly initialized
i really need help on that. this is the error that i receives. thank you
Assuming that the name of the field represented in publictable.Rows(0).Item(4) is named user_type, then you could use the following:
'Declare the object that will be returned from the command
Dim user_type As String
'Declare the connection object
Dim con As OleDbConnection
'Wrap code in Try/Catch
Try
'Set the connection object to a new instance
con = JOKENCONN()
'Create a new instance of the command object
Using cmd As OleDbCommand = New OleDbCommand("SELECT user_type FROM tbluseraccount WHERE username=#0 AND userpassword=#1;", con)
'Paramterize the query
cmd.Parameters.AddWithValue("#0", txtusername.Text)
cmd.Parameters.AddWithValue("#1", txtpass.Text)
'Open the connection
con.Open()
'Use ExecuteScalar to return a single value
user_type = cmd.ExecuteScalar()
'Close the connection
con.Close()
End Using
Catch ex As Exception
'Display the error
Console.WriteLine(ex.Message)
Finally
'Check if the connection object was initialized
If con IsNot Nothing Then
If con.State = ConnectionState.Open Then
'Close the connection if it was left open(exception thrown)
con.Close()
End If
'Dispose of the connection object
con.Dispose()
End If
End Try
If (String.IsNullOrWhitespace(user_type)) Then
'Failed login
ElseIf (user_type = "Admin") Then
'Admin login
ElseIf (user_type = "cetakoradi2") Then
'cetakoradi2 login
Else
'Not a failed login, but also not an admin or cetakoradi2 either
End If
What this code does is setup a parameterized query to get just the user_type where the username and password match the parameterized values. Since there should only ever be one record that matches those conditions (presumably) then we're able to use ExecuteScalar to return just that single field value.
Just to reinforce the point, MySqlCommand.ExecuteScalar, just like the Microsoft counterparts, "executes the query, and returns the first column of the first row in the result set returned by the query. Extra columns or rows are ignored" and returns " The first column of the first row in the result set, or a null reference if the result set is empty ".
The proposed code by #David checks for this condition using IsNullOrWhitespace.
ExecuteScalar is effective but retrieves only one value at a time.
The other option pursued by the OP is to return a datarow, which is a valid approach if he wants to return several fields at the same time. In his example he retrieves two fields for variables user_type and Name respectively.
Be careful, VB.net like any other programming language has reserved keywords. If you do not take a habit of using good naming conventions you might one day stumble upon on one of those keywords, possibly hit obscure bugs. Name is not a good name for a variable and has the potential for confusion since every object has a name property.
To address the specific issue at hand, the error message ExecuteReader CommandText property has not been properly initialized is self-explanatory. What should have been done is simply:
With cmd
.Connection = con
.CommandText = Sql
End With
You defined a command, but did not tell it what to do. In your code variable Sql is defined but unused. With this missing bit there is a chance the code will work as expected.
Small details:
Not critical, but his condition does not work if you enter whitespace for example:
If txtusername.Text = "" And txtpass.Text = "" Then
An improvement is to simply trim the values from the textboxes:
If txtusername.Text.Trim = "" And txtpass.Text.Trim = "" Then
But I think what you want is not an And but Or. I don't think you want to allow logins without passwords.
Instead of doing multiple If/ElseIf you could have a Select Case

simple login form error VB 2010

I've search a lot of resources and couldn't fix it.
My problem is when I click the button event the next form doesn't show and also I want to close my login form at the same time.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim firstname As String = ""
Dim lastname As String = ""
Dim ara As Boolean = False
cn = New OleDbConnection(con)
cn.Open()
Dim user As String
Dim pass As String
user = TextBox1.Text
pass = TextBox2.Text
With cmd
.Connection = cn
.CommandText = "Select * from users WHERE username='" & user & "' AND password='" & pass & "'"
.ExecuteNonQuery()
rdr = cmd.ExecuteReader
If rdr.HasRows Then
ara = True
While rdr.Read()
firstname = rdr("firstname").ToString
lastname = rdr("lastname").ToString
lib_name = firstname + lastname
End While
If ara = True Then
Form2.Show()
Me.Close()
x = True
Else
MsgBox(" Access Denied!" + Environment.NewLine + "Sorry, username or password is incorrect!")
End If
End If
End With
cn.Close()
cmd.Dispose()
1 : You are opening the gates of SQL INJECTION. Read more . Instead of passing values directly in your query, pass parameters first and use them later(For unknown reason, the code formatting is not working below) :
Dim cmd as New OleDbCommand("Select * from users WHERE username=#user AND password=#pass" , con)
With cmd
.Parameters.Add("#user", OleDbType.Varchar).Value = user
.Parameters.Add("#user", OleDbType.Varchar).Value = password
End With
2 : Your If statement will only work IDateReader.HasRows returns true and if ara=True which is unnecessary. .HasRows is a boolean, you don't need to create another boolean and pass the value to it. However, the rest of your code will only execute if your conditions match
3 : Form1.Close and AnotherForm.Show will never work if in your Project Proerties , Shutdown Mode is set to On main window close(by default). Either change it to On Explicit window close or On last window close or change
Me.CLose To
Me.Hide
4 : In order to reduce too much code , you can use Using Statement :
Using cmd as New SqlCommand("Select * from users WHERE username=#user AND password=#pass" , con)
'''codes here
End Using
''Now no need to call cmd.Dispose
Hope this helps :)

Multiple User Registration Form vb.net

I have a user registration form for multiple users. This works fine except the code is unable to identify if there is already username exist. I know there is mistake in my code but I am unable to rectify that one.
Code is below can anyone help me sort this, how to write modify code for reader
Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click
Dim user, pass As String
user = UsernameTextBox.Text
pass = PasswordTextBox.Text
Dim connection1 As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=Credentials.mdb;")
Dim command As New OleDbCommand("SELECT [ID] FROM [Staff] WHERE [usernameField] = username AND [passwordField] = password", connection1)
Dim usernameParam As New OleDbParameter("username", Me.UsernameTextBox.Text)
Dim passwordParam As New OleDbParameter("password", Me.PasswordTextBox.Text)
command.Parameters.Add(usernameParam)
command.Parameters.Add(passwordParam)
command.Connection.Open()
Dim reader As OleDbDataReader = command.ExecuteReader()
If reader.HasRows Then
MessageBox.Show("User Exist")
MyPlayer.SoundLocation = path & LogOnsound
PasswordTextBox.Text = ""
UsernameTextBox.Text = ""
ElseIf user = "" Or pass = "" Then
MsgBox("Please Fill The Boxs", , "Error")
Else
Dim connection As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Credentials.mdb;"
Using myconnection As New OleDbConnection(connection)
myconnection.Open()
Dim sqlq As String = "INSERT INTO [staff] ([username], [password]) VALUES (#user, #pass)"
Using cmd As New OleDbCommand(sqlq, myconnection)
cmd.Parameters.AddWithValue("#usernme", user)
cmd.Parameters.AddWithValue("#passwrd", pass)
cmd.ExecuteNonQuery()
MsgBox("User Registered!", , "register")
user = ""
pass = ""
End Using
End Using
End If
command.Connection.Close()
End Sub
It looks like you have multiple things wrong:
You should be specifying #username instead of just username in your SELECT statement so that it will be recognized as a parameter.
Why are you checking for a match on password also? If you do that, people can have the same username with just a different password...do you want that?
In your SELECT, you have usernameField as the column name in your Staff table, but in your INSERT, you have username as the column name. Which is it?
In your INSERT, you specify the parameter #user, but in your cmd.Parameters.AddWithValue statement, you have #usernme.

How to update the account table?

I need help with my update query. I need to finish this by tomorrow. I think my codes are wrong.
My form:
My database:
My code:
'user wants to change password
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As New OleDbConnection
connection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\db1.accdb;Persist Security Info=True")
Try
connection.Open()
Dim command As OleDbCommand = connection.CreateCommand
command.CommandType = CommandType.Text
command.CommandText = "Update UserAccount SET Password ='" + TextBox2.Text + "' WHERE Username = User"
command.ExecuteNonQuery()
MsgBox("Updated")z
TextBox2.Text = ""
TextBox3.Text = ""
Catch ex As Exception
MsgBox(ex.Message)
End Try
Common mistake. The problem is here:
... WHERE Username = User"
It's looking for a field named User.
Is the username actually User? If so, wrap it in quotes:
... WHERE Username = 'User'"
Is User actually a variable holding the username? If so:
... WHERE Username = '" & User & "'"

How to make log in code in vb.net

Hello Guys please help me about this code,
This is simple log in code in visual studio 2013, my problem is, i try to make wrong password and user name, but the message box does not shows, it means no event after the "else"
HERE IS MY CODE:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnEnter.Click
Dim dr As OleDbDataReader
Call OpenDB()
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM smcUser WHERE UserName = '" & txtTeacher.Text & "'AND UserPass ='" & txtPword.Text & "'")
cmd.Connection = conn
dr = cmd.ExecuteReader
If dr.HasRows = True Then
dr.Read()
If dr.Item("UserName") = txtTeacher.Text And dr.Item("UserPass") = txtPword.Text Then
frmMain.Show()
Me.Hide()
Else
MsgBox("You are not a Registered Teacher")
End If
End If
dr.Close()
frmMain.StatusStrip1.Items(0).Text = txtTeacher.Text
Call CloseDB()
End Sub
Your issue is that your query "SELECT * FROM smcUser WHERE UserName = '" & txtTeacher.Text & "'AND UserPass ='" & txtPword.Text & "'" does not return anything when you enter the wrong password, so it never even executes the code within the If dr.HasRows = True Then block.
Also, you should NEVER store passwords in plain text. Hash them. And, you should always use parameters to preclude SQL injection attacks.
So, you would want to change your code to something like this:
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM smcUser WHERE UserName = #UserName AND UserPass = #HashedPassword")
cmd.Parameters.Add(New OleDbParameter("#UserName", txtTeacher.Txt))
cmd.Parameters.Add(New OleDbParameter("#HashedPassword", HasherFunction(txtPword.Txt)))
Note the addition of the parameters and also the HasherFunction which you would have to build to hash your password accordingly.
There are plenty of resources available about SQL injection and how to avoid it. Here's one I found at the top of the Google search: https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
you almost there in your code, just don't repeat the checking if the user exists in the database, and you code should be like this based on what you put in the question
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnEnter.Click
Dim dr As OleDbDataReader
Call OpenDB()
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM smcUser WHERE UserName = '" & txtTeacher.Text & "'AND UserPass ='" & txtPword.Text & "'")
cmd.Connection = conn
dr = cmd.ExecuteReader
If dr.HasRows = True Then
' you don't need to check again if the user and password are same since you made it
' in you query to database
frmMain.Show()
Me.Hide()
Else
MsgBox("You are not a Registered Teacher")
End If
dr.Close()
frmMain.StatusStrip1.Items(0).Text = txtTeacher.Text
Call CloseDB()
End Sub
hope it will help you