Login and retrieve user data from database

Please support our ASP.NET advertiser: $4.95 a Month - ASP.NET Web Hosting – Click Here!
Reply

Join Date: Nov 2005
Posts: 4
Reputation: miragefighter is an unknown quantity at this point 
Solved Threads: 1
miragefighter miragefighter is offline Offline
Newbie Poster

Login and retrieve user data from database

 
0
  #1
Nov 21st, 2005
Hi, I'm using asp.net together with vb.net. I am trying to develop:
1. a login page in asp.net, once user enter the correct username and password, this will be directed to the User page.
2. In User page, there will be some text fields of the user (eg. name and address), all these suppose to retrieve from SQL Server. In here, if the username is found in the database, his/her data will be displayed in the textboxes ( eg. name and address), if not, the textboxes remain empty. User can choose to edit or enter new data into the textboxes and submit back to the datadase.
3. Once updated, user can click "save and logout" to save the data and logout.
I've done the login part, but only in (2), I can't retrieve the user's data from databases based on User.Identity.Name. Any idea how to retrieve data based on user's username?
Thanks.
Reply With Quote Quick reply to this message  
Join Date: Jul 2005
Posts: 483
Reputation: campkev is an unknown quantity at this point 
Solved Threads: 19
campkev campkev is offline Offline
Posting Pro in Training

Re: Login and retrieve user data from database

 
0
  #2
Nov 23rd, 2005
What error messages/symptoms are you getting? Post code from where you think problem might be happening. If you want help with your homework, you are going to have to give us some details
Reply With Quote Quick reply to this message  
Join Date: Nov 2005
Posts: 4
Reputation: miragefighter is an unknown quantity at this point 
Solved Threads: 1
miragefighter miragefighter is offline Offline
Newbie Poster

Re: Login and retrieve user data from database

 
0
  #3
Nov 25th, 2005
The scenario:
At Login.aspx, user will enter username and password to login, this works perfectly, authenticating against database in SQL Server.

Here's the code:
Login.aspx
  1. <%@ Page Language="vb" AutoEventWireup="false" Codebehind="Login.aspx.vb" Inherits="LoginTest.Login"%>
  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  3. <HTML>
  4. <HEAD>
  5. <title>Login - Login Test</title>
  6. <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">
  7. <meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
  8. <meta name="vs_defaultClientScript" content="JavaScript">
  9. <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
  10. </HEAD>
  11. <body>
  12. <form Runat="Server" ID="Form1">
  13. <h2>Please Login:</h2>
  14. <asp:Label ID="lblMessage" ForeColor="Red" Font-Bold="True" Runat="Server" />
  15. <p>
  16. <b>Username:</b>
  17. <br>
  18. <asp:TextBox ID="txtUsername" Runat="Server" />
  19. <asp:RequiredFieldValidator ControlToValidate="txtUsername" Text="Required!" Runat="Server" ID="Requiredfieldvalidator1" />
  20. <p>
  21. <b>Password:</b>
  22. <br>
  23. <asp:TextBox ID="txtPassword" Runat="Server" TextMode="Password" />
  24. <asp:RequiredFieldValidator ControlToValidate="txtPassword" Text="Required!" Runat="Server" ID="Requiredfieldvalidator2" />
  25. <p>
  26. <asp:Button Text="Login!" OnClick="Button_Click" Runat="Server" ID="Button1" />
  27. <hr>
  28. </form>
  29. </body>
  30. </HTML>

