当前位置:网站首页>Code of login page

Code of login page

2022-07-24 11:18:00 Full stack programmer webmaster

Hello everyone , I meet you again , I'm your friend, Quan Jun .

Code of login page

After finishing the page and database , My login page only needs User name and password , So the code is simpler . First find the login button , Give a click event , Then get their form values , Then judge the user name and password , Judge whether the information is filled in and whether the account and password are correct , Before that, check whether the login page belongs to the outer page .dataValidationForm yes from Form ID, User name and password must be added value

<input type="text" name="UserNuber" id="UserNuber" class="form-control" placeholder=" user name " value="@ViewBag.UserNuber" style="width:93%;" />
 <input type="Password" name="Password" id="Password" class="form-control" placeholder=" password " value="@ViewBag.Password" style="width:93%;" />
<script>
 var layer;
   $(function () {
       // Keyboard press event 
       window.onkeydown = onreturn;
         // Used to check whether the login page is an outer page 
         if (window.top.location.href != window.location.href) {
             window.top.location.href = window.location.href;
            }
         // load & initialization layui modular , Pop up layer module 
         layui.use(['layer'], function (args) {
             layer = layui.layer;
         });
        $("#btnSubmit").click(function () {
          // Get value 
          var UserNuber = $('#dataValidationForm [name="UserNuber"]').val();// user name 
          var Password = $('#dataValidationForm [name="Password"]').val();// password 
var rememberMe = $('#dataValidationForm[name="rememberMe"]:checked').val();// Remember password or not 
            // Determine whether to fill in the data   Determine user name and password 
            if (strValIsNotNull(UserNuber) && strValIsNotNull(Password)) {
                var layerIndex = layer.load();// Open the loading layer 
                $.post("/WCommerce/UserLogin",// route : Controller name + Method name in the controller 
                  {
                     UserNuber: UserNuber,// user name 
                     Password: Password,// password 
                     rememberMe: rememberMe,// Remember password or not 
                   }, function (msg) {
                     layer.close(layerIndex);// Loading layer 
                   if (msg == "success") {
                       //alert(" Login successful ");
                       // Jump to the main page 
                window.location.replace("/WCommerce/Main");// Jump path : Controller name + The main page 
                } else {
                    if (msg == "PasswordErro") {
                        layer.alert(' Please enter the correct account number or password ');
                      }
                     else if (msg == "userNoExsit") {
                         layer.alert(' The user doesn't exist ');
                      }
                      else {
                         layer.alert(' Login failed ');
                      }
                       // Empty password 
                       $("#Password").val("");
                            }
                        });
                } else {
                    alert(" Please fill in the complete data ");
                }
            });
            // The string value cannot be empty 
            function strValIsNotNull(strVal) {
                return strVal != undefined && strVal != null && strVal != '';
            }
    </script>

Then get it in the background cookie,

public ActionResult Login()
{
   string UserNuber = "";
   string Password = "";    
   bool isRember = false;
   // obtain cookie
  HttpCookie cookie = System.Web.HttpContext.Current.Request.Cookies["user"];
    if (cookie != null)
      {
       if (cookie["UserNuber"] != null)
        {
      UserNuber = System.Web.HttpContext.Current.Server.UrlDecode(cookie["UserNuber"]);
            }
            if (cookie["Password"] != null)
             {
      Password = System.Web.HttpContext.Current.Server.UrlDecode(cookie["Password"]);
              }
              isRember = true;
            }
            ViewBag.UserNuber = UserNuber;
            ViewBag.Password = Password;
            ViewBag.isRember = isRember;
            return View();
        }

Next is the most critical background code , Get the variables passed by the page , And then use linq The query method of , Query a piece of user data according to the account …

 public ActionResult UserLogin(PW_User pwUser)
{
   string strMsg = "fail";// Define a variable that records the state 
   // Get the variables passed by the page 
   string strUserNuber = pwUser.UserNuber;   // user name 
   string strPassword = pwUser.Password;     // password 
   string strIsRember = Request["rememberMe"];    // Remember no         
   // The verification code is correct 
    try
     {
      // Query a piece of user data according to the account 
      //linq
       PW_User dbUser = (from tbUser in myModels.PW_User
                         where tbUser.UserNuber == strUserNuber && tbUser.ToVoidNo == true
                         select tbUser).Single();// The result can only have one piece of data ,0 Bar or greater than or equal to 2 There will be exceptions ( Generally, it is used for single table query )
       // Encrypt the password entered by the user 
       string password = Common.AESEncryptHelper.Encrypt(strPassword);
       // Compare the encrypted password with the password found in the database 
       if (password == dbUser.Password)
        {
          //= Verify that the selected role is correct 
          var listUserType = (from tbUser in myModels.PW_User
                              join tbUserRoleDetail in myModels.PW_UserRoleDetail on tbUser.UserID equals tbUserRoleDetail.UserID
                              join tbUserType in myModels.SYS_UserType on tbUserRoleDetail.UserTypeID equals tbUserType.UserTypeID
                              where tbUser.UserID == dbUser.UserID
                              select new
                              {
                                 tbUserType.UserTypeID,
                                 tbUserType.UserType
                               }).ToList();
           if (listUserType.Count > 0)
             {
                //= Confirm that the identity is correct 
// Put user data into session in 
                // Get user type name 
                string userTypeName = listUserType[0].UserType.Trim();
                // Get user type ID
                int userTypeId = listUserType[0].UserTypeID;
                // Set up session
                Session["UserID"] = dbUser.UserID;// Pass on UserID
                Session["UserTypeID"] = userTypeId;// Pass on UserTypeID
                Session["ServerTime"] = DateTime.Now.ToString("yyy-MM-dd HH:mm:ss");// The login time 
                // Remember user information   Use cookie
                if (strIsRember != null && strIsRember.Trim() == "true")
                   {
                     // remember 
                     // Remember the password   preservation cookie
                     HttpCookie cookie = new HttpCookie("user");
                     cookie.Expires = DateTime.Now.AddDays(7);// preservation 7 God 
                     cookie["UserNuber"] = strUserNuber;// user name 
                     cookie["Password"] = strPassword;// password 
                     Response.Cookies.Add(cookie);
         }
         else
             {
                // forget 
                HttpCookie cookie = new HttpCookie("user");
                cookie.Expires = DateTime.Now.AddDays(-1);// The validity period is set to yesterday , The browser will automatically delete cookie
                Response.Cookies.Add(cookie);
               }
                 strMsg = "success";// Login successful 
                 }
                  else
                      {
                        strMsg = "userTypeErro";// Wrong user type 
                        }
                    }
                    else
                    {
                        strMsg = "passwordErro";// Wrong password 
                    }
                }
                catch (Exception e)
                {
                    strMsg = "userNoExsit";// No such user 
                    Console.Write(e);
                    //throw;
                }
            return Json(strMsg, JsonRequestBehavior.AllowGet);
        }

The complete code is like this , If you need other judgment conditions, you can add them by yourself . design sketch :

If you need to press enter to log in ,

// Press enter to achieve the login effect 
 function onreturn() {
  if (window.event.keyCode == 13) {
     $("#btnSubmit").click();
         }
     }

Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/125056.html Link to the original text :https://javaforall.cn

原网站

版权声明
本文为[Full stack programmer webmaster]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/203/202207221013197715.html