JavaScript 使用 cookie 登录

JavaScript login with cookies

过去 3 小时我一直在想办法完成我交给的其中一项任务,但我似乎做不到。

这是任务:

向系统添加带有登录表单的登录页面 (login.html)。登录时,它会创建 一个 cookie,其中保存了登录 cookie 的用户名、密码和持续时间。虽然有登录 cookie,但可以访问其他站点。如果 cookie 不存在,它会从任一页面切换到 login.html。单击注销会删除登录 cookie(将我们移回 login.html)。

这是我的 HTML 登录表单代码:

<form action="index.html" id="loginForm"  method="post">
            <div>
                Username: <input type="text" name="uname" id="uname">
            </div>
            <div>
                Password:<input type="text" name="pwd" id="pwd">
            </div>
            <div>
                <button type="submit" id="myBtn"> Sign in </button>
            </div>
        </form>

希望有人能帮助我,我的时间不多了。先感谢您! :,)

根据我的经验,您需要使用 PHP 和数据库,因为如果您只使用 javascript,用户将无法访问他们的帐户,只要他们简单地清除他们的 cookie。

抱歉,我对如何回答您的问题不是很有见地,但 PHP 将是第一步,其他人可以详细说明如何设置 PHP,因为它是不是我的专长

编辑:

<!DOCTYPE html>
<html>
<head>
<script>
function setCookie(cname,cvalue,exdays) {
  const d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  let expires = "expires=" + d.toUTCString();
  document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
  let name = cname + "=";
  let decodedCookie = decodeURIComponent(document.cookie);
  let ca = decodedCookie.split(';');
  for(let i = 0; i < ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}

function checkCookie() {
  let user = getCookie("username");
  if (user != "") {
    alert("Welcome again " + user);
  } else {
     user = prompt("Please enter your name:","");
     if (user != "" && user != null) {
       setCookie("username", user, 30);
     }
  }
}
</script>
</head>

<body onload="checkCookie()"></body>

</html>

代码来源:w3schools


    document.querySelector('#loginForm').addEventListener('submit', () => {
      setCookie('user', document.querySelector('#uname').value, '/')
      setCookie('pass', document.querySelector('#pwd').value, '/')
    })

    if(!getCookie('user')||!getCookie('pass')) if(location.href != 'https://somelocation.example/index.html/') location.replace('https://somelocation.example/index.html/')

    // Cookies setting and getting functions

    function setCookie(name, value, path, options = {}) {
            options = {
                path: path,
                ...options
            }; if (options.expires instanceof Date) {
                options.expires = options.expires.toUTCString();
            } let updatedCookie = encodeURIComponent(name) + "=" + encodeURIComponent(value)
            for (let optionKey in options) {
                updatedCookie += "; " + optionKey
                let optionValue = options[optionKey]
                if (optionValue !== true) {
                    updatedCookie += "=" + optionValue
                }
            }
            document.cookie = updatedCookie;
    }

    function getCookie(name) {
            let matches = document.cookie.match(new RegExp(
                "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\/\+^])/g, '\') + "=([^;]*)"
                ))
            return matches ? decodeURIComponent(matches[1]) : undefined
    }

解释:

1.0 事件:

使用提交表单时有事件设置cookie中的值(功能在1.2解释)

1.1 检查 cookie:

然后检查 cookie "user" 和 "pass" 是否不存在,然后你被重定向

1.2 函数:

1.2.0 setCookie:

首先我们获取用户设置的路径和选项,然后检查 expires 函数是否为日期格式(例如 1653420565221),如果为真则转换为 UTC 字符串。 (跳过 for...in 循环部分,因为未使用)毕竟,cookie 设置为新的。
1.2.1 getCookie:
只是使用 match() 获取和编码 cookie 属性,如果它不存在,则返回 undefined.