Login.aspx.vb
  1. Imports System
  2. Imports System.IO
  3. Imports System.Web
  4. Imports System.Data.SqlClient
  5. Imports System.Collections
  6. Imports System.Web.Security
  7.  
  8. Public Class Login
  9. Inherits System.Web.UI.Page
  10. Protected WithEvents lblMessage As System.Web.UI.WebControls.Label
  11. Protected WithEvents txtUsername As System.Web.UI.WebControls.TextBox
  12. Protected WithEvents Requiredfieldvalidator1 As System.Web.UI.WebControls.RequiredFieldValidator
  13. Protected WithEvents txtPassword As System.Web.UI.WebControls.TextBox
  14. Protected WithEvents Requiredfieldvalidator2 As System.Web.UI.WebControls.RequiredFieldValidator
  15. Protected WithEvents Button1 As System.Web.UI.WebControls.Button
  16.  
  17. #Region " Web Form Designer Generated Code "
  18.  
  19. 'This call is required by the Web Form Designer.
  20. <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
  21.  
  22. End Sub
  23.  
  24. Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
  25. 'CODEGEN: This method call is required by the Web Form Designer
  26. 'Do not modify it using the code editor.
  27. InitializeComponent()
  28. End Sub
  29.  
  30. #End Region
  31.  
  32. Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  33. 'Put user code to initialize the page here
  34. Dim strLinkPath As String
  35.  
  36. If Not IsPostBack Then
  37. strLinkPath = String.Format("Register.aspx?ReturnUrl={0}", _
  38. Request.Params("ReturnUrl"))
  39. 'lnkRegister.NavigateUrl = String.Format(strLinkPath)
  40. End If
  41. End Sub
  42.  
  43. Sub Button_Click(ByVal s As Object, ByVal e As EventArgs)
  44.  
  45. If IsValid Then
  46. If DBAuthenticate(txtUsername.Text, txtPassword.Text) > 0 Then
  47. FormsAuthentication.RedirectFromLoginPage(txtUsername.Text, False)
  48. Response.Redirect("Success.aspx")
  49. End If
  50. End If
  51. End Sub
  52.  
  53. Function DBAuthenticate(ByVal strUsername As String, ByVal strPassword As String) As Integer
  54. Dim conMyData As SqlConnection
  55. Dim cmdSelect As SqlCommand
  56. Dim parmReturnValue As SqlParameter
  57. Dim intResult As Integer
  58.  
  59.  
  60. conMyData = New SqlConnection(ConfigurationSettings.AppSettings("connectionstring"))
  61. cmdSelect = New SqlCommand("DBAuthenticate", conMyData)
  62. cmdSelect.CommandType = CommandType.StoredProcedure
  63. parmReturnValue = cmdSelect.Parameters.Add("RETURN_VALUE", SqlDbType.Int)
  64. parmReturnValue.Direction = ParameterDirection.ReturnValue
  65. cmdSelect.Parameters.Add("@username", strUsername)
  66. cmdSelect.Parameters.Add("@password", strPassword)
  67. conMyData.Open()
  68. cmdSelect.ExecuteNonQuery()
  69. intResult = cmdSelect.Parameters("RETURN_VALUE").Value
  70. conMyData.Close()
  71. If intResult < 0 Then
  72. If intResult = -1 Then
  73. lblMessage.Text = "Username Not Registered!"
  74. Else
  75. lblMessage.Text = "Invalid Password!"
  76. End If
  77. End If
  78. Return intResult
  79. End Function
  80.  
  81. End Class
  82.  

Once successfully logged in, user will be directed to this page "Success.aspx", and the page should be able to retrieve the user's details from the database, in this case the password of the user is to be displayed. However, my program can't retrieve and display the user's password in the textbox/label. Note: connectionstring is stored in web.config.
Some of the SQL is stored in the stored procedures.

Successful.aspx
  1. <%@ Page Language="vb" AutoEventWireup="false" Codebehind="Success.aspx.vb" Inherits="LoginTest.Success"%>
  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  3. <HTML>
  4. <HEAD>
  5. <title>Success</title>
  6. <meta content="Microsoft Visual Studio.NET 7.0" name="GENERATOR">
  7. <meta content="Visual Basic 7.0" name="CODE_LANGUAGE">
  8. <meta content="JavaScript" name="vs_defaultClientScript">
  9. <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
  10. </HEAD>
  11. <body>
  12. <asp:label id="NameLabel" Runat="server"></asp:label><asp:label id="FormResponse" Runat="server"></asp:label>
  13. <form id="formSuccess" method="post" runat="server">
  14. <h1>Welcome
  15. <%=User.Identity.Name%>
  16. </h1>
  17. <br>
  18. You have successfully logged in to the secure page.
  19. <br>
  20. Username:<%=User.Identity.Name%>
  21. <br>
  22. <br>
  23. Password:
  24. <asp:Label id="txtPassword" Runat="server" name="password"></asp:Label><br>
  25. <asp:button id="btnSubmit" Runat="server" Text="Submit"></asp:button>
  26. <asp:button id="btnLogout" Runat="server" Text="Logout"></asp:button></form>
  27. </body>
  28. </HTML>


