show user's details from table on aspx when logged in - asp.net

I posted a similar question previously but quickly deleted it as the question had a number of errors and was not clear for readers.
I am creating a log in for a patient and when logged in (from the log in page login.aspx) I want them to be redirected to a page (in this case user.aspx) when the log in is authenticated and show their details from a table.
So far I can just get a label to provide user logged in correct or user log in incorrect.
I have a patient table as follows - this is all dummy data and made up user/accounts:
This is the code behind file, have I set a session correctly? and how when the user is authenticated can they be redirected to user.aspx with their corresponding details from a table (for instance their user details)
Imports System.Data.SqlClient
Imports System.Data
Partial Class Pages_Login
Inherits System.Web.UI.Page
Protected Sub btnlogin_Click(sender As Object, e As EventArgs) Handles btnlogin.Click
Dim patientNo As String
Dim password As String
Dim bAuthethicated As Boolean
patientNo = txtuser.Text
password = txtpassword.Text
bAuthethicated = CheckUser(patientNo, password)
If bAuthethicated Then
lblresult.Text() = "correct"
Else
lblresult.Text() = "Incorrect Student Number and/or Password"
End If
End Sub
Public Function CheckUser(patientNo As String, password As String) As Integer
Dim cmdstring As String = "SELECT * FROM Patient Where Username=#PATIENTNO AND Password=#PASSWORD"
Dim found = 0
Using conn As New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Laura\Final_proj\App_Data\surgerydb.mdf;Integrated Security=True;Connect Timeout=30")
Dim cmd = New SqlCommand(cmdstring, conn)
cmd.Parameters.Add("#PATIENTNO", SqlDbType.NChar).Value = patientNo
cmd.Parameters.Add("#PASSWORD", SqlDbType.NChar).Value = password
conn.Open()
Dim reader = cmd.ExecuteReader()
While reader.Read()
Session("PatientId") = CInt(reader.Item("PatientId"))
found = CInt(reader.Item("PatientId"))
End While
reader.Close()
End Using
Return (found)
End Function
End Class
I hope someone can help. If I can provide any more information or direction on the question please let me know.

Rather than showing the user that they have successfully logged in, just add the following line of code to redirect them to the user.aspx page:
Response.Redirect("user.aspx", True)
On the user page, you need to check if the Session("PatientId") is empty, if so, then redirect back the login page. If it does have a value, ensure it is a number and then use it to load up the patient details with another DB call.
Also another tip, I noticed your passwords are in plain text. I would highly recommend that you one-way hash them using a simple function for additional security. You can then use the same function to hash the password used on the login page to compare against the database value.

Related

ASP.NET Membership provider password in email replace

We use the built in asp.net membership provider to handle users accounts. The default temporary passwords that the provider creates are a little too complex for our users so I've used the below code to generate one that's a little easier to key in so that they can reset their passwords. It's working perfectly to generate the new passwords and the membership provider is using it instead of the complex one.
Here is where my issue is: When the users request a temporary password the application emails it to them. I'm trying to replace the temporary password with the one I'm generating. You can see in the below screenshots that the password I generate appends to the bottom of the email but I can't get the <%Password%> to be replaced with my new one. What am I missing?
Public Sub PasswordRecovery1_SendingMail(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.MailMessageEventArgs) Handles PasswordRecovery1.SendingMail
Dim User As MembershipUser = Membership.GetUser(PasswordRecovery1.UserName)
Dim msg As String = e.Message.Body
Dim oldpswd As String = User.ResetPassword()
Dim newpass As String = GetPassword()
msg.Replace("<%Password%>", newpass)
msg += "<p>Your new password is: " & newpass & "</p>"
User.ChangePassword(oldpswd, newpass)
e.Message.Body = msg
End Sub
Email Template I'd like to update with newpass
Email that goes to user still has old password and new one at the bottom
Replaced the "<%Password%>" with "<-TemporaryPasswordArea>" in my template, then changed the msg assignment to the following and it's replacing it correctly in the email.
msg = msg.Replace("<-TemporaryPasswordArea>", newpass)

ASP.net Coding User Roles into Login Page

