0

Looking for direction or input on something I'm not familiar with. I created a two page site with a log in form that redirects user to the second page with the correct "access code" I created. It works as expected. What I would like to do is set a cookie when user is logged with jquery or vanilla js, then check if the user has logged in before and if they have not redirect back to log in form. I know I have not "tried anything" but just looking to learn and get an idea or advice

HTML:

<form class="form--log-in" id="log-in-form">
    <div class="form-group">
        <label for="firstName">First Name</label>
        <input type="text" class="form-control" name="firstName" id="firstName" placeholder="First Name">
    </div>
    <div class="form-group">
        <label for="lastName">Last Name</label>
        <input type="text" class="form-control" name="lastName" id="lastName" placeholder="Last Name">
    </div>
    <div class="form-group">
        <label for="userEmail">Email Address</label>
        <input type="email" class="form-control" name="userEmail" id="userEmail" placeholder="Email Address">
    </div>
    <div class="form-group">
        <label for="accessCode">Access Code</label>
        <input type="text" class="form-control" name="accessCode" id="accessCode" placeholder="Access Code">
    </div>
    <div class="form--log-in__submit-container">
        <button type="submit" class="btn button-submit form--log-in__submit" id="form_submit">
            Log in
        </button>
    </div>
</form>

jquery:

      // doc ready
      $(function () {
        checkCookie();
    }


    submitHandler: function (form) {
          var formData = {
            'method': 'register',
            'firstName': $('input[name=firstName]').val(),
            'lastName': $('input[name=lastName]').val(),
            'userEmail': $('input[name=userEmail]').val(),
            'accessCode': $('input[name=accessCode]').val(),
          };


          var validationObj = this;

          $.ajax({
            type: 'POST',
            url: form_submit_endpoint,
            data: formData,

            success: function (res) {
              var parsedResponse = JSON.parse(res);


              if (parsedResponse.status === 'success') {
                console.log('success');

                _siteNS.Utils.setCookie('x-access',true,365);

                logInModal();

              } else if (parsedResponse.status === 'error') {
                validationObj.showErrors({'accessCode': 'Incorrect Access Code.'});
                console.log('error');
              }
            }
          })
        }

    function _readCookie(name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            for (var i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) == ' ') {
                    c = c.substring(1, c.length);
                }
                if (c.indexOf(nameEQ) === 0) {
                    return c.substring(nameEQ.length, c.length);
                }
            }
            return null;
        }

        function _setCookie(cookiename, value, numberofdays) {
            var d = new Date();
            d.setTime(d.getTime() + (numberofdays * 24 * 60 * 60 * 1000));
            var expires = "expires=" + d.toUTCString();
            document.cookie = cookiename + "=" + value + ";" + expires + ";path=/";
        }



    function checkCookie() {
           // set cookie to boolean var
   var myCookie = document.cookie === null;

        //if the cookie is true and location is not the video page set location to video page
        if(myCookie === true && (!location.href.match(/video-page/))){
          window.location.replace('video-page');
        }

        //if the cookie is false and location is not the site root set location to site root
        if(myCookie === false && (!location.href.match(/index/))){
          window.location.replace('index');
        }
      }
hendy0817
  • 979
  • 2
  • 20
  • 47
  • You need to set cookie when you press the button and get sucessfully login and get cookie on Your next page on header of ajax – Bibek Apr 08 '20 at 12:30

1 Answers1

0

Here is how you would do it.

  1. After the ajax success, set a localstorage item like 'isLoggedIn', 'true'
  2. In another JS file that is loaded for every page globally, you should check if localstorage flag is set to true.
  3. Redirect to required page based on the result

NOTE: The above method is only to learn about how you can achieve auth. This is definitely not secure. You would have to use some kind of authentication like JWT and set the token in your localhost or cookie that will be sent to the server for each request.

Please do read about authentication before you build a real world app.

$.ajax({
  type: 'POST',
  url: form_endpoint,
  data: formData,

  success: function(res) {
    var parsedResponse = JSON.parse(res);


    if (parsedResponse.status === 'success') {
      // set localstorage flag if successfully logged in
      // NOTE: this is not secure. You need to have some kind of JWT token to be implemented
      if (typeof(Storage) !== "undefined") {
        localstorage.setItem('isLoggedIn', 'true');
      } else {
        // Sorry! No Web Storage support..
      }

    }
  }
});


// In another JS file that is loaded globally

window.on('load', function() {
  if (typeof(Storage) !== "undefined") {
    const loginStatus = localstorage.getItem('isLoggedIn');

    if (loginStatus === 'true') {
      // redirect him to logged in page
    } else {
      // redirect him to unauthorized in page
    }
  } else {
    // Sorry! No Web Storage support..
  }
})
SpiritOfDragon
  • 1,404
  • 2
  • 15
  • 27
  • Thank you for the advice! now where does the setCookie, getCookie functions come into play on something like this I have been reading about? having a hard time wrapping my head around these. – hendy0817 Apr 08 '20 at 13:50
  • `Cookies` and `Localstorage` are completely different. what are you trying to use and what is your scenario? you can read about cookies here https://stackoverflow.com/questions/17769011/how-does-cookie-based-authentication-work – SpiritOfDragon Apr 08 '20 at 14:09
  • Ok I see the difference, so for now i'm trying to utilize cookie-based authentication – hendy0817 Apr 08 '20 at 14:13
  • when you set cookie from the server, you can just do `getCookie` and check if required key is preset and then redirect the user to authorized page. Also note that cookies are automatically sent to your server on each request automatically which you can use on the server to validate the request and send the response. – SpiritOfDragon Apr 08 '20 at 14:17
  • Updated my code with the checkCookie function but it is causing a loop issue, any ideas on how to get that to function correctly? – hendy0817 Apr 08 '20 at 23:27