0

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?

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
Martina
  • 1,852
  • 8
  • 41
  • 78
  • global does **not** mean that it will persist across several different pages. Once a page reloads all variables are lost, as HTML (and javascript) is stateless, unless you use a storage of some kind (read: cookies or localStorage). – adeneo Dec 09 '12 at 11:06
  • Nothing you store on the browser will be safe from a user just switching their login status manually. You need to keep track of this on the server. – jbabey Dec 09 '12 at 11:49

2 Answers2

2

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

David Müller
  • 5,291
  • 2
  • 29
  • 33
0

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.

Akhil Sekharan
  • 12,467
  • 7
  • 40
  • 57