1

I'm trying to password protect my webpage (http://mywebsite.com/ for example) so that the user only has to enter the password once per session. Here's my problem: If the user cancels out of the initial prompt or enters a wrong password and then get redirected to google.com, AND THEN revisit http://mywebsite.com/ it allows them to view the page without prompting for a password.

Not sure what I'm doing wrong to resolve this small back door of a problem.

Here's the JavaScript I'm attempting to implement:

//Protect only once per browser session? (0=no, 1=yes)
       //Specifying 0 will cause protect to load every time page is loaded
   var once_per_session=1

   function get_cookie(Name) {
          var search = Name + "="
          var returnvalue = "";
          if (document.cookie.length > 0) {
            offset = document.cookie.indexOf(search)
            if (offset != -1) { // if cookie exists
                offset += search.length
                // set index of beginning of value
                end = document.cookie.indexOf(";", offset);
                // set index of end of cookie value
                if (end == -1)
                     end = document.cookie.length;
                returnvalue=unescape(document.cookie.substring(offset, end))
                }
           }
          return returnvalue;
   }

    function passwordProtect(){
        var password;
        var pass1 = "thePassword";
        password = prompt('Enter password to view page',' ');
        if(password == pass1){
            alert('Correct password, click ok to enter');
            window.location="http://mywebsite.com";
        }
        else {
            window.location="http://google.com";
        }
    }

   function loadornot(){
          if (get_cookie('protect')==''){
          passwordProtect()
          document.cookie="protect=yes"
          }
   }

   if (once_per_session==0)
          passwordProtect()
   else
          loadornot()
6
  • 6
    Ideally, serve the sensitive data only after validation with the backend - changes to the front-end won't be reliably secure. Anyone can see the Javascript source, after all. Commented Jul 30, 2018 at 3:01
  • @CertainPerformance how would I go about this? And would I use php instead? Commented Jul 30, 2018 at 3:54
  • I assume this is just for "learning" purposes? Commented Jul 30, 2018 at 4:18
  • Yes it is @Ralph Commented Jul 30, 2018 at 16:48
  • Then the answer given is right, loadornot() doesn't check the result from passwordProtect. It will always call the line where the cookie is set. You are probably assuming that if you set the window.location to a new location, the script after it will halt, which is incorrect. return a true/false from your password protect and use the return value to decide whether or not you will add the protect='yes' cookie. Commented Jul 30, 2018 at 16:52

2 Answers 2

1

Your loadornot() only loads passwordProtect() if the protect cookie is a blank string. It also sets the value of the cookie to "yes." So, the next time that you call it the cookie isn't blank any more, and `passwordProtect()' never gets called.

You appear to believe that if passwordProtect() sends the user to the google page for failing to provide a correct password, the loadornot() function will end without executing the last line. That isn't so. Keep in mind that javascript has an asynchronous execution model, which means that loadornot() doesn't stop executing while its call to passwordProtect() is executing. By the time your user enters a password, the line that sets the cookie value to "yes" has already executed.

If you want function A to execute conditionally based upon the results of decisions made in function B, you'll have to tell function A to wait until function B tells you that the decision has been made. The main ways to do this are callbacks and promises.

For a simple example of how to do a callback, see this example from w3schools.com. For a more involved example of using callbacks and promises to customize a confirm box, see this.

Sign up to request clarification or add additional context in comments.

2 Comments

Any quick examples of code implemented with my code would also be greatly appreciated.
@Kamerov Suppose you try to do one first, and then if you have trouble with it, ask for more help.
0

I fixed this issue by returning a bool from passwordProtect() then checking whether or not the bool was true before updating the cookie to "yes". I know this is a basic implementation of password protection but all the help was great.

The changes I made from before:

   //Protect only once per browser session? (0=no, 1=yes)
   //Specifying 0 will cause protect to load every time page is loaded
    var once_per_session=1
    var bool

    function get_cookie(Name) {
       [see post]
    }

    function passwordProtect(){
        var password;
        var pass1 = "thepassword";
        password = prompt('Enter password to view page',' ');
        if(password === pass1){
            alert('Correct password, click ok to enter');
            window.location="http://example.com";
            return true;
        }
        else {
            window.location="http://google.com";
            return false;
        }
    }

    function loadornot(){
        if (get_cookie('protect')===''){
            bool = passwordProtect();
            if(bool === true)
                document.cookie="protect=yes";
        }
    }

    if (once_per_session===0)
        passwordProtect()
    else
        loadornot()

4 Comments

For the sake of completeness: Note this works because alert and prompt are blocking the code (behaving like classical code running on the stack) If you replace them with a fancy async UI that pulls in the password, you will have to use promises or callbacks because passwordProtect will be async. You won't be able to use a simple boolean value as return value from your function.
This fixed my problem temporarily so to speak, but the consensus is that I'll need to implement something else to have decent security. How would PHP implementation compare to JS? @ralph
I switched to PHP because it seems more effective and private
That's why I asked first if the purpose of this was to learn JavaScript. You definitely can not do something like that for actual production use. Please invest time to understand the difference between server side code and client side code and always remember any client side code can't be trusted and can be easily manipulated... From the question, it looks like you are fairly new in this area. So just take your time to understand the technolog(ies) better. Good luck!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.