restrict access to a .net page without a valid session vb.net - mysql

I currently have a login page login.aspx that copies "affID" into a session and uses it on another page dashboard.aspx
login.aspx file looks like this :
Dim Query As String
Query = "select * from mdxmain.taffiliate where affID = '" & username.Text & "' and affPassword = '" & password.Text & "'"
COMMAND = New MySqlCommand(Query, MysqlConn)
Session("affID") = username.Text
READER = COMMAND.ExecuteReader
Dim count As Integer
count = 0
While READER.Read
count = count + 1
End While
If count = 1 Then
Response.Redirect("dashboard.aspx")
Else
Literal1.Text = "Invalid credentials"
End If
MysqlConn.Close()
Finally
End Try
MysqlConn.Dispose()
dashboard.aspx session load file looks like this :
Dim userid As String = HttpContext.Current.Session("affID")
I need help with not allowing access to the dashboard.aspx file without having a valid session. Also how to timeout the session after 2minutes

In your dashboard page_load event, check if the session variable is nothing, if it is, then redirect to your login page.
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim userid As String = HttpContext.Current.Session("affID")
if ( userid is Nothing) then
Response.Redirect("login.aspx")
end if
End Sub
Update
For the timeout there is some good information here

Related

How to store user's information for future use from MySQL

I have a very simple application where a user will login and be redirected to the dashboard. I got the login part working, however, my next goal is to be able to store the users information for later use on other forms.
Example: User "admin" logs in successfully. I need to be able to store every column in the table for admin so that we can call the user's information for welcome messages, user information form, etc without having to query the database everytime.
I believe this can be accomplished with a class, however, I'm unsure how to rewrite my login script to save all details into a class.
I've tried creating a class, and adding Public Shared properties for each column but I'm not sure how to get every column into the class rather than just the username.
Imports MySql.Data.MySqlClient
Public Class frmLogin
'count is number of invalid login attempts
Dim count As Integer
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
count = count + 1
Dim x As New MySqlConnection
Dim admin As New MySqlCommand
Dim dr1 As MySqlDataReader
ConnectDatabase()
admin.Connection = conn
admin.CommandText = "SELECT user.username, user.password FROM user WHERE user.username = '" & txtUsername.Text & "' and user.password = '" & txtPassword.Text & "'"
dr1 = admin.ExecuteReader
If dr1.HasRows Then
'Read the data
dr1.Read()
Me.Hide()
frmDashboard.Show()
Else
MsgBox("Invalid Username or Password! " & vbCrLf & count & " out of 3 attempts remaining.")
If count >= 3 Then
MsgBox("You have exceeded the maximum number of attempts to login. Account has been disabled. Please contact OJFS helpdesk at extension 100.", MsgBoxStyle.Critical)
txtUsername.Enabled = False
txtPassword.Enabled = False
End If
End If
Connect.conn.Close()
End Sub
Dim Assistance As Boolean = False
Private Sub linkLoginHelp_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles linkLoginHelp.LinkClicked
If Assistance = True Then
Me.Height = 284
Me.CenterToScreen()
Assistance = False
txtUsername.Select()
Else
Me.Height = 463
Me.CenterToScreen()
Assistance = True
txtUsername.Select()
End If
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Application.Exit()
End Sub
End Class
The Using...End Using blocks ensure that your database objects are closed and disposed even if there is an error.
Of course in a real application you would NEVER store passwords as plain text.
Comments in line.
'Your class might look something like this
Public Class User
Public Shared ID As Integer
Public Shared Name As String
Public Shared Department As String
Public Shared Address As String
End Class
Private count As Integer
Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
count = count + 1
'keep connections local for better control
'pass the connection strings directly to the constructor of the connection
Using cn As New MySqlConnection("Your connection string")
'pass the query and the connection directly to the constructor of the commmand
Using cmd As New MySqlCommand("SELECT * FROM user WHERE user.username = #User and user.password = #Password;", cn)
'Always use parameters to avoid SQL injection
cmd.Parameters.Add("#User", MySqlDbType.VarChar).Value = txtUsername.Text
cmd.Parameters.Add("#Password", MySqlDbType.VarChar).Value = txtPassword.Text
'Open the Connection at the last possible minute.
cn.Open()
Using dr1 = cmd.ExecuteReader
If dr1.HasRows Then
dr1.Read()
'The indexes of the data reader depent on th order of the fields in the database
User.ID = CInt(dr1(0))
User.Name = dr1(1).ToString
User.Department = dr1(2).ToString
User.Address = dr1(3).ToString
Me.Hide()
frmDashboard.Show()
Return 'a successful login will end here
End If
End Using 'closes and disposed the reader
End Using 'close and disposes the command
End Using 'closes and dipose the connection
MsgBox("Invalid Username or Password! " & vbCrLf & count & " out of 3 attempts remaining.")
If count >= 3 Then
MsgBox("You have exceeded the maximum number of attempts to login. Account has been disabled. Please contact OJFS helpdesk at extension 100.", MsgBoxStyle.Critical)
btnLogin.Enabled = False 'Instead of the text boxes disable the button.
'If you just disable the text boxes they can keep clicking the button and opening connections.
End If
End Sub

