Link to home
Start Free TrialLog in
Avatar of ltpitt
ltpitt

asked on

jQuery Mobile user authentication

Hi all!

I've finished my web application using a mix of html, php and jquery mobile.

I need to use user authentication to handle security of a page I don't want normal users to access...

Any kind of ideas / suggestions / links / snippets about best way to implement this in JQM?

Thanks!
Avatar of Insoftservice inso
Insoftservice inso
Flag of India image

Avatar of ltpitt
ltpitt

ASKER

I appreciate your help in googling information but I already did that.

I'd love to get real experiences and ideas from people answering...

Other than that one of the link is about aspx while my requirements are jqm, php and mysql and this shows nothing more than a little http://lmgtfy.com/

No offence :)
Avatar of Rob
It's important to realise that jQuery mobile is just javascript, nothing more.  I say this because user authentication does not have anything to do with the client side (other than taking their credentials and sending to the server).
So your php handles the authentication.
For pages I've wanted to have authentication on, I include an authentication PHP script at the top of that page (the page must be generated using PHP) so that it executes first and if the user isn't logged in (checks if the user is logged in via a session cookie) it shows a login page and doesn't go any further.  It will remember the page the user is trying to access so when they login successfully they are taken to the page they originally was trying to access.
So the login form, if displayed, just posts to a simple authentication php that takes the username and password (and page the user wants to view) and checks it against the database.  If successful, redirects to the requested page.
Rather than me give you my code, show me where you're up to and what you have or need code samples for and I can adapt it to that.
Avatar of ltpitt

ASKER

Hello there and thank you again for caring :)

Here's my authentication code:

<?php

require_once('PasswordHash.php'); // include the PHPass framework
$hasher = new PasswordHash(8, TRUE); // initialize the PHPass class

class Authenticate {
    function login($username, $password) {
        global $hasher;
        // includo il file di configurazione con i parametri del db
        require_once('config-db.php');
        // importo la classe
        require_once('MysqliDb.php');

        $db = new MysqliDb($config['host'], $config['user'], $config['pass'], $config['name']);

        $db->where('utente_email', $username);
        $row = $db->get('utenti');
#       unset($row[0]['utente_pass']);
#       print_r($row); // contains array of returned rows
        
        if (empty($row)) {
            $msg = 'userko';
            return $msg;
        }
         
        if (!$hasher->CheckPassword($password, $row[0]['utente_pass'])) {
            $msg = 'passwordko';
            return $msg;
        }
         
        unset($hasher);
        $msg = "ok";
        return $msg;

    }   
        global $hasher;
        // includo il file di configurazione con i parametri del db
        require_once('config-db.php');
        // importo la classe
        require_once('MysqliDb.php');

        $db = new MysqliDb($config['host'], $config['user'], $config['pass'], $config['name']);
 
        $data['utente_email'] = $username;
        $data['utente_pass'] = $hasher->HashPassword($password);
        $data['utente_date'] = date("Y-m-d H:i:s");
        
         
        $primary_id = $db->insert(utenti, $data);
     
        if ($primary_id > 0) {
            return true;
        }
        else {
            return false;
        }
    }
}
 
?>

Open in new window


If I've understood right the only missing thing is to let my php page generate the html and to study and implement sessions, right?

For now my poor man solution is:

var serviceURL = "php/";
var loggato = 0;

$(document).bind('pageinit pageshow', '.autorizzazione_report_avanzato', function() {
disabilitaSubmit();
$("#btn_form_autorizzazione_report_avanzato").click(function(){
//$("#form_autorizzazione_report_avanzato").fadeOut();
validaFormAutorizzazioneReportAvanzato();
});
$("#email").select();
});

$(document).bind("pagebeforeshow", ".autorizzazione_report_avanzato", function() {
$("input[type=text]").click(function() {
   $(this).select();
});
});

function validaFormAutorizzazioneReportAvanzato() {

$("#form_autorizzazione_report_avanzato").validate({

        messages: {

		email: {
				email: "Inserire una email valida",
			},		
		password: {
				required: "Campo obbligatorio",
			}
        },

        errorPlacement: function(error, element){
                if (element.attr("name") === "email" || element.attr("name") === "password") {
                        error.insertAfter($(element).parent());
                } else {
                        error.insertAfter(element);
                }
        },
        success: function(){
        $(".ui-block-b div").removeClass("ui-btn-active");
        },
        submitHandler: function(form){
                $( "#popupDialog" ).popup( "open" );
        }
});
}



function disabilitaSubmit()
	{
        $('input,select').keypress(function(event) { return event.keyCode != 13; });
	}

function getUrlVars()
    {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');

            if($.inArray(hash[0], vars)>-1)
            {
                vars[hash[0]]+=","+hash[1];
            }
            else
            {
                vars.push(hash[0]);
                vars[hash[0]] = hash[1];
            }
        }

        return vars;
    }

