Question

My project is composed by 2 html pages:

  1. index.html, which contains the login and the registration form.
  2. user_logged.html, which contains all the features of a logged-in user.

Now, what I want to do is a control if the user is really logged in, to avoid the case where a user paste a url in the browser and can see the pages of another user. hours as now, if a user paste this url in the browser:

 www.user_loggato.html?user=x#profile

is as if logged in as user x and this is not nice.

My html pages both use js files that contains scripts. I decided to create a global variable called logged inizialized to false and change the variable to true when the login is succesful.

The problem is that the variable, remains false.

here is the code:

 var logged=false; (write in the file a.js)

while in the file b.js I have:

 function login() {

 //if succesfull
        logged=true;
       window.location.href = "user_loggato.html?user="+ JSON.parse(str).username + #profilo";

Now with some alerts I found that my variable logged is always false. Why?

Was it helpful?

Solution

Javascript is not the way to go, as it runs on the client side. Even if there would be a way to share javascript variables between different requests, the user could manipulate them.

You have to take a server side technique for this (maybe PHP with sessions).

OTHER TIPS

JS variables will reset on every submit/refresh. You could use sessionStorage or cookies for this purpose. For example:

Put this in your login form:

function login() {
    window.sessionStorage[logged] = true;
   window.location.href = "user_loggato.html?user="+ JSON.parse(str).username + #profilo";
}

And in your user_loggato.html, you can retrive it like:

function getLoginStatus() {
    return window.sessionStorage['logged'];
}

Hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top