Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript login with cookies

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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! :,)

>Solution :


    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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading