Using the Ajax Modal Popup as a Login Control – A Beginner`s Guide – Part 2
In my previous article Using the Ajax Modal Popup as a Login Control – A Beginner`s Guide, I showed you how to implement a functioning Ajax Modal Popup form. In this followup article, I will show you how to implement the code behind to compare the supplied username and password against credentials stored in your SQL database.
Getting Started – The SQL database backend
For this example, we’re going to use a very simple SQL backend that contains only 5 columns, I won’t bother explaining the username, email and password columns but let’s discuss quickly the other Columns.
I have set the UserId column to UniqueIdentifier, is use a GUID becuase it is, by design Unique. By using a uniqueIdentifier for the UserId, it enables us to query the database using this parameter with confidence.
I use an IsConfirmed column set to Bit, essentially this is like storing a Boolean value as it stores True or False in the form of a Null, 0 for false or a 1 for True. I use this column in the case where you may allow a user to Register (and store their info in the DB), but until they receive and click on a Confirmation email, their account IsConfirmed is set to Null or 0. Once they have received and clicked on the Confirmation Link, I then set IsConformed to True which then gives the user full access.
The Stored Procedure to achieve this looks like this.
ALTER PROCEDURE [dbo].[LoginRegisteredUser] @username varchar (70), @Password varchar (25) AS BEGIN SET NOCOUNT ON; SELECT userId, username, password, email FROM users WHERE (username = @username) AND (password = @password) AND (isconfirmed = 1) /* USER HAS BEEN CONFIRMED!! */
Let’s move on and I’ll explain how things work a little later in the article.
Using Panels – Logged in or Not Logged in, that is the question
In this example we will expand on the control layout from our previous article Using the Ajax Modal Popup as a Login Control – A Beginner`s Guide. In your Site1.Master.vb page, you’ll need to Import ‘system.data’ and ‘system.data.sqlclient’, we will also import the connection Class that I use to connect to my database, you can find the tutorial here. You also need to edit the web.config and ensure that the connection string matches that of your current setup. Leave the connectionString name as “evermanprogrammer” so the example will work properly.
Let’s change our Site1.Master page with two Panels.
<asp:linkButton ID="lnkLoginNow" runat="server" Text="Login">
Now let’s add some code-behind so this makes a little more sense.
In your Site1.Master.Vb, let’s add the following code.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then CheckIsUserLoggedIn() End If End Sub Protected Sub CheckIsUserLoggedIn() If Session("userID") IsNot Nothing Then pnlLoggedIn.Visible = True pnlNotLoggedIn.Visible = False lblWelcome.Text = "Welcome back " & Session("Username").ToString Else pnlLoggedIn.Visible = False pnlNotLoggedIn.Visible = True End If End Sub
What’s Happening here?
Quite simply, when a user accesses any page on the website, the MastePage Page_Load will fire, loading the CheckIsUserLoggedIn Procedure. We check for a Session variable by the name of UserId (remember that GUID from the beginning of this article?), if the user has not used the Login Control, the Session(“UserId”) will be Null, therefore the PnlLoggedIn is Hidden from the User and the PnlNotLoggedIn, which contains our ModalPopup’s TargetControlId of lnkLoginNow.
If the Session variable resolves to true, then we display the pnlLoggedIn and give a friendly greeting to the user by displaying their username which we also handily saved into a session variable.
How to bring the pieces together
The last piece of the puzzle is connecting the btnLogin’ click and the Stored procedures together to make this all work. So, in our site.Master.vb we’re going to add some additional code to handle the btnSubmit_Click event. I’m also going to throw some additional code in here just to keep things clean, assuming you’re just going to copy and paste this right into an application.
First, I need to import the Data Connection class I created for connecting to a DB, please refer to Re-Usable Database Connection Class – A Beginner’s Tutorial Part 1.
Imports System.Data.SqlClient Imports System.Data Imports data_readers
Then let’s add some code.
Private Sub btnLogin_Click(sender As Object, e As System.EventArgs) Handles btnLogin.Click If LogInUser(txtuserName.Text, txtPassword.Text) Then 'reset txtuserName.Text = String.Empty lblError.Text = String.Empty Response.Redirect(Session("CurrentPage").ToString) Else lblError.Text = "* Username or Password incorrect." lblError.ForeColor = Drawing.Color.Red End If End Sub Public Function LogInUser(ByVal Username As String, ByVal Password As String) As Boolean Dim myReturn As Boolean = False If Username IsNot Nothing AndAlso Password IsNot Nothing Then Dim param(2) As SqlParameter param(1) = New SqlParameter("@username", SqlDbType.VarChar, 70) param(1).Value = Username param(2) = New SqlParameter("@password", SqlDbType.VarChar, 25) param(2).Value = Password Using reader As SqlClient.SqlDataReader = data_readers.data.ExecuteDataReader("LoginRegisteredUser", param(1), param(2)) If reader.Read Then If reader("userID").ToString IsNot Nothing And Not IsDBNull(reader("userID")) Then Session("userID") = reader("userID").ToString Session("userName") = reader("userName").ToString Session("email") = reader("email").ToString End If myReturn = True Else Session.Abandon() Session.Contents.RemoveAll() myReturn = False End If End Using End If Return myreturn End Function Public Shared Function GetCurrentPageName() As String Dim sPath As String = System.Web.HttpContext.Current.Request.Url.ToString Return sPath End Function Protected Sub SetCurrentPage() Session("CurrentPage") = GetCurrentPageName() End Sub
What’s with all the code?
Ok, let’s break things down a little. When the user enters their login credentials and hit submit, some basic validation is performed by the validation controls. If the information passes validation, btnLogin_Click will fire.
We have an IF Statement that asks,
If LogInUser(txtuserName.Text, txtPassword.Text) Then
If the Function LogInUser returns TRUE, the ModalForm will have the current login credentials reset to nothing and the user will be redirected back to the current page. Why, when the Page_Load fires, it will discover a UserId in a Session Variable and will display the pnlLoggedIn, along with the username which has been saved in a Session Variable. If the function returns FALSE, the lblError on the Modal form will display an error to the users, allowing them to try again.
Let’s see how the Function resolves to TRUE or FALSE.
Function LogInUser recieves the username and password as parameters. The first thing we do is set our default answer to FALSE, this is a safety precaution. We ensure that somehow we haven’t sent empty string to our function, then send our credentials to the LoginRegisteredUser Stored Procedure from above. If the user account is found with the given credentials, we set 3 Session variables, storing userID, username and email address. We then set the Return value to TRUE. If the Stored Procedure does not find a matching account, we ensure all Session variables are cleared, then Return FALSE.
Simple. There are two helper functions associated with the above code. In the Page_Load we call SetCurrentPage
Protected Sub SetCurrentPage() Session("CurrentPage") = GetCurrentPageName() End Sub
which sets the current child page we have loaded into a Session Variable so that we can redirect the user back to whatever page they launched the Modal Form from. This function is helped by the GetCurrentPageName which actually gets and returns the current Page.
Bringing it all Together
Ok, so what happens when we run this puppy and we login using
We should see this
This occurs simply because the correct information was passed to the Stored Procedure and then the private user credentials were returned to the application. These changes are reflected back to the user using information they will recognize, such as a username.
Now, I did not do certain things like encrypt the password (Passing Parameters to a QueryString – The right way to do it, Encryption) but that wasn’t the goal of this project. At this point, we have a functioning Modal Popup form which connect to the SQL database and performs a routine credentials verification. Of course, this can be built upon, such as saving information into cookies, etc., but I’ll leave that to your imagination.
I hope at this point you can see the flexibility of using a Modal Popup form for your Login Control, as well as the ease of implementing it in your upcoming projects. Please be sure to download the Zip at the bottom of this article, it contains all the Source code as well as the database Script file.
If you found this article helpful, please consider clicking on one of my sponsors, its what pays the bills here.
Visit my Sponsors
- [RESOLVED]leanModal - a JQuery modal plugin with asp.net controls | ASP Web Form Data Control on Using the Ajax Modal Popup as a Login Control – A Beginner`s Guide
- [RESOLVED]Localization of sitemap | ASP Web Form Data Control on asp.Net Easily make your web application multilingual – Part 1
- [RESOLVED]Multiple Page Load with Working Map Page Route | ASP Web Form Data Control on asp.Net 4.0 Routing, a simple Tutorial that works
- [RESOLVED]masterpage initializeculture no suitable method found to override error? | ASP Web Form Data Control on asp.Net Easily make your web application multilingual – Part 1
- repeater databing | ASP.NET MVC on Nested Repeaters, do it clean and simple – A Beginner’s Tutorial – Part 1