Variables won't update in vb.net

I have a problem in my vb.net code, I have a login form that is connected to a mysql database. It can already check if the user is in the database, now the next thing to do is to get the name, access level and userId from the database according to the logged in account, I have store it in a module that holds a global variable.
This is my code.
Module pubvars
Public Gplev As String
Public Gname As String
Public GuserId As Integer
End Module
Then I will use this variables on other forms, in the first session of logging in the variables was read correctly,but when I logged out, then login with a new user account, the variable passed was not updated, which is supposedly changed as a new account was logged in.
Here is the code where I declare the variables.
Dim search1 As MySqlCommand = New MySqlCommand("SELECT * FROM `login` WHERE login.username = '" & TextBox1.Text & "' AND login.password = '" & TextBox2.Text & "'", con)
con.Open()
Dim dr As MySqlDataReader = search1.ExecuteReader
Dim userFound As Boolean = False
While dr.Read
userFound = True
pubvars.Gname = dr("name").ToString
pubvars.Gplev = dr("permission_level").ToString
pubvars.GuserId = dr("userId").ToString
End While
If userFound = True Then
main_menu.Show()
Me.Hide()
Else
MsgBox("Sorry, username or password not found", MsgBoxStyle.OkOnly, "Invalid Login")
TextBox1.Text = ""
TextBox2.Text = ""
End If
And here is the code where I used the variables in the second form.
Private Sub main_menu_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Label3.Text = pubvars.Gname
If pubvars.Gplev = "2" Then
Button8.Enabled = False
Button8.Visible = False
ElseIf pubvars.Gplev = "3" Then
Button8.Enabled = False
Button8.Visible = False
ElseIf pubvars.Gplev = "4" Then
Button8.Enabled = False
Button8.Visible = False
End If
End Sub
For logout I have the following code.Is this right or it is not enough for logout?
Private Sub Button7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button7.Click
pubvars.Gname = ""
pubvars.Gplev = "0"
login.Show()
Me.Hide()
End Sub
Move the login var assignment logic from Load event to Activated event. The Load event gets executed only once, when you load a Form for the first time.
The Activated event happens every time you display the form .Show(). If you move the code from Load event to Activated, you should fix the issue.

visual basic 2012 connection must be valid and open

What I have is a small messaging function that basically can send a message to one user or to a group of users. There are two mysql tables; one called users for the users who use the system, and another messages where the messages are stored. The system can send to specific users but when sending to a group of people, VB gives me the
InvalidOperationException was handled: connection should be open and valid
The code is given below.
Dim receiver, subject, message As String
Dim user As Integer
Dim MySqlConnection As New MySqlConnection
Dim MyAdapter As New MySqlDataAdapter
Dim command As New MySqlCommand
Dim mydata As MySqlDataReader
Private Sub sendButton_Click(sender As Object, e As EventArgs) Handles sendButton.Click
user = loginForm.user
If recieverTextBox.Text = "" And studentCheckBox.Checked = False And facultyCheckBox.Checked = True Then
subject = subjectTextBox.Text
message = messageRichTextBox.Text
MySqlConnection = New MySqlConnection
MySqlConnection.ConnectionString = "server=localhost; User ID=root; password=''; database=sis_db"
Dim query = "insert into messages (date, sender, receiver, subject, message) select CURRENT_DATE, '" & user & "',user_id,'" & subject & "', '" & message & "' from users where user_type='faculty';"
Try
MySqlConnection.Open()
command.CommandText = query
MyAdapter.SelectCommand = command
mydata = command.ExecuteReader 'the error message points here'
MsgBox("Messages sent", MsgBoxStyle.OkOnly, Title:="SUCCESS!")
recieverTextBox.Clear()
subjectTextBox.Clear()
messageRichTextBox.Clear()
Catch ex As MySqlException
MsgBox("DATABASE ERROR!")
End Try
MySqlConnection.Close()
ElseIf
you can replace the select current_date with DateTime.Now instead
have you tested the connection ? its probably just a typo

