Cookie realizes the function of remembering password and automatic login

1. Demand analysis:

Now we need to realize that when the user enters the user name and password in the original page and clicks the remember password button, the login interface is successfully entered, and then the original page is refreshed after clicking Logout. The original page automatically saves the last user name and password.
If the user clicks auto-login, then refresh the original page after logging out, the original page will display the user name and password, and automatically enter the login interface after 500ms.
If the user has already entered the login interface, after refreshing the page again, the user still stays on the login interface.
Note: The original page and login page here are written in one page, and I use transparency and hierarchy to distinguish which page should be displayed currently.

2. Solutions

  • Note: The cookie for remembering the password is named remMe, the cookie for automatic login is named auto,
    the cookie for the username is named username, and the cookie for the password is named password
  • Note: The name of the cookie name means that the login status is saved, and the value of the name is true, and it will always be on the login interface. Without this cookie, it means that the login is logged out. This cookie is set and deleted in NodeJs.
  • Supplementary knowledge: How to get the corresponding cookie in the front-end js?
//得到cookie名为name的value值
 function getCookie(name){
    
    
   var cookieArray=document.cookie.split(";");
   for(var i=0;i<cookieArray.length;++i){
    
    
    var cookies=cookieArray[i].split("=");
    if(cookies[0].trim()==name){
    
    
     return cookies[1];
    }
   }
   if(i==cookieArray.length){
    
    
    return "";
   }
  }
  //设置名为cname,值为cvalue,过期时间为exdays天的cookie
  //d.getTime()获得了1970年至此刻的时间毫秒差
  //d.toGMTString()是形如:Thu, 20 Feb 2020 07:54:01 GMT的时间
   function SetCookie(cname,cvalue,exdays){
    
    
       var d = new Date();
       d.setTime(d.getTime()+(exdays*24*60*60*1000));
       var expires = "expires="+d.toGMTString();
       document.cookie = cname + "=" + cvalue + "; " + expires;
  }

1. Only use cookies, set cookies and delete cookies in front-end js
analyze:
(1) You can monitor the event of clicking to confirm the login in the front-end js. Once you click OK, you can judge whether to click to remember the password and automatically log in to set the cookie. If you click to set the corresponding value of the cookie to true, if you don’t click it, set it The corresponding value of the cookie is false. And you need to set two additional cookies to save the user name and password. These two cookies will only be generated when remembering the password or automatically logging in, otherwise they will be deleted.
(2) When refreshing the page, the front-end js judges whether to assign the value of the cookie named username and password to the original page's username and password by judging the values ​​of the remMe and auto cookies of the current page as true or false The input box and the value of the cookie named name determine whether the login interface is displayed.
Part of the code is as follows:
Note: This is written in the form of an object, and these two methods are written in an object.

//that.remember为记住密码的按钮,that.remember1为自动登录的按钮
//that.buttonTwo为确认登录的按钮
//可以实现(1)功能
rememberFunction: function(){
    
    
  var that=this;
  function addButtonTwo(){
    
    
	   if(that.remember.checked==true&&that.te2.value!="请输入用户名"&&that.pa2.value!="请输入密码"){
    
    
		    var name=that.te2.value;
		    var pass=that.pa2.value;
		    SetCookie("remMe","true",1);
		    SetCookie("username",name,1);
		    SetCookie("password",pass,1);    
	    }else{
    
    
	            SetCookie("remMe","false",1);
		    if(that.remember1.checked==false){
    
    
			     SetCookie("username","",-1);
			     SetCookie("password","",-1);
		    }
            }
	   if(that.remember1.checked==true&&that.te2.value!="请输入用户名"&&that.pa2.value!="请输入密码"){
    
    
		    var name=that.te2.value;
		    var pass=that.pa2.value;
		    SetCookie("auto","true",1);
		    SetCookie("username",name,1);
		    SetCookie("password",pass,1);
	    }else{
    
    
		    SetCookie("auto","false",1);
		    if(that.remember.checked==false){
    
    
		     SetCookie("username","",-1);
		     SetCookie("password","",-1);
		    }  
            }
     }
     that.buttonTwo.addEventListener('click',addButtonTwo);
 },
 //可以实现(2)功能
 //that.page2为登录界面, that.wrapper为原始界面, 
 //that.load代表原始页面中登录的输入信息框
 //that.te2代表输入用户名的input框,that.pa2代表输入密码的input框
 windowOnload: function(){
    
    
	  var that=this;
	  window.onload=function(){
    
    
		   that.load.onmouseenter();
		   if(getCookie('name')){
    
    
			    that.page2.style.opacity=1;
			    that.page2.style.zIndex=1;
			    that.wrapper.style.opacity=0;
			    that.wrapper.style.zIndex=0;
		   }else{
    
    
			   if(getCookie('remMe')=='true'){
    
    
				     that.remember.checked=true;
				     that.te2.value=getCookie('username');
				     that.pa2.value=getCookie('password');
				     that.te2.style.color="#000";
				     that.pa2.style.color="#000";
		           }else if(getCookie('remMe')=='false'){
    
    
				     if(getCookie('auto')=='false'){
    
    
					      SetCookie("username","",-1);
					      SetCookie("password","",-1);
				     }
			    }
		            if(getCookie('auto')=='true'){
    
    
				     that.remember1.checked=true;
				     that.te2.value=getCookie('username');
				     that.pa2.value=getCookie('password');
				     that.te2.style.color="#000";
				     that.pa2.style.color="#000";
				     setTimeout(function(){
    
    
					      if(that.remember1.checked== "true"){
    
    
					          SetCookie("name","true",30);
					          that.page2.style.opacity=1;
					          that.page2.style.zIndex=1;
					          that.wrapper.style.opacity=0;
					          that.wrapper.style.zIndex=0;
					      }
				    },500);
			     }else{
    
    
                                   if(getCookie('remMe')=='false'){
    
    
				      SetCookie("username","",-1);
				      SetCookie("password","",-1);
				     }
		             }
	         }
	 }
}

2. Only use cookies, set cookies in NodeJs, delete cookies in front-end js
analyze:
Don't forget that writing cookies purely in js is obviously extremely insecure. Therefore, I improved the solution one
(1) after each click on the OK login button, the user information sent to the background by ajax carries "check=...&check1=...". check is the state of remembering the password, the value is true or false, check1 is the state of automatic login, and the value is the same as check. Then judge the check value and check and the user name and password in the NodeJs background. If the login is successful, if the values ​​of check and check1 are both false, delete the cookie of the user name and password. If the check is true or check1 is true, set the user name and Password cookie. At the same time, set the three cookies remMe, auto, and name.
(2) Same as the analysis (2) in scheme 1, the function implementation is also the same as the windowOnload function in scheme 1.

Part of the code is as follows:

//NodeJs实现分析(1)
//查询--->这里使用了MySql数据库
function select(name){
    
    
 //异步
     var p=new Promise(function(resolve,reject){
    
    
            var sql='SELECT test_name,test_pass FROM websites WHERE test_name=?';
            var f=[];
            f.push(name);
            connection.query(sql,f,function(err,result){
    
    
                  if(err){
    
    
                           console.log('[SELECT ERROR]-',err.message);
                  }else{
    
    
			    var dataString=JSON.stringify(result);
			    var data=JSON.parse(dataString);
			    console.log('data[0]为: ',data[0]);
			    resolve(data[0]);
	          }
	 }
      })
     return p;
}
//关于登录----->GET
server.use('/login',function(req,res){
    
    
	 var name=req.query['name'];
	 var pass=req.query['pass'];
	 var check=req.query['check'];
	 var check1=req.query['check1'];
	 //1.检查用户名不存在
	 //2.判断用户密码是否正确
	 var test=select(name);
	 var users;
	 test.then(function(data){
    
    
	     users=data;
	     //我们希望它返回的值users={name:"222",pass:"333",check:0}
	     console.log('登陆用户信息为: ',users);
	     if(users==undefined){
    
    
	         res.send({
    
    ok:false,msg:"该用户不存在"});
	     }else if(users["test_pass"]!=pass){
    
    
	         res.send({
    
    ok:false,msg:"用户或者密码错误"});
	     }else{
    
    
	           if(check=='true'||check1=='true'){
    
    
	               res.cookie('username',name,{
    
    path:'/',maxAge:1000*3600*24});
	               res.cookie('password',pass,{
    
    path:'/',maxAge:1000*3600*24});
	            }else if(check=='false'&&check1=='false'){
    
    
	               res.cookie('username',name,{
    
    path:'/',maxAge:-1});
	               res.cookie('password',pass,{
    
    path:'/',maxAge:-1});
	            }
	            res.cookie('name',"true",{
    
    path:'/',maxAge:1000*3600*24*30});
	            res.cookie('remMe',check,{
    
    path:'/',maxAge:1000*3600*24});
	            res.cookie('auto',check1,{
    
    path:'/',maxAge:1000*3600*24});
	            res.send({
    
    ok:true,msg:"登录成功"});
	    }
     })
})
//退出------>GET
server.use('/quit',function(req,res){
    
    
    res.clearCookie('name');
    res.send('登出成功。重定向的事让前端做');
})

3. Both cookie and seesion are used. In NodeJs, only the user name is saved in the cookie, and the complete user name and user password are saved in the session

analyze:
Generally speaking, it is best not to directly expose private information such as user passwords on the front-end page. We can continue to improve the second solution and save complete user information in the session.
(1) After clicking the confirm login button, NodeJs judges if the login is successful, if the login is successful, check is true or check1 is true, set a user object, the attributes are username and password, and save the username and password in the session. And set the username username cookie. If both check and check1 are false, the username cookie will be deleted, and the req.session.user object in the session will be deleted. At the same time, set the three corresponding cookies: remember password check, automatic login check1, and login status name.
(2) When refreshing the interface, if these two cookies: check is true or check1 is true, send an ajax request to get req.session.user.password. Put this value into the password input box, and put the value of the cookie name username into the username input box.
Problems encountered:
In the analysis (2), it is always difficult to send an ajax request while refreshing the interface, and there is always no value in the password input box after refreshing the interface every time. So the code for this solution is not complete.

3. Supplement: Cookie cross-domain solution

The cookie is stored on the client. Even if we set it in the background NodeJs, we
res.header("Access-Control-Allow-Origin","*");can only achieve ajax cross-domain and cannot achieve ajax cross-domain and bring cookies together. How to solve this problem?

  • When the front-end JS writes an ajax request
    xhr.open('get',url,true);
    //支持cookie跨域 3
    xhr.withCredentials = true;
    xhr.send(null);
  • NodeJs
server.use('*',function(req,res,next){
    
    
     //支持cookie跨域 1
     res.header("Access-Control-Allow-Origin",req.headers.origin);
     //支持cookie跨域 2
     res.header("Access-Control-Allow-Credentials",true);
     res.header("Access-Control-Allow-Headers","Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild");
     res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
     next();
})

Guess you like

Origin blog.csdn.net/qq_44875145/article/details/104393987