function verificaPassword() {
	var loggato = 0;
        $("#popupDialog" ).popup( "close" );
        var formData = $("#form_autorizzazione_report_avanzato").serialize();
                $.ajax({
                        type: "POST",
                        url: "php/login.php",
                        success: function (result)
        {
		if (result == 'ok') {
		$.mobile.changePage("report_avanzato.html");
		loggato = 1;
                console.log("Login ok");
		
        } else if (result == 'userko') {
            alert("Email non esistente");
        } else {
            alert("Password errata");
        }

        },

                        error: onError
                });
                        return false;
}


        function onError(data, status)
        {
            console.log ("Errore grave");
        }

Open in new window






and so I can check if the user is logged on my private page and if not it gets back to auth page:

$(document).bind('pagebeforeshow', '.report_avanzato', function(){
console.log(loggato);
if (loggato == "0") {
window.location.href="autorizzazione_report_avanzato.html";
}
});

Open in new window



It works but I feel its weakness :P :D
Yes unfortunately there is a weakness here... but having said that I can't see all your code, such as php/login.php that is called from the ajax.  Can you post that?
It's ok for the user to "login" like you've shown me and you Authenticate class (and login function) is ok, however I can't see anywhere you're creating a session.
The session is important as is "remembers" if the user is logged in or not.  This information is stored in a cookie and transferred back and forth with the server, but it's the server that controls it and whether a session is valid or not.
The other issue is what is going to stop me going right to report_avanzato.html??
 I can see that in your javascript and that will be visible to everyone so really you have no security at all:
$.mobile.changePage("report_avanzato.html");

Open in new window

Your PHP needs to control this.  Off the top of my head I would have a PHP script called "show_report" and I pass the report I want to view eg avanzato.  The PHP script will know how to find the right html file and will send the HTML back to the browser for viewing either in a new window or inserted in a viewing area such as a div etc.  
The key here is the PHP can check and will know whether the user is logged on or not and can return the appropriate message.  You may have reports that do not require authentication, in this case the script may decide not to check authentication or still provide the report regardless.
So for example:
$.ajax({
                        type: "POST",
                        url: "php/show_report.php",
                        data: { report: avanzato }
...

Open in new window

Avatar of ltpitt

ASKER

Hi there!

Forgive the latency but I was either finding ways to finish the basic app functions (believe it or not it's "working") or sleeping :D

Here's my login.php:

<?php

include('autenticazione.php');
date_default_timezone_set('Europe/Rome');
$auth = new Authenticate;

$username = $_POST['email'];
$password = $_POST['password'];

$risultato = $auth->login($username, $password);

if ($risultato == 'ok') {
echo "ok";
#return ok;
}
if ($risultato == 'userko') {
echo "userko";
}
if ($risultato == 'passwordko') {
echo "passwordko";
}

?>

Open in new window


and the included autenticazione.php:

<?php

require_once('PasswordHash.php'); // include the PHPass framework
$hasher = new PasswordHash(8, TRUE); // initialize the PHPass class

class Authenticate {
    function login($username, $password) {
        global $hasher;
        // includo il file di configurazione con i parametri del db
        require_once('config-db.php');
        // importo la classe
        require_once('MysqliDb.php');

        $db = new MysqliDb($config['host'], $config['user'], $config['pass'], $config['name']);

        $db->where('utente_email', $username);
        $row = $db->get('utenti');
#       unset($row[0]['utente_pass']);
#       print_r($row); // contains array of returned rows
        
        if (empty($row)) {
            $msg = 'userko';
            return $msg;
        }
         
        if (!$hasher->CheckPassword($password, $row[0]['utente_pass'])) {
            $msg = 'passwordko';
            return $msg;
        }
         
        unset($hasher);
        $msg = "ok";
        return $msg;

    }   
 
    function register($username, $password) {
        global $hasher;
        // includo il file di configurazione con i parametri del db
        require_once('config-db.php');
        // importo la classe
        require_once('MysqliDb.php');

        $db = new MysqliDb($config['host'], $config['user'], $config['pass'], $config['name']);
 
        $data['utente_email'] = $username;
        $data['utente_pass'] = $hasher->HashPassword($password);
        $data['utente_date'] = date("Y-m-d H:i:s");
        
         
        $primary_id = $db->insert(utenti, $data);
     
        if ($primary_id > 0) {
            return true;
        }
        else {
            return false;
        }
    }
}
 
?>

Open in new window

I'm sure it does "work" :)  If the people using this are not very computer smart then it's ok.  If you have people that are computer smart and will try and find your reports and get around logging in then you will need to change the security around this.

To put it simply, If I was to go to your site, I wouldn't need to log in to view the report.
Avatar of ltpitt

ASKER

So you definitely use php sessions, right?
ASKER CERTIFIED SOLUTION
Avatar of Rob
Rob
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ltpitt

ASKER

Tagit is my mentor.

I'll do it and let you know :)