1

I have a temporary login script, that checks a password, assigns a cookie, and then redirects the user to a new page. On the console page, I have code that checks if the cookie is set to true. If it is, it deletes it and continues. If it isn't, it redirects the user back to the homepage. I got all the code in place, but it doesn't work! Here's some more important info:

  • The cookie is called login
  • the logged in cookie is set to true
  • The cookie sets properly, it's a problem with the console page's code. Here's my code:

function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
        var end = document.cookie.indexOf(";", begin);
        if (end == -1) {
        end = dc.length;
        }
    }
    // because unescape has been deprecated, replaced with decodeURI
    //return unescape(dc.substring(begin + prefix.length, end));
    return decodeURI(dc.substring(begin + prefix.length, end));
} 

function doSomething() {
    var myCookie = getCookie("login");

    if (myCookie == true) {
alert("Logged in for one session!");
        document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";       

    }
    else {
alert("Login Failed. Redirecting...");
window.location.assign("https://www.code-u.org/")
    }
}
Ajit Panigrahi
  • 752
  • 10
  • 27
  • Post the console error – Stefano Maglione Oct 19 '17 at 20:20
  • well did you add console.log lines to see why it is and is not working? eg `console.log('myCookie', myCookie, myCookie==true);` And FYI, the cookie value would be a string, not a boolean. Does it go into the if? does it go into the else? – epascarello Oct 19 '17 at 20:21
  • It may be noteworthy that this question is this answer: https://stackoverflow.com/a/5968306/114900 – msanford Oct 19 '17 at 20:21
  • I dont have the console error, Stefano I know that, msanford, I used that code, but i'm having prioblems with it. How would i add console.log, epascarello? I changed it to "true" instead of true according to your suggestion, and it didn't work! – DANIEL MESKIN Oct 19 '17 at 20:22
  • Can you first do alert(myCookie) before if (myCookie == true) { to see what myCookie value is? – Nickolodeon Oct 19 '17 at 20:44
  • Anyways it seems your getCookie(...) parsing is completely screwed up. – Nickolodeon Oct 19 '17 at 20:56

1 Answers1

0

Two years too late to help you, but it's because this widely copypasted getCookie has an error in it.

Namely it does not work if the cookie set is the first cookie in document.cookies, because when the branch if (begin == -1) is taken, end is never set.

The solution would be to replace the getCookie with another implementation.

Bemmu
  • 17,849
  • 16
  • 76
  • 93