I've developed a login page, which functions off of a stored procedure. The login part functions well, however, the website will consist of roles that will determine what page the user is directed to once they are logged into the secure section. The columns I’m focusing on in the database / table are:
Guid -0 column
Login_name -9th column
Login_Pwd -10th column
Role_ID -11th column / Contains a value of 1 or a 2
What I’m trying to do is: get the login page to distinguish between the users with a Role_ID of 1 and those that have a Role_ID of 2. But, currently, when I log into the page, I’m directed to the SecurePage.aspx regardless of what Role ID the user has. Could I please get some direction on this?
This is my Stored Procedure:
ALTER PROCEDURE [dbo].[Check_Users]
#Login_name as varchar(100),
#Login_Pwd as varchar(50)
AS
/* SET NOCOUNT ON */
SELECT * FROM SupplierCompany WHERE Login_name=#Login_name AND Login_Pwd=#Login_Pwd
RETURN
This is the code behind my login button:
Try
Dim con As New SqlConnection(GetConnectionString())
con.Open()
Dim cmd As New SqlCommand("Check_Users", con)
cmd.CommandType = CommandType.StoredProcedure
Dim p1 As New SqlParameter("Login_name", username.Text)
Dim p2 As New SqlParameter("Login_Pwd", password.Text)
cmd.Parameters.Add(p1)
cmd.Parameters.Add(p2)
Dim rd As SqlDataReader = cmd.ExecuteReader()
If rd.HasRows Then
rd.Read()
lblinfo.Text = "You are Authorized."
FormsAuthentication.RedirectFromLoginPage(username.Text, True)
Response.Redirect("securepages/SecurePage.aspx")
Else
lblinfo.Text = "Invalid username or password."
End If
'check the Role of the usre logging in
While (rd.Read())
Session("numrecord") = rd.GetValue(0).ToString()
rd.GetValue(11).ToString()
If rd.GetValue(11).ToString() = 1 Then
Response.Redirect("securepages/SecurePage.aspx")
ElseIf rd.GetValue(11).ToString() = 2 Then
Response.Redirect("securepages/newShipment.aspx")
End If
End While
Catch
Finally
End Try
..Any assistance is greatly appreciated.
Inside your If rd.HasRows Then you redirect to the SecurePage, so I'm guessing it doesn't even reach the while. Try removing the Response.Redirect("securepgaes/SecurePage.aspx") inside this if, and adding the while loop there, like this:
If rd.HasRows Then
rd.Read()
lblinfo.Text = "You are Authorized."
FormsAuthentication.RedirectFromLoginPage(username.Text, True)
'Response.Redirect("securepages/SecurePage.aspx") Remove this line
'check the Role of the user logging in
While (rd.Read())
Session("numrecord") = rd.GetValue(0).ToString()
rd.GetValue(11).ToString()
If rd.GetValue(11).ToString() = 1 Then
Response.Redirect("securepages/SecurePage.aspx")
ElseIf rd.GetValue(11).ToString() = 2 Then
Response.Redirect("securepages/newShipment.aspx")
End If
End While
Else
lblinfo.Text = "Invalid username or password."
End If
Where have you defined the code to redirect the logged in user?
The Login control by default will try and redirect you to a destination page once successful. I would think you should hook in to the OnLoggedIn event and redirect the page before the server has a chance to do it for you.
As an alternative if that doesn't work you could try building your own 'Login Control' - since you are using a stored procedure to validate users anyway, it's not a huge leap to dump a few textboxes on the page and go that way. At least then you don't need to worry about overriding the default behaviour. I believe ASP.NET provides a bunch of SPs you can use which will validate user passwords and such - check it out on the server (they are all like dbo.aspnet_*.

Evaluating whether a page is the result of a referral from a particular page

I have an Edit Profile page which allows users to change their information - currently it only allows users who have a record in the table 'userprofiles' to edit their information. I want newly registered users to be able to edit their profiles as well.
At the minute, I am using the ASP.NET membership system with the appropriate asp.net_ tables in an Access database to store user credentials. The 'userprofiles' table is a separate table which has more personal information in it. There is no link between the two tables
Here is my code behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If IsCrossPagePostBack Then
SeparateNewUserFunction()
Return
End If
If Not IsPostBack Then
DisplayData()
SaveConfirmation.Visible = False
End If
End Sub
And here is my DisplayData() function just if anyone was interested as to what it does:
Protected Sub DisplayData()
Dim conn As OleDbConnection = New OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
Dim sql = "SELECT * FROM userprofiles WHERE TravellerName=#f1"
Dim cmd = New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#f1", User.Identity.Name)
conn.Open()
Dim profileDr = cmd.ExecuteReader()
profileDr.Read()
Dim newEmailAddress = ""
Dim newDescription = ""
If Not IsDBNull(profileDr("EmailAddress")) Then newEmailAddress = profileDr.Item("EmailAddress")
If Not IsDBNull(profileDr("Description")) Then newDescription = profileDr.Item("Description")
If Not IsDBNull(profileDr("AvatarURL")) Then ProfilePic.ImageUrl = profileDr.Item("AvatarURL")
description.Text = newDescription
email.Text = newEmailAddress
conn.Close()
End Sub
Rather than checking if a record exists in the 'userprofiles' table that matches the User.Identity.Name of the current user, I thought it would be easier just to evaluate whether or not the user had just been redirected from the Register.aspx page. (If this evaluation is true, then as you can see above, a separate "New User" function will be called).
That is my logic, but I have no clue if VB.NET has a "referrer" or "isReferred" expression? (at the minute as you can see I thought isCrossPagePostback might be the right thing but no luck!)
Any ideas?
You need to check whether or not a record exists and base your logic on that. That is the only right way to do it. As in:
What if you introduce a new page to handle registrations? This logic breaks.
What if you one day you retire and the next guy decides to rename the Register.aspx page? This logic breaks.
What if user hits back button and clicks the Register button again? This logic may break.
You should also consider a foreign key and unique constraint on that table, as well as using UserId instead of TravellerName. TravellerName can change, UserId will not.
... and yes you can the referring page by using HttpRequest.ServerVariables, which gets you a list of IIS Server Variables.

