global variables doesn't change value in Javascript - javascript

My project is composed by 2 html pages:
index.html, which contains the login and the registration form.
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?

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

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.

Related

AngularJS + PHP Login authentication

I'm building a WebApp where i have a login page and also some user restrictions.
I have my app running perfect but now I'm stuck in the login process.
The WebApp is based on AngularJs, PHP and a database with MYSQL.
Also, I'm asking this because i didn't found any good answer or work process on the first steps of the login process. Also keep in mind I'm not an AngularJs advanced user, I'm still learning, so sorry if I'm making somethins stupid.
What i have:
Right now I have a simple login system (working) using only PHP, like this:
index.php
<?php session_start();
include ('dist/php/config.php');
if(isset($_GET['out'])){
session_destroy();
back("#");
}
if((!empty($_POST['user'])) && (!empty($_POST['password']))){
$p = ['user'=>$_POST['user'], 'password'=>$_POST['password']];
$r = sql("select * from users where user= :user and password = :password",$p);
if($r != 0){
foreach($r as $ln){
$_SESSION['loggedin']=$ln['name_user'];
}
} else {
$msg = "<div class='login_fb'><p>User or password incorrect</p></div>";
}
}
if(!empty($_SESSION['loggedin'])){
include "system.php";
} else { ?>
<head>
<meta charset="UTF-8" />
[... rest of head ...]
</head>
<body>
[... rest of body with login form ...]
</body>
<?php } ?>
My routing system is controlled with AngularJs ui-router.
The problem this system (at least i don't know how to do it) is to keep the user data reusable even after the page refresh.
My objective
What i want is:
Login into the WebApp;
Store user data to be used in all pages; For example, it's name or it's ID;
Be able to refresh the page and don't lose the logged state;
Control the user access based on it's power level (master, admin, user, guest);
Secure Login system;
Prevent users to access a further page when changing the URL manually. For example: Typing webapp.com/#/order and with this they jump the login process;
I've alreay found some examples, but they are way to complex (i mean, lack of explanation or plain code), or have some of these failures. I also found this great answer here but it already start the explanation with user logged in.
Also, i saw some reference to use $cookieStore (or just $cookie, since it's deprecated) like this:
app.run(['loginService', function(loginService){
var username = $cookieStore.get('username');
var password = $cookieStore.get('password');
loginService.login(username, password);
}]);
But is it ok to use this code? Is it safe? Because we'll have to handle the password value.
What i want to know
So, with this is mind, what i want to know is:
Is it ok, recommended or is there a better option to handle the login process than the one I'm using at the momment?
How can i prevent the users to access the WebApp without the login process?
How can i store the user data to control it's access to restricted areas or to just simple show a message with his name?
How to keep the user logged in even after the refresh?
If it's okay to stay using the same login system I'm using now, how can i keep the user information reusable trought all the other pages and also keep it reusable after a page refresh?
Hope you guys can help me.

How to redirect to base url which is not always unique

Right now in my test environment it's sufficient to say window.location.href = "/home"but in other environment this base url will not be the same.
How do I, using JavaScript, redirect the page to the base url of the web application?
It's an ASP NET MVC Application.
You can always get the base url with #Url.Content("~/"); thus you have access to the value. How you share it with javascript is up to you. One way is to simply put the value in your site layout(s):
_layout.cshtml
<!DOCTYPE html>
<html>
<head>
<script>
applicationRootUrl = #UrlContent("~/");
...
then in any subsequent javascript
window.location.href = applicationRootUrl;
This is actually not possible to autodetect. You can define a variable in your script, eg.
var baseurl='/jkip';
and then do your redirects as
window.location.href=baseurl;
You will need to change the variable accordingly on localhost (set value '/jkip') and on production environment (set value to '/').
Alternatively you may need to redirect to 'current directory', which can be done without defining any variables at all, simply as
window.location.href='.';
but I'm unsure if this is what you want.

Is it possible to delete an entire Webpage when the user navigates away?

If the user navigates off the webpage, is it possible to execute a php script?
I know that Javascript can be executed..
$(window).bind('beforeunload', function(){
return 'DataTest';
});
Cookies might work, but I am not sure how a listener could track an expired cookie, and then delete the correct webpage.
A sample file system is like this:
user0814HIFA9032RHBFAP3RU.php
user9IB83BFI19Y298RYBFWOF.php
index.php
listener.py
data.txt
Typically, to create the website, php writes to the data.txt and the Python listener picks up this change, and creates the file (user[numbers]). As you might think, these files stack up overtime and they need to be deleted.
The http protocol is stateless, therefore users simply can not "navigate away".
The browser requires a page, the server returns it, and the communication stops.
The server doesn't have reliable methods to know what the client will do with that page.
Disclaimer: I'm not sure, as Fox pointed out, that this is the right way to go in your case. I actuallly upvoted Fox's answer.
However, if you absolutely need to delete each page right after the user left it, use this:
$(window).bind('beforeunload', function() {
$.ajax('yourscript.php?currentUser=0814HIFA9032RHBFAP3RU');
});
Then in yourscript.php, put something like the following:
<?php
// load your userId (for example, with $_SESSION, but do what you want here)
$actualUser = $_SESSION['userId'];
// checks if the requested id to delete fits your actual current user's id
if (isset($_GET['currentUser'] && $_GET['currentUser'] == $actualUser)
{
$user = $_GET['currentUser'];
$file = 'user'.$user.'.php';
unlink($file);
}

Ajax Login that refresh only the logged div

Using Zoo Visitor ajax login or Ajax Auth, i manage well the ajax login witn EE.
When the user is logged, how to refresh only the div that contains: welcome user you are logged.
<div class="Welcome"><span>{username}</span> Logout</div><br />
Here is the Zoo Visitor Ajax login script:
$(document).ready(function(){
$('#loginForm').ajaxForm({
dataType: 'json',
success: function(data) {
if (data.success) {
alert('You are now logged in. You can add additional actions in the js script.');
} else {
alert('Failed with the following errors: '+data.errors.login);
}
}
});
});
I guess i have to insert a javascript code inside:
alert('You are now logged in. You can add additional actions in the js script.');
I'm still learning javascript, using
setInterval(function(){
document.getElementById('info').innerHTML =
It's a good method??Does someone has some tips??
It is possible to use a Expression Engine function??
thanks,
Stéphane
Assuming your <div class="Welcome">...</div> already exists on the page you would replace
alert('You are now logged in. You can add additional actions in the js script.');
With
$('div.Welcome').html('<span>Welcome...</span> Logout');
However, note that I removed {username}. When the user visits the page while logged out they do not have a username. When they log in via AJAX the page is not refreshed, therefore the username still remains on the server side. Zoo Visitor does not return any member data with it, either.
It might be better for you to just use a regular log in process than use AJAX if you're trying to do app-like stuff.
If you still want to stick to JavaScript for this then one thing you could do is create a template that returns the data via JSON, e.g.
{exp:http_header content_type="application/json"}
{ "username": "{username}" }
(Note the use of the http_header plugin.)
Right after a successful login you would use AJAX to check that template, then confirm the results. If username has a length then you know the person is logged in and you can update your Welcome div.
Or... you may want to try logging in via Open API by Ben Croker. Apparently its authentication returns the member data you're looking for, see http://docs.eeopenapi.apiary.io/#authentication

Check for undefined javascript variable?

I am trying to check if a variable is defined, if it is then an ajax request is run...If it is not I want the user to be redirected to a separate page where the variable is set.
for example I want something like this:
// if variable is undefined
if (typeof accessKey === 'undefined') {
alert('the variable is not set!');
} else {
var accessKey = 'some random string generated from google';
alert('the variable is set!');
proceed to refresh the page and run through check again.
}
So the first time the page is run, it checks if the variable is set. If the variable is not set it will set the variable and then reload the page and run through the check again.
Problem is 'accessKey' always returns undefined but the code runs through as if the variable is defined. Why?
If the variable is not set it will set the variable and then reload the page [emphasis mine] and run through the check again
There is your problem: variables (or any other piece of js code) do not persist between page reloads.
If you need stuff to persist, you have to use one of these:
Server-side sessions or databases (using ajax to pass data to the server and persist it there)
Client-side storage (such as localStorage).
Cookies (can be generated at client-side or server-side)
Save the value in hiddenfields or in cookie.

Categories