String from Database set as public string

Ok from the answer from the previous question the reasoning still applies here but this time A different issue. There is a login system (Loginvb.vb) that I got for the launcher I was creating and was wondering 2 things:
Is there a better way to do the Login check with the database (as in
more secure) (the login style will have a web based registration
setting via PHP script)?
Is there a way to take a certain column (labled as access) in the database and put it
as a public string so I can check if it will equal 1 2 or 3 in a
different form labeled as Main.vb
Here is the current login check:
Public Sub login_Click(sender As Object, e As EventArgs) Handles login.Click
If txtuserName.Text = "" Or txtpassWord.Text = "" Then
MsgBox("You cannot progress until you login....(moron =p)")
Else
'Connects To the Database
Dim connect As MySqlConnection
connect = New MySqlConnection()
connect.ConnectionString = "server=127.0.0.1;user id=sc;Password=derp;database=sclaunch" 'not the actual login ;)
Try
connect.Open()
Catch myerror As MySqlException
MsgBox("Error Connecting to Database. Please Try again !")
End Try
'SQL Query To Get The Details
Dim myAdapter As New MySqlDataAdapter
Dim sqlquerry = "Select * From login where username = '" + txtuserName.Text + "' And password= '" + txtpassWord.Text + "'"
Dim myCommand As New MySqlCommand()
'My fail attempt at what I am trying to do :(
Dim sql22 As MySqlConnection
sql22 = New MySqlConnection()
sql22.ConnectionString = "Select * From login where access ="
'End of fail attempt
myCommand.Connection = connect
myCommand.CommandText = sqlquerry
'Starting The Query
myAdapter.SelectCommand = myCommand
Dim mydata As MySqlDataReader
mydata = myCommand.ExecuteReader
'To check the Username and password and to validate the login
If mydata.HasRows = 0 Then
MsgBox("Invalid Login")
Else
'fail testing xD
Label3.Text = sql22
MsgBox("You are now Loged In!")
End If
End If
End Sub
Still basically learning more and more as I am coding all this got to love trial and error and the moments where you get stuck =/ (Sorry to the admins or whatever for fixing tag issues still new to the site xD)
Assuming that the same table login that contains the credentials contains also the access column that you want to retrieve, then I have changed a lot of your code
Dim sqlquerry = "Select * From login where username = #name AND password=#pwd"
Dim myCommand As New MySqlCommand(sqlquery, connect)
myCommand.Parameters.AddWithValue("#name", txtuserName.Text)
myCommand.Parameters.AddWithValue("#pwd", txtpassWord.Text)
Dim mydata = myCommand.ExecuteReader
If mydata.HasRows = False Then
MsgBox("Invalid Login")
Else
' the same record that contains the credentials contains the access field'
mydata.Read()
Label3.Text = mydata("access").ToString()
MsgBox("You are now Loged In!")
End If
What I have changed:
Removed the string concatenation and added the appropriate parameters
Removed myAdapter and every references to it (not needed, you don't
fill DataTable/DataSet)
Removed sql22 and every references to it. It's a Connection and you
try to use like a Command
Fixed the check on HasRows (Returns a boolean not an integer. Are you
using Option Strict Off?)

Limiting the time in and time out in a day in VB.NET?

I have developed a time monitoring system using fingerprint where the employee will scan his/her finger then it will record the time in and time out. But my problem is logging in and logging out by the employee is unlimited. Is there a solution where the employee can log in and log out ONCE IN A DAY? Every employee will log in and log out once. Here is my code for my Daily Time Record Form: (Im using visual studio 2010/Digital Persona UareU for my scanner)
Imports MySql.Data.MySqlClient
Imports System.Windows.Forms
Imports DPFP
Public Class frmDTR
Dim counter As Integer = 0
Dim oConn As New MySqlConnection(ConnectionString.ConnString)
Private matcher As DPFP.Verification.Verification
Private matchResult As DPFP.Verification.Verification.Result
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
Me.Close()
End Sub
Public Sub SEARCH_EMPLOYEE()
Try
'Load From DB
GlobalFunctions.db_connect()
Dim reader As MySqlDataReader
Dim command As MySqlCommand = connection.CreateCommand()
command.CommandText = "SELECT * FROM employee_records WHERE ID_Number='" & strid & "'" 'check tag number if existing
reader = command.ExecuteReader()
If (reader.HasRows) Then
While (reader.Read())
With Me
'plot the data into controls
.txtID.Text = reader(1).ToString
.txtFirst.Text = reader(2).ToString
.txtMiddle.Text = reader(3).ToString
.txtLast.Text = reader(4).ToString
.txtAge.Text = reader(5).ToString
.txtBday.Text = reader(6).ToString
.txtDepartment.Text = reader(7).ToString
.txtYear.Text = reader(8).ToString
.txtGender.Text = reader(9).ToString
.txtContact.Text = reader(10).ToString
.txtMobile.Text = reader(11).ToString
.txtEmail.Text = reader(12).ToString
'fetch image from database
Dim imgBytes() As Byte = reader("image") 'image field
Dim image As Bitmap = New Bitmap(New System.IO.MemoryStream(imgBytes)) 'convert binary to image
.ProfilePic.Image = image 'show picture to picture box
End With
Call LOG_EMP() 'look up if login /log out
Timer1.Enabled = True
End While
Else
'Me.lblStatus.Text = "ID not recognized!"
End If
Catch ex As Exception
MessageBox.Show("Error scanning: " & ex.Message)
End Try
GlobalFunctions.connection.Close()
End Sub
Public Sub LOG_EMP()
Try
' Load From DB
GlobalFunctions.db_connect()
Dim reader As MySqlDataReader
Dim command As MySqlCommand = connection.CreateCommand()
command.CommandText = "SELECT * FROM employee_logs WHERE ID_Number='" & strid & "' AND Time_Out='Null'"
reader = command.ExecuteReader()
If (reader.HasRows) Then
While (reader.Read())
End While
'logout
Call EMP_LOGOUT()
Else
'log in
Call EMPT_LOGIN()
End If
Catch ex As Exception
MessageBox.Show("Error scanning: " & ex.Message)
End Try
GlobalFunctions.connection.Close()
End Sub
'insert login data
Public Sub EMPT_LOGIN()
' Connect to Database
GlobalFunctions.db_connect()
Dim command As MySqlCommand
Dim transaction As MySqlTransaction
transaction = GlobalFunctions.connection.BeginTransaction()
Try
command = New MySqlCommand("INSERT INTO employee_logs values('','" & txtID.Text & "','" & txtFirst.Text & "','" & txtMiddle.Text & "','" & txtLast.Text & "','" & txtDepartment.Text & "','" & Date.Today & "','" & TimeOfDay & "','Null') ", GlobalFunctions.connection, transaction)
command.ExecuteNonQuery()
transaction.Commit()
'sms = txtFirst.Text & " Enter the Building Premises #" & Now 'actual sms
lblStatus.ForeColor = Color.Lime
Dim SAPI
SAPI = CreateObject("SAPI.spvoice")
SAPI.Speak("Welcome!" & txtFirst.Text)
Me.lblStatus.Text = "Successfully Logged IN! Welcome!" 'set status to login
'Will_SendSMS() 'send sms to number
Catch ex As MySqlException
MessageBox.Show("Error in inserting new record! Error: " & ex.Message, "Data Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
transaction.Rollback()
End Try
'close connections
GlobalFunctions.connection.Close()
End Sub
Public Sub EMP_LOGOUT()
' Connect to Database
GlobalFunctions.db_connect()
' Dim command As MySqlCommand
Dim transaction As MySqlTransaction
transaction = GlobalFunctions.connection.BeginTransaction()
Try
GlobalFunctions.execute_nonquery("Update employee_logs set Time_Out='" & TimeOfDay & "' WHERE ID_Number='" & strid & "' AND Time_Out='Null' AND Date='" & Date.Today & "'")
transaction.Commit()
'sms = txtFirst.Text & " Left the Building Premises #" & Now & "Powered by: " ' actual sms to be sent
lblStatus.ForeColor = Color.Lime
Dim SAPI
SAPI = CreateObject("SAPI.spvoice")
SAPI.Speak("Goodbye!" & txtFirst.Text)
lblStatus.Text = "Successfully Logged OUT! Goodbye!" ' set status to logout
'Will_SendSMS() 'send sms
Catch ex As MySqlException
MessageBox.Show("Error in updating a record! Error: " & ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error)
transaction.Rollback()
End Try
' close connections
GlobalFunctions.connection.Close()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
'counter for display
counter += 1
If counter = 6 Then
Call ClearTextBox(Me)
lblStatus.ForeColor = Color.Lime
Me.lblStatus.Text = "Please scan your finger....."
Lblverify.ForeColor = Color.Black
Lblverify.Text = "Status"
ProfilePic.Image = Nothing
Timer1.Enabled = False
counter = 0
End If
End Sub
Private Sub frmDTR_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
Try
Me.VerificationControl.Focus()
Catch ex As MySqlException
MessageBox.Show("System Error: " & ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Sub frmDTR_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
matcher = New Verification.Verification()
matchResult = New Verification.Verification.Result
Me.VerificationControl.Focus()
Dim SAPI
SAPI = CreateObject("SAPI.spvoice")
SAPI.Speak("Please scan your finger")
End Sub
Private Sub VerificationControl_OnComplete(ByVal Control As Object, ByVal FeatureSet As DPFP.FeatureSet, ByRef EventHandlerStatus As DPFP.Gui.EventHandlerStatus) Handles VerificationControl.OnComplete
Dim strSQL As String = "Select * from finger_template"
Dim oDa As New MySqlDataAdapter(strSQL, oConn)
Dim dt As New DataTable
Dim dr As DataRow
Try
oDa.Fill(dt)
For Each dr In dt.Rows
Lblverify.ForeColor = Color.Red
Lblverify.Visible = True
Dim bytes As Byte() = Nothing
bytes = dr.Item("byte_template")
Dim tmplate = New DPFP.Template()
tmplate.DeSerialize(bytes)
matcher.Verify(FeatureSet, tmplate, matchResult)
If matchResult.Verified Then
EventHandlerStatus = DPFP.Gui.EventHandlerStatus.Success
strid = dr.Item("Account_ID")
Call SEARCH_EMPLOYEE()
Exit For ' success
End If
If Not matchResult.Verified Then EventHandlerStatus = DPFP.Gui.EventHandlerStatus.Failure
Lblverify.Text = "Status"
lblStatus.Text = "Unrecognize fingerprint....."
Lblverify.ForeColor = Color.Red
lblStatus.ForeColor = Color.Red
Timer1.Start()
Next
Catch ex As Exception
End Try
End Sub
End Class
This is very nice that you are developing this logic. Actually I have come a crossed YOUR question. Now I can recommend you some vb.net code using back end MS ACCESS 2007 .well You just validate when an employee logged in then put this code after log In button or what ever you are using .
Dim cmd1 as oledbcommond
cmd1 = New OleDbCommand("SELECT * FROM LOGTIME WHERE timein<>null and timeout<>null and dt='" & Label8.Text & "' and eid='" & txtemid.Text & "' ", cn)
dr = cmd1.ExecuteReader()
If dr.Read Then
MessageBox.Show("Already this Employee ID contains today's attendance,now you can't Log again", "Information On Your ID", MessageBoxButtons.OK, MessageBoxIcon.Information)
cmd1.Dispose()
cn.Close()
Exit Sub
End If
just follow the steps
Use normal login button which will validate for user
then if the authenticate user then show his login time in another textbox in the same form.and
use one more textbox to show the logout time ,now
1)use two buttons a)button1 as logintime button and b)button2 as logout time button
2)Then write code to add the login time into the data base,and for ur better understanding put one message box too which will shows the"Time in added to the database" and after that put the above code which will validate the current day attendance if the employee wants to login twice or thrice in a day this code will not allow him to login again only once he/she can ... and code the above behind the login button
note:-keep in mind that all the procedure will work after the employee log out ..Hope this will help you out..