Set cookie using jquery on form submit / log in

2020-04-30 17:23发布

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');
        }
      }

1条回答
我只想做你的唯一
2楼-- · 2020-04-30 18:14

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

查看更多
登录 后发表回答