Success.aspx.vb
  1. Imports System
  2. Imports System.IO
  3. Imports System.Web
  4. Imports System.Data.SqlClient
  5. Imports System.Collections
  6. Imports System.Web.Security
  7. Imports System.Data
  8. Imports System.Data.SqlDbType
  9. Imports System.Security.Cryptography
  10. Imports System.Text
  11.  
  12.  
  13. Public Class Success
  14. Inherits System.Web.UI.Page
  15. Protected WithEvents formSuccess As System.Web.UI.HtmlControls.HtmlForm
  16. Protected WithEvents txtPassword As System.Web.UI.WebControls.Label
  17. Protected WithEvents lblmessage As System.Web.UI.WebControls.Label
  18. Protected WithEvents btnSubmit As System.Web.UI.WebControls.Button
  19. Protected WithEvents NameLabel As System.Web.UI.WebControls.Label
  20. Protected WithEvents FormResponse As System.Web.UI.WebControls.Label
  21. Protected WithEvents btnLogout As System.Web.UI.WebControls.Button
  22. Protected WithEvents txtUsername As System.Web.UI.WebControls.Label
  23.  
  24. #Region " Web Form Designer Generated Code "
  25.  
  26. 'This call is required by the Web Form Designer.
  27. <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
  28.  
  29. End Sub
  30.  
  31. Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
  32. 'CODEGEN: This method call is required by the Web Form Designer
  33. 'Do not modify it using the code editor.
  34. InitializeComponent()
  35. End Sub
  36.  
  37. #End Region
  38.  
  39. Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  40. 'Put user code to initialize the page here
  41.  
  42. If Not (User.Identity.IsAuthenticated) Then
  43. Response.Redirect("Login.aspx")
  44. End If
  45.  
  46. 'txtPassword.Text = Profile.password
  47.  
  48. If Not Page.IsPostBack Then
  49. Dim db As UsersDB = New UsersDB("connectionstring")
  50. txtPassword.Text = db.GetPassword(Page.User.Identity.Name)
  51. End If
  52.  
  53. End Sub
  54.  
  55. Public Function GetPassword(ByVal username As String) As String
  56. 'Retrieve the connection string from the configuration file.
  57. Dim con As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("connectionstring"))
  58.  
  59. Dim htmlStr As New StringBuilder()
  60.  
  61. 'Create a parameterized command with placeholders.
  62. Dim SQL As String = "SELECT * FROM tblUser WHERE username = @username"
  63. Dim cmd As SqlCommand = New SqlCommand(SQL, con)
  64. cmd.Parameters.Add("@username", username)
  65. Dim encryptedData() As Byte
  66. Try
  67. 'Update the record
  68. con.Open()
  69. Dim reader As SqlDataReader = cmd.ExecuteReader()
  70. If reader.Read() Then
  71. encryptedData = CType(reader("tblUser"), Byte())
  72. txtPassword.Text = reader.Item("password")
  73.  
  74. End If
  75. reader.Close()
  76. Catch
  77. Return Nothing
  78. Finally
  79. con.Close()
  80. End Try
  81.  
  82. 'Decrypt and return the password.
  83. Return EncryptionUtil.DecryptToString(encryptedData, CType(HttpContext.Current.Application("Key"), Rijndael))
  84.  
  85. End Function
  86.  
  87.  
  88.  
  89. Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
  90.  
  91. Dim conMaster As SqlConnection
  92. Dim cmdInsert As SqlCommand
  93. Dim intUpdate As Integer
  94. Dim paramValue As SqlParameter
  95. 'Dim intDate As DateTime = DateTime.Now()
  96.  
  97. conMaster = New SqlConnection(ConfigurationSettings.AppSettings("connectionstring"))
  98. cmdInsert = New SqlCommand("AddData", conMaster)
  99. cmdInsert.CommandType = CommandType.StoredProcedure
  100.  
  101. 'Make sure return value is taken from stored procedure
  102. paramValue = cmdInsert.Parameters.Add("ReturnValue", SqlDbType.Int)
  103. paramValue.Direction = ParameterDirection.ReturnValue
  104.  
  105.  
  106. 'DateAddedLabel.Text = DateTime.Now.ToString
  107.  
  108.  
  109. 'Parameters built to eliminate sql injection attacks
  110. 'cmdInsert.Parameters.Add("@date_added", DateTime.Parse(DateAddedLabel.Text))
  111. 'cmdInsert.Parameters.Add("@username", txtUsername.Text)
  112. cmdInsert.Parameters.Add("@password", txtPassword.Text)
  113.  
  114.  
  115.  
  116. 'Open database connection
  117. conMaster.Open()
  118.  
  119. 'Update database by inserting new parameters
  120. cmdInsert.ExecuteNonQuery()
  121.  
  122. If cmdInsert.Parameters("ReturnValue").Value = 1 Then
  123. 'Duplicate value found go to error page
  124. Response.Redirect("FormError.aspx")
  125. End If
  126.  
  127. 'Close database connection
  128. conMaster.Close()
  129.  
  130.  
  131.  
  132. End Sub
  133.  
  134. Private Sub btnLogout_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLogout.Click
  135. FormsAuthentication.SignOut()
  136. Response.Redirect("Logout.aspx")
  137. End Sub
  138. End Class
  139.  

