Home > Software engineering >  JavaScript login with cookies
JavaScript login with cookies

Time:05-25

I've been trying to figure out how to do one of the tasks that im given for the past 3 hours and I just can't seem to do it.

This is the task:

Add a login page (login.html) with a login form to the system. When logging in, it creates a cookie in which the username, password and duration of the login cookie are saved. While there is a login cookie, other sites can be visited. If the cookie doesn't exist it switches to login.html from either page. Clicking on logout deletes the login cookie (moves us back to the login.html) .

this is my HTML code for the login form:

<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>

Hope someone could help me, I've got little time left. Thank you in advance! :,)

CodePudding user response:


    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, '\\$1')   "=([^;]*)"
                ))
            return matches ? decodeURIComponent(matches[1]) : undefined
    }

Explaining:

1.0 Event:

There is event to set values in cookie when using submitting form (functions explaining at 1.2)

1.1 Checking cookies:

Then there is checking if cookie "user" and "pass" do not exist, then you are being redirected

1.2 Functions:

1.2.0 setCookie:

First we are getting path and options that user set, then checking if expires function is in Date format (e.g. 1653420565221), and if it's true then converting to UTC string. (Skipped part with for...in loop because not in use) After all, cookies setting to new one.
1.2.1 getCookie:
Just getting and encoding cookie property using match(), and if it's not exist, returning undefined.

CodePudding user response:

In my experience, you need to use PHP and a database because if you just use javascript, the users won't be able to access their accounts if they simply clear their cookies.

Sorry for not being very insightful on how to answer your question, but PHP would be the first step, someone else can elaborate on how to get the PHP set up, because it is not my specialty.

Edit:

<!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 onl oad="checkCookie()"></body>

</html>

source of code: w3schools

  • Related