How can I transfer login value to another page?

I am a newbie in using asp.net with code behind of vb.net I just wanna know on how to see the name of the admin on the POS page. it seems that this code doesn't work??
Main.lbl_name.Text = CurName.ToUpper
POS.lbl_cashier.Text = CurName.ToUpper
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cmd1 As New SqlCommand
Dim rdr As SqlDataReader
cmd1.Connection = cn
cmd1.Connection.Open()
cmd1.CommandText = "SELECT * from UserTable WHERE Username ='" & txt_username.Text & "'"
rdr = cmd1.ExecuteReader
If rdr.HasRows = True Then
rdr.Read()
If txt_username.Text = rdr.Item(0) And txt_password.Text = rdr.Item(3) Then
CurPos = rdr.Item("Type")
CurUser = rdr.Item("Username")
CurName = rdr.Item("EmployeeName")
If rdr.Item(4) = "ADMINISTRATOR" Then
MsgBox("WELCOME! " & rdr.Item(4), MsgBoxStyle.Information)
'Main.lbl_name.Text = CurName.ToUpper
'POS.lbl_cashier.Text = CurName.ToUpper
cmd1.Connection.Close()
Response.Redirect("ACESCHOOLSUPPLIES.aspx")
'Me.Dispose()
You can't just access other pages, ASP.NET runtime is ignorant about other pages, you have access to your current page only!
You can use the Session variable to store some data temporarily for current user session, the Session object is available on every ASP.NET Page.
Session("adminname") = CurName
On other page where you want to show it you just reload it from Session
Dim NewName = Session("adminname")
Take some hidden field and use session.add("username") and store your username or which ever you want and the n retrieve that from your second page.
Session.Add("Username",Username);
does essentially the same as
Session["Username"] = Username;
As Alaudo suggested, storing variables in Session state is an option.
For the sake of completeness other options you have are:
Cookies
QueryString
Hidden fields (for POST requests)
The logged on user name is something I personally would not store in Session state or pass around using any of the alternate techniques I mention above.
Looking at your code it seems you are trying to authenticate some credentials (user name/password).
I recommend you look at MemebershipProvider in ASP.NET. Are you familiar with this? You can then easily access the logged in user.

Insert asp.net Membership-generated UserId into custom table (vb)

I've spent a couple of hours trying to find the answer to this, and although there are tutorials all over the 'net none of them work for me (or I am too n00b to understand what they're telling me...)
Anyway, I'm creating users in asp.net using Membership. What I want to do is add the generated UserId to a column in a custom table I've created, to link the stuff in the custom table with the user created in aspnet_Users.
Here's the code I've got for the registration submit button:
Private Sub submit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submit.Click
Dim connectionString As String = WebConfigurationManager.ConnectionStrings("edinsec").ConnectionString
Dim createStatus As MembershipCreateStatus
Membership.CreateUser(fname.Text, password.Text, email.Text, sq.Text, sa.Text, False, createStatus)
''#Something has to happen here!
Dim insertSQL As String
insertSQL = "INSERT INTO clients (UserId)"
insertSQL &= "VALUES (#userId)"
Using con As New SqlConnection(connectionString)
Dim cmd As New SqlCommand(insertSQL, con)
cmd.Parameters.AddWithValue("#firstname", firstname.Text)
Try
Try
con.Open()
Catch ex As SqlException
MsgBox("Connection Problem - Please Retry Later", 65584, "Connection Error")
End Try
cmd.ExecuteNonQuery()
MsgBox("Thank you for joining us - we will be in touch shortly.", 65600, "Join Up")
Response.Redirect("Default.aspx")
Catch Err As SqlException
MsgBox("Error inserting record - please retry later.", 65584, "Insertion Error")
End Try
con.Close()
End Using
End Sub
As you can see I'm trying to grab the Membership-generated userid and insert it into the clients table. I've tried numerous approaches to grabbing the UserId but none work.
Membership works to create the user, it's just the part afterwards that I'm stuck on.
Any help would be much appreciated :)
I managed it in the end using this code:
Dim userid As Guid = New Guid(Membership.GetUser(username.Text).ProviderUserKey.ToString())
...where username.Text is the content of the username form input, where the user chooses their username.
The relevant parameter line is this:
cmd.Parameters.Add("#UserId", g)
I get a warning about the method I'm using being deprecated, but it works at least!
Membership.CreateUser returns a MembershipUser object. You can get the UserId from that returned object.
MembershipUser user = Membership.CreateUser(...);
Guid userId = (Guid)user.ProviderUserKey;

Resources