Task requirements: Do a login, with automatic memory account and password function, to ensure security, Ajax, no refresh, a good user experience. (Master page)
This is the front page that requires user login
First of all, we analyze
User requirements:
1. After login, login box is hidden, and welcome to login box display, and, the left-corner login button disappears, safe exit display.
2. If you choose to remember the account number and password, login directly next time, and ensure security.
Implementation process:
First of all, when the login to issue an AJAX request, user authentication login, login, save the current username and password to cookies, note that the password to use MD5 encryption, MD5 is based on the user's machine configuration generated, and return the login status and user name of the JSON data
The second login, the detection of user status, if the user cookies saved username and password, according to user name read user password, and MD5 encryption, verify two times password is the same, if the same return JSON data, login status True and username, If only the user name is in the cookie, return the login status to False and username
Foreground main code:
Copy Code code as follows:
<%@ Master language= "C #" autoeventwireup= "true" codefile= "Left_Top_Dwon.master.cs"
inherits= "Left_top_dwon"%>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<html xmlns= "http://www.w3.org/1999/xhtml" >
<head id= "Head1" runat= "Server" >
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<title> Untitled Document </title>
<link href= "Css/top_foot.css" rel= "stylesheet" type= "Text/css"/>
<link href= "Css/style.css" rel= "stylesheet" type= "Text/css"/>
<script type= "Text/javascript" src= ' <%=resolveurl ("js/main_nav.js")%> ' ></script>
<script type= "Text/javascript" src= ' <%=resolveurl ("js/nav.js")%> ' ></script>
<script src= ' <%=resolveurl ("admin/scripts/jquery-1.7.1.min.js")%> ' type= ' Text/javascript ' ></ Script>
<script type= "Text/javascript" >
Detecting Login Status
function Checkloginstate ()
{
$.ajax ({
URL: "Member/data/getmemberinfo.ashx?method=checkloginstatus",
Type: "Post",
Success:function (data,status) {
var jsoninfo= $.parsejson (data);
alert (data);
Remember both the account number and the password
if (jsoninfo.status&&jsoninfo.username!= "")
{
$ ("#divNotLogin"). Hide ();
$ ("#divIsLogin"). Show ();
$ ("#liLogin"). Hide ();
$ ("#liLogout"). Show ();
$ ("#lbUserName"). Text (jsoninfo.username);
}
If you only remember the account number
else if (jsoninfo.status&&jsoninfo.username== "") {
$ ("#divNotLogin"). Show ();
$ ("#divIsLogin"). Hide ();
$ ("#liLogin"). Show ();
$ ("#liLogout"). Hide ();
$ ("#txtUserName"). Val (Jsoninfo.username);
}
else{
$ ("#divNotLogin"). Show ();
$ ("#divIsLogin"). Hide ();
$ ("#liLogin"). Show ();
$ ("#liLogout"). Hide ();
}
}
});
}
$ (function () {
First logon needs to detect whether to log on automatically
Checkloginstate ();
Get news Category
$.ajax ({
URL: ' <%=resolveurl ("Admin/news/data/getnewsinfo.ashx?method=getnewstypeforcombox")%> ',
Type: "Get",
Success:function (text) {
var jsondata=$.parsejson (text);
$ ("#m2"). Empty ()//Empty the contents of the M2 child element first
$.each (Jsondata,function (key,value) {//Note here
Here links also need to add specific pages
$ ("#m2"). Append (' <a href=\ "' + ' <%=resolveurl (" news/newslist.aspx? Typeid= ")%> ' +value. Typeid+ ' > ' +value. typename+ ' </a> ');
});
}
});
Get Process Knowledge Categories
$.ajax ({
URL: ' <%=resolveurl ("Admin/product/data/getproductinfo.ashx?method=gettopcrafttypeinfo")%> ',
Type: "Get",
Success:function (text) {
var jsondata=$.parsejson (text);
$ ("#m1"). Empty ()//Empty the contents of the M2 child element first
$.each (Jsondata,function (key,value) {//Note here
Here links also need to add specific pages
$ ("#m1"). Append (' <a href=\ "' + ' <%=resolveurl (" craftknowledge/craftknowledgelist.aspx? Fid= ")%> ' +value. Fid+ ' > ' +value. typename+ ' </a> ');
});
}
});
Login
$ ("#aLogin"). Click (function () {
var name=$ ("#txtUserName"). Val ();
var pwd=$ ("#txtPwd"). Val ();
var cbname=$ ("#cbUserName"). attr ("checked");
var cbpwd=$ ("#cbPwd"). attr ("checked");
if (name== "" | | pwd== "")
{
Alert ("User name or password cannot be empty!");
Return
}
if (cbname== "checked")
Cbname= "1";
Else
Cbname= "0";
if (cbpwd== "checked")
cbpwd= "1";
Else
cbpwd= "0";
var data={"name": Name, "PWD":p wd, "CBName": CBName, "Cbpwd": Cbpwd}
$.ajax ({
URL: "Member/data/getmemberinfo.ashx?method=memberlogin",
Type: "Post",
Data:data,
Success:function (returndata,status) {
var jsoninfo= $.parsejson (Returndata);
if (jsoninfo.status)
{
$ ("#divNotLogin"). Hide ();
$ ("#divIsLogin"). Show ();
$ ("#liLogin"). Hide ();
$ ("#liLogout"). Show ();
$ ("#lbUserName"). Text (jsoninfo.username);
}
else{
Alert ("The account or password you entered is not correct!) It is possible that your account has not been activated by email!"
}
}
});
});
});
</script>
<asp:contentplaceholder id= "Head" runat= "Server" >
</asp:ContentPlaceHolder>
</head>
<body>
<div class= "Sheel" >
<div class= "Header" >
<div class= "Top_side" >
<ul>
<li id= "Lilogin" ><a href= "#" > Login </a> | </li>
<li><a href= "#" > Registration </a> </li>
<li>|<a href= "#" > Personal Information </a> </li>
<li>|<a href= "#" > My favorites </a> </li>
<li>|<a href= "#" > My message </a> </li>
<li>|<a href= "#" > Station message </a> </li>
<li id= "Lilogout" >|<a id= "A2" href= "<%=resolveurl" ("Member/data/getmemberinfo.ashx?method=memberlogout ")%> ' > Safe exit </a></li>
</ul>
</div>
<div class= "NAV" >
<ul id= "SDDM" >
<li><a href= "#" > Home </a> </li>
<li><a href= "#" > Process Overview </a></li>
<li><a href= "#" onmouseover= "Mopen (' M1 ')" onmouseout= "Mclosetime ()" > Process knowledge </a>
<div id= "M1" Onmouseover= "Mcancelclosetime ()" onmouseout= "Mclosetime ()" >
<a href= "#" > Da wu Clay sculpture </a> <a href= "#" > Gold lacquer woodcarving </a> <a href= "#" > Chaozhou embroidery </a> <a href= "#" > Chaozhou Ceramics </a>
</div>
</li>
<li><a href= "#" > Works exhibition </a></li>
<li><a href= "#" > Non-Legacy Works </a></li>
<li><a href= "#" onmouseover= "Mopen (' m2 ')" onmouseout= "Mclosetime ()" > News Center </a>
<div id= "m2" onmouseover= "Mcancelclosetime ()" onmouseout= "Mclosetime ()" >
<a href= "#" > Da wu Clay sculpture </a> <a href= "#" > Gold lacquer woodcarving </a> <a href= "#" > Chaozhou embroidery </a> <a href= "#" > Chaozhou Ceramics </a>
</div>
</li>
<li><a href= "#" > Master style </a></li>
<li><a href= "#" > Enterprise Show </a></li>
<li><a href= "#" > Contact Us </a></li>
</ul>
</div>
</div>
<div class= "Content" >
<div class= "Left_side" >
<form id= "Flogin" >
<div class= "Logo_bottom" >
</div>
<div class= "Login" >
<h4>
User Login </h4>
<div class= "lg_table" id= "Divnotlogin" >
<table class= "table1" width= "198" cellpadding= "0" cellspacing= "0" border= "0" >
<tr>
<TD width= "align=" "Right" >
User name
</td>
<TD width= "108" align= "Center" >
<input type= "text" id= "txtUserName" name= "txtUserName"/>
</td>
<TD width= "rowspan=" 2 ">
<a href= "#" id= "Alogin" >
<img src= ' <%=resolveurl ("images/login.png")%> ' alt= ' login '/></a>
</td>
</tr>
<tr>
<TD align= "Right" >
Password
</td>
<TD align= "center" >
<input type= "Password" name= "txtpwd" id= "Txtpwd"/>
</td>
</tr>
</table>
<div class= "Border" >
</div>
<table class= "table2" width= "190" cellpadding= "0" cellspacing= "0" border= "0" >
<tr>
<TD width= ">"
<a href= "#" >
<img src= ' <%=resolveurl ("images/lg_forget.png")%> ' alt= ' forgotten password '/></a>
</td>
<TD width= ">"
<a href= "#" >
<img src= ' <%=resolveurl ("images/zhuce.png")%> ' alt= ' registered '/></a>
</td>
</tr>
<tr>
<td>
<input type= "checkbox" Name= "Cbusername" id= "Cbusername"/><span> remember username </span>
</td>
<td>
<input type= "checkbox" Name= "Cbpwd" id= "cbpwd"/><span> Remember password </span>
</td>
</tr>
</table>
</div>
<div class= "lg_table" id= "Divislogin" >
<table id= "Tbislogin" class= "table1" width= "198" cellpadding= "0" cellspacing= "0"
border= "0" >
<tr>
<TD class= "Style1" style= "height:90px" >
<font style= "color:red" > Welcome you back!</font><br/>
Respected <font style= "color:red" ><label id= "Lbusername" ></label></font> users!
</td>
</tr>
<tr>
<TD align= "center" class= "Style2" >
<a href= "###" > View personal Information </a> | <a id= "A1" href= ' <%=resolveurl ("member/data/getmemberinfo.ashx?method=memberlogout")%> ' > Exit </a>
</td>
</tr>
</table>
</div>
</div>
</form>
<div class= "Enter Enter1" >
<a href= "#" >
<img src= ' <%=resolveurl ("images/master.png")%> ' alt= ' "Master entrance" title= "Master Entrance"/></a></div>
<div class= "Enter Enter2" >
<a href= "#" >
<img src= ' <%=resolveurl ("images/company.png")%> ' alt= ' Enterprise entrance ' title= ' Enterprise entrance '/></a></div>
<div class= "Paihang" >
<h3>
<p class= "Hide" >
Recommended rankings </p>
<p>
<a href= "#" > More </a></p>
</h3>
<ul class= "Ph_ul" id= "PH1" >
<li><a href= "#" onmouseover= "setph (0);" class= "Ph_hover" > Master recommended </a></li>
<li><a href= "#" onmouseover= "setph (1);" > Crafts Recommendation </a></li>
<li><a href= "#" onmouseover= "setph (2);" > Company Recommendation </a></li>
</ul>
<div class= "ph_p" id= "PH2" >
<ul style= "Display:block;" >
<li class= "Ph_li1" ><a href= "#" class= "Phplihover" > Zhou Shaojun </a></li>
<li class= "Ph_li2" ><a href= "#" > Zhou Shaojun </a></li>
<li class= "Ph_li3" ><a href= "#" > Zhou Shaojun </a></li>
<li class= "Ph_li4" ><a href= "#" > Zhou Shaojun </a></li>
<li class= "ph_li5" ><a href= "#" > Zhou Shaojun </a></li>
</ul>
<ul>
<li class= "Ph_li1" ><a href= "#" class= "Phplihover" > Big </a></li>
<li class= "Ph_li2" ><a href= "#" > Big </a></li>
<li class= "Ph_li3" ><a href= "#" > Big </a></li>
<li class= "Ph_li4" ><a href= "#" > Big </a></li>
<li class= "ph_li5" ><a href= "#" > Big </a></li>
</ul>
<ul>
<li class= "Ph_li1" ><a href= "#" class= "phplihover" > Small grain </a></li>
<li class= "Ph_li2" ><a href= "#" > Small grain </a></li>
<li class= "Ph_li3" ><a href= "#" > Small grain </a></li>
<li class= "Ph_li4" ><a href= "#" > Small grain </a></li>
<li class= "ph_li5" ><a href= "#" > Small grain </a></li>
</ul>
</div>
</div>
<div class= "Question" >
<h3>
<p class= "Hide" >
Participate in survey </p>
</h3>
<table width= ">"
<tr>
<TD colspan= "2" >
<b>Q.</b><span> which of the following crafts do you like best? </span>
</td>
</tr>
<tr>
<td>
<input type= "Radio"/><span> Clay sculpture </span>
</td>
<td>
<input type= "Radio"/><span> wood carving </span>
</td>
</tr>
<tr>
<td>
<input type= "Radio"/><span> ceramics </span>
</td>
<td>
<input type= "Radio"/><span> Stone carving </span>
</td>
</tr>
<tr>
<td>
<a href= "#" >
<img src= ' <%=resolveurl ("images/sumbit.gif")%> ' alt= ' Submit '/></a>
</td>
<td>
<a href= "#" >
<img src= ' <%=resolveurl ("images/see.gif")%> ' alt= ' view results '/></a>
</td>
</tr>
</table>
</div>
<div class= "Search" >
<div class= "Search_thing" >
<table width= ">"
<tr>
<TD height= ">"
<select name= "Select" class= "select" >
<option> Wood carving </option>
<option> Clay sculpture </option>
<option> Ceramics </option>
</select>
</td>
<TD height= ">"
<input type= "text" value= ""/>
</td>
</tr>
<tr>
<TD colspan= "2" >
<a href= "#" >
<img src= ' <%=resolveurl ("images/search.png")%> ' alt= ' search '/></a>
</td>
</tr>
<tr>
<TD colspan= "2" class= "High_search" >
<a href= "search.html" > Go to Advanced Search >></a>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class= "Right_side" >
<asp:contentplaceholder id= "ContentPlaceHolder1" runat= "Server" >
</asp:ContentPlaceHolder>
</div>
<div class= "Footer" >
<div class= "S_nav" >
<ul>
<li><a href= "#" > Online message </a>|</li>
<li><a href= "#" > Contact Us </a>|</li>
<li><a href= "#" > About Us </a>|</li>
<li><a href= "#" > Enterprise Information </a>|</li>
<li><a href= "#" > Investment cooperation </a></li>
</ul>
</div>
<div class= "Foot" >
<p>
<span> Guangdong province Chaozhou </span> <span>2011©all RIGHTS RESERVED. [Copyright] Student Innovation Activity Center </span>
</p>
<p>
<span> Production and maintenance: Computer Engineering research and Development laboratory </span><span> contact QQ Group:73983871</span></p>
</div>
</div>
</div>
</div>
</body>
</html>
Next, the background request is appropriate:
Copy Code code as follows:
<%@ WebHandler language= "C #" class= "Getmemberinfo"%>
Using System;
Using System.Web;
Using Common;
Using Czcraft. Model;
Using Czcraft. BLL;
Using System.Web.SessionState;
public class Getmemberinfo:ihttphandler, IRequiresSessionState
{
Record log
private static readonly log4net. ILog logger = log4net. Logmanager.getlogger (System.Reflection.MethodBase.GetCurrentMethod (). DeclaringType);
public void ProcessRequest (HttpContext context)
{
String methodname = context. Request["Method"];
if (!string. IsNullOrEmpty (methodname))
Callmethod (methodname, context);
}
<summary>
Invoke different methods based on business requirements
</summary>
<param name= "Method" > Methods </param>
<param name= "Context" > Contexts </param>
public void Callmethod (string method, HttpContext context)
{
Switch (method)
{
Case "Checkexistusername":
Checkexistusername (context);
Break
Case "Memberlogin":
Memberlogin (context);
Break
Case "Savememberinfo":
Savememberinfo (context);
Break
Case "Checkloginstatus":
Checkloginstatus (context);
Break
Case "Memberlogout":
Memberlogout (context);
Break
Default
Return
}
}
<summary>
Exit
</summary>
<param name= "Context" ></param>
public void Memberlogout (HttpContext context)
{
String UserName = (string) context. session["UserName"];
MEMBERBLL BLL = new MEMBERBLL ();
if (! Tools.isnullorempty (UserName))
{
If session exists, clear session
Context. Session.remove ("UserName");
}
Remove cookies
Cookiehelper.clearcookie ("UserName");
Cookiehelper.clearcookie ("Pwd");
Page Jump
Jscript.alertandredirect ("Safe exit success!) Welcome to visit next time!", "http://www.cnblogs.com/Default.aspx");
}
<summary>
Check User logon status
</summary>
<param name= "Context" ></param>
public void Checkloginstatus (HttpContext context)
{
String UserName = (string) context. session["UserName"];
MEMBERBLL BLL = new MEMBERBLL ();
if (! Tools.isnullorempty (UserName))
{
If session exists, return directly to user status
Bll. Writejsonforlogin (True, UserName);
}
Else
{
User Automatic login status detection
Context. Response.Write (BLL. Checkloginstatus ());
}
}
<summary>
Member Login
</summary>
<param name= "Context" ></param>
public void Memberlogin (HttpContext context)
{
Try
{
Get Data
String Name = context. request["Name"];
String Pwd = context. request["PWD"];
String issavename = context. request["CBName"];
String issavepwd = context. request["Cbpwd"];
User logon status
BOOL Status = false;
JSON data returned to the client
String Returnjson = "";
SQL injection Detection
if (Tools.isvalidinput (ref Name, True) && (Tools.isvalidinput (ref PWD, True)) && (Tools.isvalidinput ( Ref issavename, True) && (Tools.isvalidinput (ref issavepwd, True))
{
member Info = new Member ();
MEMBERBLL BLL = new MEMBERBLL ();
Info.username = Name;
Info.password = PWD;
Returnjson = BLL. Returnjson (info, out Status);
if (Status)//if successfully logged in
{
Remember the account number and password
Bll. Rememberuserinfo (info, BLL.) Getremembertype (Issavename, issavepwd));
Save Login Status
Context. session["UserName"] = Info.username;
}
Context. Response.Write (Returnjson);
}
}
catch (Exception ex)
{
Logger. Error ("Member Login Error!", ex);
}
}
<summary>
Verify that the account is present
</summary>
<param name= "Context" ></param>
public void Checkexistusername (HttpContext context)
{
String username = context. request["username"];
if (Tools.isvalidinput (ref username, true)
{
Context. Response.Write (New Memberbll (). Checkexistusername (username));
}
}
<summary>
Save user Information
</summary>
<param name= "Context" ></param>
public void Savememberinfo (HttpContext context)
{
Try
{
Form Read
String txtUserName = context. request["txtUserName"];
String txtpwd = context. request["Txtpwd"];
String Txtemail = context. request["Txtemail"];
String Txtcheckcode = context. request["Txtcheckcode"];
Verify Code Checksum
if (!txtcheckcode.equals context. session["Checkcode"]. ToString ()))
{
Return
}
String SQL injection detection
if (Tools.isvalidinput (ref txtusername, True) && tools.isvalidinput (ref txtpwd, True) && Tools.isvalidinput (ref txtemail, True)
{
member Info = new Member ();
Info.username = txtUserName;
Info.password = txtpwd;
Info. Email = Txtemail;
Info.states = "0";
if (new Memberbll (). AddNew (Info) > 0)
{
SMTP SMTP = new SMTP (info. Email);
String Webpath = context. Request.Url.Scheme + "://" + context. Request.Url.Authority + "/default.aspx";
Smtp. Activation (Webpath, info.username);/Send activation message
Jscript.alertandredirect ("Registered user success!!", ".. /default.aspx ");
}
Else
{
Jscript.alertandredirect ("Registered user failed!", "."). /default.aspx ");
}
}
}
catch (Exception ex)
{
Logger. Error ("Wrong!", ex);
}
}
public bool IsReusable
{
Get
{
return false;
}
}
}
Business logic BLL part of code:
Copy Code code as follows:
<summary>
User Login
</summary>
<param name= "Info" > member model</param>
<returns></returns>
public bool Memberlogin (member info)
{
return new Memberdal (). Memberlogin (info);
}
<summary>
JSON-formatted data returned to the client (for decision based on user login status)
</summary>
<param name= "Info" ></param>
<returns></returns>
public string Returnjson (member info, out BOOL Status)
{
Login status
Status = Memberlogin (info);
Generate JSON Format data
Return Writejsonforlogin (Status, info.username);
}
<summary>
Remember the enumeration of account numbers and passwords
</summary>
public enum Remembertype
{
<summary>
Remember the account number
</summary>
Remembername = 0,
<summary>
Remember both the account number and the password
</summary>
Remembernameandpwd = 1,
<summary>
Do not remember the account password
</summary>
Noremember = 2
}
<summary>
According to save account password status to determine whether to save the account or the same time save the account and password
</summary>
<param name= "Issavename" > "1" On behalf of Save, "0" means not save </param>
<param name= "Issavepwd" > "1" On behalf of Save, "0" means not save </param>
<returns></returns>
Public Remembertype Getremembertype (string issavename, String issavepwd)
{
Remembertype savetype = Remembertype.noremember;
Save account and Password
if (Issavename.equals ("1") && issavepwd.equals ("1"))
{
Savetype = remembertype.remembernameandpwd;
}
Save Account
if (Issavename.equals ("1") &&! Issavepwd.equals ("1"))
{
Savetype = Remembertype.remembername;
}
else if (! Issavename.equals ("1"))
{
Savetype = Remembertype.noremember;
}
return savetype;
}
<summary>
Check user logon status to verify automatic login (and return to JSON format)
</summary>
<returns></returns>
public string Checkloginstatus ()
{
Login status
bool Status = true;
String UserName = Common.CookieHelper.GetCookieValue ("UserName");
If the cookie is empty, return directly
if (Tools.isnullorempty (UserName))
{
Status = false;
}
String Pwd = Common.CookieHelper.GetCookieValue ("Pwd");
if (Tools.isnullorempty (PWD))
{
Status = false;
}
Else
{
Find the user's real password and make MD5 encryption
string password = tools.getmd5 (new Memberdal (). GetPassword (UserName));
If you have the same password two times, you can automatically log in.
if (!password. Equals (PWD))
{
Status = false;
}
}
Generate JSON Format data
Return Writejsonforlogin (Status, UserName);
}
<summary>
Write JSON data for user logins
</summary>
<param name= "status" > Login status </param>
<param name= "UserName" > Username </param>
<returns></returns>
public string Writejsonforlogin (bool Status, string UserName)
{
StringBuilder json = new StringBuilder ();
StringWriter SW = new StringWriter (JSON);
using (jsonwriter jsonwriter = new JsonTextWriter (SW))
{
jsonwriter.formatting = formatting.indented;
Jsonwriter.writestartobject ();
Jsonwriter.writepropertyname ("Status");
Jsonwriter.writevalue (Status);
Jsonwriter.writepropertyname ("UserName");
Jsonwriter.writevalue (UserName);
Jsonwriter.writeendobject ();
}
Return JSON. ToString ();
}
<summary>
Remember user information
</summary>
<param name= "type" > Remember user Information category </param>
<returns></returns>
public bool Rememberuserinfo (member info, Remembertype type)
{
if (type = = Remembertype.remembername)
{
Remember the account number 7 days
Cookiehelper.setcookie ("UserName", Info.username, DateTime.Now.AddDays (7));
}
else if (type = = Remembertype.remembernameandpwd)
{
MD5 Hash Encryption
String Sercret = Tools.getmd5 (Info.password);
Also remember the account number and password for 7 days
Cookiehelper.setcookie ("UserName", Info.username, DateTime.Now.AddDays (7));
Cookiehelper.setcookie ("Pwd", Sercret, DateTime.Now.AddDays (7));
}
Else
{
return false;
}
return true;
}
Implementation effect:
Summarize:
We write every day in the user login, but consider security, reusability, but very few, in this practice, switch statements, or a big problem, so far in addition to reflection does not have a good solution, is being considered!
Can be found that this implementation of the improvement is very large, I clearly remember last year to achieve this function of the bad code, too garbage, code messy AH ...
Code weight Quality, summary analysis study!
Author Cnblogs Tianzh