1

I have searched many, many topics on the Net discussing about session variables and how to get them from Javacript through Ajax. However, though I have been able to do so, this doesn't completely solve my problem.

Objective

To provide online inventory management online.

Constraints

  • Only authenticated users can manage the online inventory
  • Inventory management controls are hidden from an unauthenticated user
  • Each sections must be independently informed of the authentication in order to show/hide their controls accordingly

Code Samples

  • authenticate.php
  • project.js
  • index.php
  • atv.php
  • atv-inventory-list.php
  • sectionhandler.php

index.php

<?php session_start(); ?>
<html>
...
    <div id="newAtvDialog" title="Input information on the new ATV">
        <form id="newAtvAjaxForm" action="addNewAtv.php" method="post">
        ...
        </form>
    </div>
    <div id="section">
        <$php echo file_get_contents("inventory-sections.html"); ?>
    </div>
...
</html>

authenticate.php

<?php
require_once "data/data_access.php";

$userName = "";
$password = "";

if (isset($_REQUEST["userName"])) $userName = $_REQUEST["userName"];
if (isset($_REQUEST["password"])) $password = $_REQUEST["password"];

$isAuthentic = isAuthenticUser($userName, $password);
$_SESSION["isAuthentic"] = $isAuthentic;
echo $isAuthentic;

// I try to use the below-written function where ever I need to show/hide elements.
function isCurrentUserAuthenticated() { 
    return isset($_SESSION["isAuthentic"]) && $_SESSION["isAuthentic"]; 
}
?>

project.js

$(document).ready(function() {
    $("#newAtvDialog").dialog({
        autoOpen: false,
        closeOnEscape: true,
        modal: true,
        width: 1000
    });

    $("#newAtvAjaxForm").ajaxForm(function(data) {
        $("#newAtvDialog").dialog("close");
        $("#section").load("sectionhandler.php?section=atv&type=-1&make=0&year=0&category=0", function(event) { $("button").button(); }); 
    });
});

atv.php

<div id="newAtvButton"> <!-- This DIV is to be hidden when not authenticated -->
    <button id="addNewAtvButton">Add New ATV</div>
</div>
<div id="criterion">
    ...
</div>
<div id="atv-inventory">
    <?php include ('atv-inventory-list.php'); ?>
</div>

atv-inventory-list.php

<?php 
$type = -1;
$make = 0;
$year = 0;
$category = 0;

if (isset($_REQUEST["type"])) $type = $_REQUEST["type"];
...

$atvs = getAllAtvs($type, $make, $year, $category);
foreach ($atvs as $value=>$atv):
?>
<div class="inventory-item">
    <img src="<?php echo utf8_decode($atv->getPathToImage())">
    <div class="item-title">
    ...
    </div>
    <div id="commands">
    <!-- This is the way I have tried so far, and it doesn't seem to work properly. -->
        <button id="removeAtvButton" 
           class="<?php echo isCurrentUserAuthenticated() ? 'show' : 'hide'; ?>">
           Remove ATV
        </button> 
    </div>
</div>

sectionhandler.php

$section = "";
if (isset($_REQUEST["section"])) $section = $_REQUEST["section"];

$type = -1;
$make = 0;
$year = 0;
$category = 0;

// getting values from $_REQUEST[]

$activatedSection = "";

switch($section) {
    case "atv": $activatedSection = "atv.php";
    ...
}

$file = $url.raw_url_encore($activatedSection);
include $file;

Supplementary thoughts

I thought of setting a boolean session variable which would expire after about 20 minutes of inactivity from the user, forcing him to log in again.

I know I shan't use passwords stored in the database. This is the first step of the authentication within this site which I shall put online pretty soon, as the client is going to ask for delivery any time soon. Encrypted passwords will be the next step. But first, I need the show/hide feature to work properly.

I have also thought about cookies, and being quite new to web development, I ain't quite sure what would be the best approach. As far as I'm concerned, the simplest the best, as long as it implies a minimum of security. This is not the NASA site after all! ;-)

Thanks everyone for your inputs! =)

7
  • "Encrypted passwords will be the next step." - security SHOULD NOT be an afterthought. Commented Oct 1, 2013 at 7:52
  • I know you don't want Nasa-Security but, have you thought about create the content? Instead of show/hide, maybe you can use append/remove, to ensure no auth user can see your hidden data via debuggers (like firebug in mozilla) Commented Oct 1, 2013 at 7:52
  • Btw you should really only post relevant code snippets, there is just too much irrelevant code to look through. Commented Oct 1, 2013 at 7:53
  • @RainFromHeaven: Got it. Then, just edit the question so that only relevant code is in there! Plus, as for the security not being an after-thought, I agree. But before getting deeper into a hole, you ought to dig it first step first. So, instead of criticizing, might you help? Commented Oct 1, 2013 at 14:36
  • @Lan: Thanks for the idea, I just didn't think about this option. Could you, please, show me some sample code so that I may get the how-to? I'm not used to PHP and Web technologies in general. This stuff is quite new to me. Thanks in advance! Commented Oct 1, 2013 at 14:38

1 Answer 1

1

It's an idea, but you can work on/from it;

actionURL is a php file where you can check if the user is logged in with a valid session.

ajaxSession function returns true or false if the user is logged.

Then you can call this function every X seconds/minutes to control if the session still going.

window.setInterval(function(){
  // call your function here
  if(ajaxSession(actionUrl)){
      //return true, user logged, append/show protected divs.

  }else{
      //return false, remove/hide protected divs and ask user to log.

  }    
}, 5000); //every 5 seconds.

ajaxSession function:

 function ajaxSession(actionUrl) {
        var sessionOK= false;

        $.ajax({
        async: false,
        url: actionUrl,
        success: function(msg) {
             // check the return call from the php file.
              if(msg== 'OK'){ 
                 sessionOK = true;
              }else{
                 sessionOk = false;
              }
        }});

        return sessionOK;
    }

EDIT

I will add an example code for the actionUrl, that will return if the session is isset or not to the ajaxSession function:

<?php
    session_start();

    // $_SESSION['reg'] is true when the user is logged in.
    if($_SESSION['reg'] == true){
        echo 'OK';
    }else{
        echo 'NO';
    }
?>

Remember to check in the ajaxSession function the result of the Ajax call. If it's Ok, then sessionOk = true, if not, sessionOk = false.

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

5 Comments

Thanks for this sample. I shall take an eye out this solution and let you know. Thanks for your kind help. =)
@WillMarcouiller check my answer again. I've add some code in the ajax call and I've add a sample of the php file that check if the user is logged in. Todo: how to show/hide divs in jQuery.. a hint: $("#div_id").show();
+1 For providing much samples to help connect everything together. This seems an effective way to do this. Now remains to show/hide the DIV sections, this is another challenge by itself! Don't hesitate if you come to think of something. I'll be glad to learn! =)
I tried removing all of my buttons from my HTML code, and add them through the $("#sectionId").html("<button>Hello!</button>"); on success of the ajaxCallback anonymous function, and it doesn,t seem to work. I am going to edit my question to mark the changes.
@WillMarcouiller, maybe it's better to make another question, asking about how to hide/show html code after an ajax call via jquery..

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.