locked
Login and Logout with logics only RRS feed

  • Question

  • User2072242043 posted

    Hi,

    As i am new here, trying to learn ASP.NET WEB PAGES in detail, I want to create a Register page and a table behind it, which allow to insert the user record for login credentials .
    When user successfully registered, I have a page which allows him to log in, but i am facing these true logical problems.

    1: User gets log in, and he can logout without any permission by pressing browser back button.
    2: If i create a logout button and when user press it i only redirect him to the login page without any checking.

    Now what i want to do is that, i allow user to log in with cookies or sessions with certain conditions and when he press logout button, it should expire or clear session or cookie.

    To do so i have found many solutions from the internet but, i want to do this without using any helper or any builtin function/property etc.
    I want to do it with programming logic as i always used to do in PHP.
    Please give me your best ideas and suggestions i will be very thankful to you people.

    Best regards, 

    Radhesham Khatri

    Sunday, August 2, 2015 2:34 PM

Answers

  • User325035487 posted

    In the Login.cshtml set a session variable if the password they entered was true.

    bool validpass = PasswordHash.ValidatePassword(currentpass, hash); //Using PasswordHash.cs - custom. can use ur logic here
                if (validpass) //Set Session variables and Redirect
                {
                  Session["user"] = Request.Form["Username"];
                }

    In the _PageStart.cshtml in the root of the site, I Put an If Condition to switch between two layouts. One for Logged in User and One when the Session variable user is null for not logged in users. This way some parts of the site which doesnt need login can be accessed. Put _PageStart.cshtml in those Folders of your app which need access control, code to Redirect to Login Page if the Session variable user is null.

    if (Session["user"] == null){
    Response.Redirect("~/")'
    }

    Then in the Logout.cshtml page

    @{
    
        Session.Abandon();
    
        Response.Redirect("~/");
    }

    This is what I did.

    For authorization. I actually wrote a Function in Functions.cshtml

    Roles column is Just comma seperated string in my Db, for example -  Admin,Manager,User

    @using System.Globalization;
    @functions { 
    public static bool EmpRoles(string rolename, string empid)
     {
         var db = Database.Open("dbname");
         var sqlroles = @"SELECT Roles FROM Employees WHERE Emp_ID=@0";
         string userroles = (string)db.QueryValue(sqlroles, empid);
         bool role = userroles.Split(',').Contains(rolename);
         return role;
     }
    }

    Calling this is easy to check if the user is in a particular role and set options for admin or manager for a module or a regular user and so on.

    if (@Functions.UserRoles("E1213","Admin")){
    //User has role admin... 
    }

    Hope it helps

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, August 2, 2015 4:47 PM
  • User-821857111 posted

    You should avoid relying on Session to maintain a user's authentication status. Sessions can be dropped for all sorts of reasons beyond your control, and your users will soon become frustrated if they continually have to log back in again. You should use one of the Membership frameworks. SimpleMembership was introduced with Web Pages. The Starter Site template includes a fully working membership system. Or you can read this blog post for the simplest way to implement it: http://www.mikepope.com/blog/displayblog.aspx?permalink=2240

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 4, 2015 3:46 AM
  • User-1980594115 posted

    I respect your statement, but I have been using Sessions in Adobe Coldfusion for 10 years and now ASP.NET web pages for 3 years with no issues. Any login/logout routine can have issues using memory, Sessions, or saving info in a users machine, Cookies.  I like the way that session variables are reset when a user closes his browser. I have been very pleased with the reliability of using session variables.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 4, 2015 11:55 AM
  • User325035487 posted

    i have about 4500 users in my table. havent find a guide where i dont need to register them again. Thats a daunting task. hence i went for session

    Mike i followed the article you linked above http://www.mikepope.com/blog/displayblog.aspx?permalink=2240 before. Then i had to abandon as there are no instructions or help how to register my existing users from admin side. Any ideas? Since we are in the same topic I dont need to create another thread to ask right?

    I would really like to use Web Security. makes life easy

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 4, 2015 4:36 PM
  • User2072242043 posted

    I am agree with you JKJHSE, you are right. I also read this  http://www.mikepope.com/blog/displayblog.aspx?permalink=2240 article completely and learn the use of Web security in Web pages and no doubt it makes life very easy in many cases but there is no use of Session and user can even can back themselves from browser back button to the place from they came and can play with logout button under their boundaries .
    I am very much confuse how to use session step by step to Log in the user and it must not be back by browser back button util and unless he loged out himself.
    Hope anyone will give helping hand at this position,

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 6, 2015 5:24 AM
  • User-1980594115 posted

    Here is a sample is what I use.

    I first save my referring page to userpage to return to. A user may go directly to a page and not be logged in, so I want to have them go to the login page and return back.

    I open the database and read the table record for the user identification and password that was entered in the form.

    I then check to make sure that the user exists and that the information matches.

    Then I save the userid and role in a session. 

    I redirect the user back to the original page.

    var loc = "";
    var userpage = "";
    
    // Test For URL Existence
    if (Request.QueryString["loc"] == null)
    {
    	loc = "";
    }
    	else
    {
    	loc = Request.QueryString["loc"];
    	userpage = "~/" + loc;
    }
    
    // Open Connection String stored in the Web.config
    var db = Database.Open("DatabaseConnection");
    
    // Get Login Record
    var row2 = db.QuerySingle("SELECT * FROM login_table WHERE userID=@0 and userPassword=@1", userId, userPassword);
    
    if (row2 != null)
    {
    	Session["UserId"] = row2.userID;
    	Session["AccessRole"] = row2.accessRole;
    
    	if (loc == "") {
            // Redirect User Back to Default Page
            Response.Redirect(@Href("~/"));
        }
        else
        {
            // Redirect User Back to Referring Page
            Response.Redirect(@Href(userpage));
        }
    }
    else
    {
       Validation.AddFormError("UserId/Password Not Found. Please re-enter");
       // Clear all session variables
       Session.RemoveAll();
    }
    

    At the top of each of my pages, I have the following to test for the existence of a valid login session and proper role access.

    if (Session["AccessRole"] == null || Session["UserId"] == null)
    {
    	// Redirect User To Login Page
    	Response.Redirect(@Href("~/LoginForm.cshtml?loc=tables/Main.cshtml"), false);
    }
    else
    {
    	// Test Valid Role, if not valid send to Default.cshtml with message
    	if (Session["AccessRole"].ToString() != "admin")
    	{
    		// Redirect User To Default Page
    		// N O T   A U T H O R I Z E
    		Response.Redirect(@Href("~/Default.cshtml?err=notauth"));
    	}
    }
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 6, 2015 11:20 AM
  • User-1980594115 posted

    In the login page, I changed the following:

    1. Query to test for both the name and password instead of just name.

    2. If login is found in the database, then save in session variables. I did not save the password, you can if you need to.

    3. The password does not need to be tested after that in your code, it was tested in the query.

    //This is user name where i want to use session and than want to proceed to its desired page where if become true
    var Name = Request.Form["Name"];
    
    //This is user password where i want to use session and than want to proceed to its desired page where if become true
    var Password = Request.Form["Password"];
    
    var SelectData = "SELECT name,password,role FROM organization WHERE name=@0 and password=@1";
    var SelectedData = db.QuerySingle(SelectData, Name, Password);
    
    // Logic to redirect Here
    if (SelectedData != null)
    {
    	// Create Session Variables
    	Session["Name"] = Name;
    	Session["Role"] = SelectedData.role;
    
    	if (SelectedData.role == "Super Admin")
    	{
    	// For instance this if becomes true, Than user should not be back to login page until he logout 
    		Response.Redirect("~/superAdmin?Name=" + Name);
    	}
    	if (SelectedData.role == "Admin")
    	{
    		Response.Redirect("~/admin?Name=" + Name);
    	}
    	if (SelectedData.role == "Hr Manager")
    	{
    		Response.Redirect("~/HrManager?Name=" + Name);
    	}
    	if (SelectedData.role == "Project Manager")
    	{
    		Response.Redirect("~/ProjectManager?Name=" + Name);
    	}
    	if (SelectedData.role == "User")
    	{
    		Response.Redirect("~/user?Name=" + Name);
    	}
    }
    else
    {
    	<div class="alert alert-danger">
    		<strong>Please</strong> Check User Name and Password.
    	</div>
    }
    

    In the superAdmin page or any other pages, one can read the session variables to do as you will:

    @{
    	Layout="_common.cshtml";
    
    	var db=Database.Open("Task7");
    
    	var Name="";
    	var Assignrole="";
    	
    	if (Session["Name"] != null and Session["Role"] != null)
    	{
    		Name=Session["Name"].ToString();
    		Assignrole=Session["AccessRole"].ToString();
    	}
    	
    	var CNIC=Request.Form["cnic"];
    	var Email=Request.Form["email"];
    	var Password=Request.Form["password"];
    }
    


    On your logout page, include the following to clear the session variables:

    @{ 
        // Clear all session variables
        Session.RemoveAll();
    }
    

    You can also somewhat prevent ones from using the Back Button by using the following javascript:

    <!--- Prevent the LoginForm to be accessed using the Back Button  --->
    <script type="text/javascript" language="JavaScript">
        window.history.forward(-1);
    </script> 
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, August 10, 2015 4:31 PM

All replies

  • User325035487 posted

    In the Login.cshtml set a session variable if the password they entered was true.

    bool validpass = PasswordHash.ValidatePassword(currentpass, hash); //Using PasswordHash.cs - custom. can use ur logic here
                if (validpass) //Set Session variables and Redirect
                {
                  Session["user"] = Request.Form["Username"];
                }

    In the _PageStart.cshtml in the root of the site, I Put an If Condition to switch between two layouts. One for Logged in User and One when the Session variable user is null for not logged in users. This way some parts of the site which doesnt need login can be accessed. Put _PageStart.cshtml in those Folders of your app which need access control, code to Redirect to Login Page if the Session variable user is null.

    if (Session["user"] == null){
    Response.Redirect("~/")'
    }

    Then in the Logout.cshtml page

    @{
    
        Session.Abandon();
    
        Response.Redirect("~/");
    }

    This is what I did.

    For authorization. I actually wrote a Function in Functions.cshtml

    Roles column is Just comma seperated string in my Db, for example -  Admin,Manager,User

    @using System.Globalization;
    @functions { 
    public static bool EmpRoles(string rolename, string empid)
     {
         var db = Database.Open("dbname");
         var sqlroles = @"SELECT Roles FROM Employees WHERE Emp_ID=@0";
         string userroles = (string)db.QueryValue(sqlroles, empid);
         bool role = userroles.Split(',').Contains(rolename);
         return role;
     }
    }

    Calling this is easy to check if the user is in a particular role and set options for admin or manager for a module or a regular user and so on.

    if (@Functions.UserRoles("E1213","Admin")){
    //User has role admin... 
    }

    Hope it helps

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, August 2, 2015 4:47 PM
  • User2072242043 posted

    I have this login page where i select user and password from database checks with if statement, if true i redirect it to another page if not than showing error message. 
    When gets logged in i press browser back button it automatically go back to login page without any restriction.
    I used to use Session for such a case in PHP but don't know how to do this using ASP.Net Web pages(Razor).
    I don't want to use any built in Functions or anything like properties etc as you Explained above like,

    PasswordHash
    Session.Abandon();

    I am new here in Asp.net. i want to go from very very basic.
    I hope you have a better guidance for me.

    Here is code for log in page.
    Create a database name it Task7
    A table name it corporation
    Coulmns: id of int primary key,
                    super_admin nvarchar(50)
                    super_admin_password nvarchar(50)


                    


    @{
        var db=Database.Open("Task7");
        var Name=Request.Form["Name"];
        var Password=Request.Form["Password"];
    
        
        
        
        
        var SelectData="SELECT * FROM corporation";
        var SelectedData=db.Query(SelectData);
           
    }
       
    
    <!DOCTYPE html>
    
    <html lang="en">
    
         <head>
            <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    		<meta charset="utf-8">
    		<title>Login Panel</title>
    		<meta name="generator" content="Bootply" />
    		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    		<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
            <link href="bootstrap/css/bootstrap.css" rel="stylesheet">
            <!--[if lt IE 9]>
    			<script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
    		<![endif]-->
    		<link href="bootstrap/css/adminLogin.css" rel="stylesheet">
            
    	</head>
    
    
    
        <body>
            <!--Pulling Awesome Font -->
    <div class="container">
        <h1 style="
                      text-align: center;
                      padding-bottom: 64px;
                      font-family: inherit;
                      color: cadetblue;
                      font-size: xx-large;">Welcome to Login Panel</h1>
        <div class="row">
    		<div class="col-md-4 col-md-offset-4">
        		<div class="panel panel-default">
    			  	<div class="panel-heading">
    			    	<h3 class="panel-title">Please sign in</h3>
    			 	</div>
    			  	<div class="panel-body">
                          @if(IsPost)
                          {
                              foreach(var match in SelectedData)
                          {
                            if(match.super_admin==Name && match.super_admin_password==Password )
                            {
                               Response.Redirect("~/superAdmin?Name="+Name);
                               
                            }
                            else
                            {
                <div class="alert alert-danger">
        <strong>Oops!</strong> User and Password do not match.
                </div>
                          break;
                             }
                          }
                          }
    
    			    	<form action="" method="post">
                        <fieldset>
    			    	  	<div class="form-group">
    			    		    <input class="form-control" placeholder="Name" name="Name" type="text">
    			    		</div>
    			    		<div class="form-group">
    			    			<input class="form-control" placeholder="Password" name="Password" type="password" value="">
    			    		</div>
    			    		
    			    		<input class="btn btn-lg btn-success btn-block" type="submit" value="Login">
    			    	</fieldset>
    			      	</form>
    			    </div>
    			</div>
    		</div>
    	</div>
    </div>
        </body>
    </html>
    



    Monday, August 3, 2015 1:52 AM
  • User325035487 posted

    I gave you a working solution above. Did you try.?

    Tuesday, August 4, 2015 2:03 AM
  • User-821857111 posted

    You should avoid relying on Session to maintain a user's authentication status. Sessions can be dropped for all sorts of reasons beyond your control, and your users will soon become frustrated if they continually have to log back in again. You should use one of the Membership frameworks. SimpleMembership was introduced with Web Pages. The Starter Site template includes a fully working membership system. Or you can read this blog post for the simplest way to implement it: http://www.mikepope.com/blog/displayblog.aspx?permalink=2240

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 4, 2015 3:46 AM
  • User2072242043 posted

    Ok Mike i am going to read this whole article

    Tuesday, August 4, 2015 9:20 AM
  • User-1980594115 posted

    I respect your statement, but I have been using Sessions in Adobe Coldfusion for 10 years and now ASP.NET web pages for 3 years with no issues. Any login/logout routine can have issues using memory, Sessions, or saving info in a users machine, Cookies.  I like the way that session variables are reset when a user closes his browser. I have been very pleased with the reliability of using session variables.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 4, 2015 11:55 AM
  • User-821857111 posted

    I have been very pleased with the reliability of using session variables.
    Glad to hear it. I wish I could say the same. And there are lots and lots of threads in this forum and ones like it that aren't pleased with the lack of reliability using sessions. There are far fewer issues with authentication cookies, which is what all the modern membership/identity frameworks use. That's why I recommended it.

    Tuesday, August 4, 2015 3:46 PM
  • User325035487 posted

    i have about 4500 users in my table. havent find a guide where i dont need to register them again. Thats a daunting task. hence i went for session

    Mike i followed the article you linked above http://www.mikepope.com/blog/displayblog.aspx?permalink=2240 before. Then i had to abandon as there are no instructions or help how to register my existing users from admin side. Any ideas? Since we are in the same topic I dont need to create another thread to ask right?

    I would really like to use Web Security. makes life easy

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 4, 2015 4:36 PM
  • User2072242043 posted

    I am agree with you JKJHSE, you are right. I also read this  http://www.mikepope.com/blog/displayblog.aspx?permalink=2240 article completely and learn the use of Web security in Web pages and no doubt it makes life very easy in many cases but there is no use of Session and user can even can back themselves from browser back button to the place from they came and can play with logout button under their boundaries .
    I am very much confuse how to use session step by step to Log in the user and it must not be back by browser back button util and unless he loged out himself.
    Hope anyone will give helping hand at this position,

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 6, 2015 5:24 AM
  • User-1980594115 posted

    Here is a sample is what I use.

    I first save my referring page to userpage to return to. A user may go directly to a page and not be logged in, so I want to have them go to the login page and return back.

    I open the database and read the table record for the user identification and password that was entered in the form.

    I then check to make sure that the user exists and that the information matches.

    Then I save the userid and role in a session. 

    I redirect the user back to the original page.

    var loc = "";
    var userpage = "";
    
    // Test For URL Existence
    if (Request.QueryString["loc"] == null)
    {
    	loc = "";
    }
    	else
    {
    	loc = Request.QueryString["loc"];
    	userpage = "~/" + loc;
    }
    
    // Open Connection String stored in the Web.config
    var db = Database.Open("DatabaseConnection");
    
    // Get Login Record
    var row2 = db.QuerySingle("SELECT * FROM login_table WHERE userID=@0 and userPassword=@1", userId, userPassword);
    
    if (row2 != null)
    {
    	Session["UserId"] = row2.userID;
    	Session["AccessRole"] = row2.accessRole;
    
    	if (loc == "") {
            // Redirect User Back to Default Page
            Response.Redirect(@Href("~/"));
        }
        else
        {
            // Redirect User Back to Referring Page
            Response.Redirect(@Href(userpage));
        }
    }
    else
    {
       Validation.AddFormError("UserId/Password Not Found. Please re-enter");
       // Clear all session variables
       Session.RemoveAll();
    }
    

    At the top of each of my pages, I have the following to test for the existence of a valid login session and proper role access.

    if (Session["AccessRole"] == null || Session["UserId"] == null)
    {
    	// Redirect User To Login Page
    	Response.Redirect(@Href("~/LoginForm.cshtml?loc=tables/Main.cshtml"), false);
    }
    else
    {
    	// Test Valid Role, if not valid send to Default.cshtml with message
    	if (Session["AccessRole"].ToString() != "admin")
    	{
    		// Redirect User To Default Page
    		// N O T   A U T H O R I Z E
    		Response.Redirect(@Href("~/Default.cshtml?err=notauth"));
    	}
    }
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, August 6, 2015 11:20 AM
  • User2072242043 posted

    Hi,
    As you explained the way you work with using SESSION on login and logout pages is fine. but I am very New to this concept using Asp.Net Web Pages.
    I Have understand a bit of your code where you have declared the SESSION variables and hence as a result to it I am not getting all these clearly and want to show you my login page Whole code using that I want to use Sessions.
    My login page From where every User will get login using their credentials.

       
    
    <!DOCTYPE html>
    
    <html lang="en">
    
         <head>
            <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    		<meta charset="utf-8">
    		<title>Login Panel</title>
    		<meta name="generator" content="Bootply" />
    		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    		<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
            <link href="bootstrap/css/bootstrap.css" rel="stylesheet">
            <!--[if lt IE 9]>
    			<script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
    		<![endif]-->
    		<link href="bootstrap/css/adminLogin.css" rel="stylesheet">
            
    	</head>
    
    
    
        <body>
            <!--Pulling Awesome Font -->
    <div class="container">
        <h1 style="
                      text-align: center;
                      padding-bottom: 64px;
                      font-family: inherit;
                      color: cadetblue;
                      font-size: xx-large;">Welcome to Login Panel</h1>
        <div class="row">
    		<div class="col-md-4 col-md-offset-4">
        		<div class="panel panel-default">
    			  	<div class="panel-heading">
    			    	<h3 class="panel-title">Please sign in</h3>
    			 	</div>
    			  	<div class="panel-body">
                         @{
    
        var db = Database.Open("Task7");
        if (IsPost)
        {
        //This is user name where i want to use session and than want to proceed to its desired page where if become true
            var Name = Request.Form["Name"];
            var SelectData = "SELECT name,password,role FROM organization WHERE name=@0";
            var SelectedData = db.QuerySingle(SelectData, Name);
    //This is user password where i want to use session and than want to proceed to its desired page where if become true
            var Password = Request.Form["Password"];
            // Logic to redirect Here
    
            if (SelectedData != null)
            {
                if (SelectedData.password != Password) 
                {
                  <div class="alert alert-danger">
                    <strong>Please</strong> Check User Name and Password.
                </div>
                }
                if (SelectedData.role == "Super Admin" && SelectedData.password == Password)
                {
      // For instance this if becomes true, Than user should not be back to login page until he logout 
                    Response.Redirect("~/superAdmin?Name=" + Name);
                }
                if (SelectedData.role == "Admin" && SelectedData.password == Password)
                {
                    Response.Redirect("~/admin?Name=" + Name);
                }
                if (SelectedData.role == "Hr Manager" && SelectedData.password == Password)
                {
                    Response.Redirect("~/HrManager?Name=" + Name);
                }
                if (SelectedData.role == "Project Manager" && SelectedData.password == Password)
                {
                    Response.Redirect("~/ProjectManager?Name=" + Name);
                }
                if (SelectedData.role == "User" && SelectedData.password == Password)
                {
                    Response.Redirect("~/user?Name=" + Name);
                }
            }
            else
            {
                <div class="alert alert-danger">
                    <strong>Oops!</strong> User and Password do not match or User Doesnt Exist.
                </div>
            }
        }
    }
    			    	<form action="" method="post">
                        <fieldset>
    			    	  	<div class="form-group">
    			    		    <input class="form-control" placeholder="Name" name="Name" type="text">
    			    		</div>
    			    		<div class="form-group">
    			    			<input class="form-control" placeholder="Password" name="Password" type="password" value="">
    			    		</div>
    			    		
    			    		<input class="btn btn-lg btn-success btn-block" type="submit" value="Login">
    			    	</fieldset>
    			      	</form>
    			    </div>
    			</div>
    		</div>
    	</div>
    </div>
        </body>
    </html>
    


    _common.cshtml

    <!DOCTYPE html>
    
    <html lang="en">
        <head>
            <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    		<meta charset="utf-8">
    		<title>Registration form for employee</title>
    		<meta name="generator" content="Bootply" />
    		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    		<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
            <link href="bootstrap/css/bootstrap.css" rel="stylesheet">
            
            
    
    		<!--[if lt IE 9]>
    			<script src="//html5shim.googlecode.com/svn/trunk/html5.js"></script>
    		<![endif]-->
    		<link href="bootstrap/css/styles.css" rel="stylesheet">
    	</head>
        </head>
        <body>
            
            <div class="navbar navbar-inverse navbar-fixed-top" id="nav" style="margin: 0 auto;
                                                                                width: 76%;">
            <div class="container">
        <div class="navbar-header">
          
          <a class="navbar-brand" href="#">Khatri Corporation</a>
        </div>
        <div class="collapse navbar-collapse">
          <ul class="nav navbar-nav">
            <li class="active"><a href="#">Home</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Contact</a></li>
              <li><a href="@Href("~/Login")" class="btn btn-default" style="    margin: 8px;
        margin-left: 610px;
        padding: 6px;"><span class="glyphicon glyphicon-user"></span> Logout</a></li>
          </ul>
        </div><!--/.nav-collapse -->
    </div><!--/.navbar -->
                 
            </div>
            <div class="main">
                 @RenderBody()
            </div>
          
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
            <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
    
        </body>
    </html>
    



    I have some comments in code please check out them and When it comes to this Page named superAdmin.cshtml

    @{
            Layout="_common.cshtml";
            var db=Database.Open("Task7");
    
            var Name=Request.Form["name"];
            var CNIC=Request.Form["cnic"];
            var Email=Request.Form["email"];
            var Password=Request.Form["password"];
            var Assignrole=Request.Form["AssignRoll"];
    
           
     }
               
                  
                
            
          
    
        
    
    
       <div class="container" style="margin-top: 70px; background-color:cornsilk;"> 
           
           
            <h3>Super Admin <em style="color: #00ff21;">@Request.QueryString["Name"]</em> is here </h3>
       
    <form class="form-horizontal" action='' method="POST">
        <hr>
        <!--output result-->
        @{
            
            if(IsPost)
            {
                 var sql = "SELECT Count(*) As Total FROM organization Where email = '"+Email+"'";
                    if( db.QueryValue(sql,Email) > 0){
                         
                    <div class="alert alert-danger">
                <strong>Ooops! </strong> Mr, @Name Already has a Role.
                    </div>
                        <hr>
                                                        }
                                                        else
                                                        {
                var insertRecord="INSERT into organization(name,cnic,email,password,role) VALUES (@0,@1,@2,@3,@4)";
                var insertedRecord=db.Execute(insertRecord,Name,CNIC ,Email,Password,Assignrole);
    
                <div class="alert alert-success">
                <a href="#" class="close" data-dismiss="alert" >&times;</a>
                <strong>Successfully Submited!</strong>  Role has been assigned to Mr. <em>@Name</em>.
               </div> 
                <hr>
                                                        }
               
            }
            
        }
        
        <div class="control-group">
          <!-- Name -->
          <label class="control-label"  for="name">Name</label>
          <div class="controls">
            <input type="text" id="name" name="name" placeholder="">
            
          </div>
        </div>
    
        <div class="control-group">
          <!-- CNIC -->
          <label class="control-label"  for="cnic">CNIC</label>
          <div class="controls">
            <input type="text" id="cnic" name="cnic">
            </div>
        </div>
     
        <div class="control-group">
          <!-- E-mail -->
          <label class="control-label" for="email">E-mail</label>
          <div class="controls">
            <input type="text" id="email" name="email">
          
          </div>
        </div>
     
        <div class="control-group">
          <!-- Password-->
          <label class="control-label" for="password">Password</label>
          <div class="controls">
            <input type="password" id="password" name="password" placeholder="" class="input-xlarge">
            
          </div>
        </div>
    
        <select class="form-control"  style="  width: 30%; margin-bottom: 17px;" name="AssignRoll">
                        <option>Select</option>
                        <option value="Admin">Admin</option>
                        <option value="Hr Manager">Hr Manager</option>
                        <option value="Project Manager">Project Manager</option>
                        <option value="User">User</option>
                      
        </select>
     
        
     
        <div class="control-group">
          <!-- Button -->
          <div class="controls">
            <button class="btn btn-success">Register</button>
          </div>
        </div>
      
        
    
    </form>
    </div>

    He Should use logout button to logout and when he press browser back button he should not redirect to it.



    I hope you can Help me in a better way now

    Friday, August 7, 2015 1:58 AM
  • User-1980594115 posted

    In the login page, I changed the following:

    1. Query to test for both the name and password instead of just name.

    2. If login is found in the database, then save in session variables. I did not save the password, you can if you need to.

    3. The password does not need to be tested after that in your code, it was tested in the query.

    //This is user name where i want to use session and than want to proceed to its desired page where if become true
    var Name = Request.Form["Name"];
    
    //This is user password where i want to use session and than want to proceed to its desired page where if become true
    var Password = Request.Form["Password"];
    
    var SelectData = "SELECT name,password,role FROM organization WHERE name=@0 and password=@1";
    var SelectedData = db.QuerySingle(SelectData, Name, Password);
    
    // Logic to redirect Here
    if (SelectedData != null)
    {
    	// Create Session Variables
    	Session["Name"] = Name;
    	Session["Role"] = SelectedData.role;
    
    	if (SelectedData.role == "Super Admin")
    	{
    	// For instance this if becomes true, Than user should not be back to login page until he logout 
    		Response.Redirect("~/superAdmin?Name=" + Name);
    	}
    	if (SelectedData.role == "Admin")
    	{
    		Response.Redirect("~/admin?Name=" + Name);
    	}
    	if (SelectedData.role == "Hr Manager")
    	{
    		Response.Redirect("~/HrManager?Name=" + Name);
    	}
    	if (SelectedData.role == "Project Manager")
    	{
    		Response.Redirect("~/ProjectManager?Name=" + Name);
    	}
    	if (SelectedData.role == "User")
    	{
    		Response.Redirect("~/user?Name=" + Name);
    	}
    }
    else
    {
    	<div class="alert alert-danger">
    		<strong>Please</strong> Check User Name and Password.
    	</div>
    }
    

    In the superAdmin page or any other pages, one can read the session variables to do as you will:

    @{
    	Layout="_common.cshtml";
    
    	var db=Database.Open("Task7");
    
    	var Name="";
    	var Assignrole="";
    	
    	if (Session["Name"] != null and Session["Role"] != null)
    	{
    		Name=Session["Name"].ToString();
    		Assignrole=Session["AccessRole"].ToString();
    	}
    	
    	var CNIC=Request.Form["cnic"];
    	var Email=Request.Form["email"];
    	var Password=Request.Form["password"];
    }
    


    On your logout page, include the following to clear the session variables:

    @{ 
        // Clear all session variables
        Session.RemoveAll();
    }
    

    You can also somewhat prevent ones from using the Back Button by using the following javascript:

    <!--- Prevent the LoginForm to be accessed using the Back Button  --->
    <script type="text/javascript" language="JavaScript">
        window.history.forward(-1);
    </script> 
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, August 10, 2015 4:31 PM