UsersDB.vb
  1. Imports Microsoft.VisualBasic
  2. Imports System
  3. Imports System.Data.SqlClient
  4. Imports System.Data
  5. Imports System.Configuration
  6. Imports System.Web.Security
  7. Imports System.Collections
  8. Imports System.Web
  9. Imports System.Security.Cryptography
  10.  
  11. Public Class UsersDB
  12. Protected WithEvents txtUsername As System.Web.UI.WebControls.TextBox
  13.  
  14. Private connectionSetting As String
  15.  
  16. Public Sub New(ByVal connectionStringSettingName As String)
  17. Me.connectionSetting = connectionStringSettingName
  18. End Sub
  19.  
  20. Public Function GetPassword(ByVal userName As String) As String
  21. ' Retrieve the connection string from the configuration file.
  22. Dim con As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings(connectionSetting))
  23.  
  24. ' Create a parameterized command with placeholders.
  25. Dim SQL As String = "SELECT * FROM tblUser " + "WHERE username = @username"
  26. Dim cmd As SqlCommand = New SqlCommand(SQL, con)
  27. cmd.Parameters.Add("@username", userName)
  28.  
  29. Dim encryptedData As Byte()
  30. Try
  31. ' Update the record.
  32. con.Open()
  33. Dim reader As SqlDataReader = cmd.ExecuteReader(CommandBehavior.SingleRow)
  34. reader.Read()
  35. encryptedData = CType(reader("tblUser"), Byte())
  36. reader.Close()
  37. Catch
  38. Return Nothing
  39. Finally
  40. con.Close()
  41. End Try
  42.  
  43. ' Decrypt and return the credit card number.
  44. Return EncryptionUtil.DecryptToString(encryptedData, CType(HttpContext.Current.Application("Key"), Rijndael))
  45. End Function
  46.  
  47.  
  48. End Class

EncryptionUtil.vb
  1. Imports Microsoft.VisualBasic
  2. Imports System
  3. Imports System.Security.Cryptography
  4. Imports System.IO
  5.  
  6.  
  7. Public Class EncryptionUtil
  8. Inherits System.Web.UI.Page
  9.  
  10. Public Shared Function EncryptString(ByVal stringToEncrypt As String, ByVal crypt As SymmetricAlgorithm) As Byte()
  11. ' Create a cryptographic stream for encryption.
  12. Dim ms As MemoryStream = New MemoryStream()
  13. Dim cs As CryptoStream = New CryptoStream(ms, crypt.CreateEncryptor(), CryptoStreamMode.Write)
  14.  
  15. ' Write the string to binary data with the help of a BinaryWriter.
  16. Dim w As BinaryWriter = New BinaryWriter(cs)
  17. w.Write(stringToEncrypt)
  18. w.Flush()
  19.  
  20. ' All the data has been written. Now, make sure the last block
  21. ' is properly padded. Failing to do this will cause an error
  22. ' when you attempt to decrypt the data.
  23. cs.FlushFinalBlock()
  24.  
  25. ' Now move the encrypted data out of the stream,
  26. ' and into an array of bytes.
  27. Return ms.ToArray()
  28. End Function
  29.  
  30. Public Shared Function DecryptToString(ByVal dataToDecrypt As Byte(), ByVal crypt As SymmetricAlgorithm) As String
  31. ' Create a cryptographic stream for decryption.
  32. Dim ms As MemoryStream = New MemoryStream()
  33. Dim cs As CryptoStream = New CryptoStream(ms, crypt.CreateDecryptor(), CryptoStreamMode.Write)
  34.  
  35. ' Write the binary data to the memory stream.
  36. cs.Write(dataToDecrypt, 0, dataToDecrypt.Length)
  37. cs.FlushFinalBlock()
  38.  
  39. ' Read the unencrypted data from the stream into a string,
  40. ' with the help of the BinaryReader.
  41. Dim r As BinaryReader = New BinaryReader(ms)
  42. ms.Position = 0
  43. Dim decryptedData As String = r.ReadString()
  44. r.Close()
  45.  
  46. Return decryptedData
  47. End Function
  48.  
  49. End Class
  50.  
As from above, encryption is not necessary, as I will eventually replace the data to be displayed as normal data, instead of displaying the password.

Need help in retrieving the user's data from database and display on the form, user can edit and update and resubmit back to the database.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC