HTML5 securely store username/password - php

I'm working on a HTML5 mobile app. The app only uses 1 html file which contains a login form. On submit javascript posts the username and password to a php script on the server which returns 'true' or 'false'.
When the authentication returns true the app changes the html5 page and stores the username and password in html5 local storage.
Since this is sensitive data my question is how to store these values in a secure way?
function handleLogin() {
var form = $("#loginForm");
var u = $("#username", form).val();
var p = $("#password", form).val();
if(u != '' && p!= '') {
$.post("http://www.mywebsite.com/login.php", {username:u,password:p}, function(res) {
if(res == true) {
//store
window.localStorage["username"] = u;
window.localStorage["password"] = p;
$.mobile.changePage("index-2.html");
} else {
/// error message
}
$("#submitButton").removeAttr("disabled");
},"json");
}
return false; }

I would suggest using Access tokens, since this can be updated and changed frequetly, it also doesnt reveal who the user or what their hashed password is.
http://php.net/manual/en/oauth.getaccesstoken.php
Edit: You do NOT want to use localStorage!

Related

cookie is not working

I set cookie in php by sending values through post but on redirect cookie, it showing that cookie is not set.
//username is just stored here for an example, it is not a good process to store credentials in cookie.
$('.loginDialogBtn').click(function() {
$usernameLogIn = $('#usernameLogIn').val();
var $passwordLogIn = $('#passwordLogIn').val();
$.post('authorizationAdmin.php', {
usernameLogIn: $usernameLogIn,
passwordLogIn: $passwordLogIn
}, function(data) {
var response = JSON.parse(data);
if (response['done'] === $usernameLogIn ) {
location.href = 'http://foodinger.in/Admin/home.php?restUsername=' + $usernameLogIn;
}
else {
$('.loginError').html('Incorrect Username and password');
}
});
});
php
if(isset($_POST['usernameLogIn']) && !empty($_POST['usernameLogIn']) && isset($_POST['passwordLogIn']) && !empty($_POST['passwordLogIn'])) {
$Username=strip_tags(trim($_POST['usernameLogIn']));
$password = strip_tags(trim($_POST['passwordLogIn']));
setcookie('username',$username, time() + (83600*30), "/Admin/", '.foodinger.in');
setcookie('restaurantId',$restId, time() + (83600*30), "/Admin/", '.foodinger.in');
}
after click on login button i can see cookie is being set in my browser but i can't fetch it using $_COOKIE.
is there any server setting which could make it wrong ?
update -- i was using "walkme" which created the problem, once i removed walkme and deleted all the cookies, it worked. Can anyone please
tell me why "walkme" is creating problem in fetching my cookie
variables
Thanks in advance
Try this to debug your cookie :
// Print an individual cookie
echo $_COOKIE["username"];
echo $HTTP_COOKIE_VARS["username"];
// Another way to debug/test is to view all cookies
print_r($_COOKIE);

Ajax request to another controller in codeigniter not working

I have a Login/logout method located in my home controller. There are username and password textboxes on all the pages which are generated by different controllers.
I've a common jquery file for all my views which uses ajax to post the username and password from any of the pages to the Home controller Login/Logout method. But this does not seem to work as those pages are being generated by different controllers and not the Home controller. When I check firebug I see the url mentioned in the Ajax script is being appended to the controller of that page and no actual redirection takes place.
I've seen that it is usually recommended to use a self made helper in such scenarios. But I'm not sure how can that be used via jquery ajax.
Home controller
function validate_login_user()
{
$this->load->model('model');
if ($this->sristi_model->validate_login())
{
$data = array (
'username' => $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
$this->load->view('includes/logged_in.php');
//return true;
}else{
$this->load->view('includes/loginerror.php');
//return true;
}
}
The javascript
$('#sitelogin').on('click', '.login', function(){
var username = $('#username').val();
var password = $('#password').val();
if (username == "" || password == ""){
$('#error').fadeIn(200).delay(1000).fadeOut(1000);
return false;
}else if(username !== undefined && password !== undefined)
{
$.ajax({
url:"home/validate_login_user",
type:'POST',
data:{username:username,password:password},
cache:false,
success:function(msg){
$('#sitelogin').html(msg).hide().fadeIn(800);
$('#loginerror').delay(2000).fadeOut(1000);
}
});
return false;
}else{
return false;
}
});
When I try to login through the Product controller I get this in Firebug
URL: POST validate_login_user
localhost/ci/product/categories/localhost/ci/home/validate_login_user
Status: 500 Internal Server Error
Domain: localhost
Size: 1.6 KB
Remote IP: [::1]:80
Let me know if you find something...
I was somehow able to see this answer in my notifications but I don't see it on this page. Preceding the ajax url with a slash did the job and now everything is working fine.
Thanks to whoever commented that.

Cannot get ajax post to work

I am able to the js file to fire which does do the first alert but i cannot get the 2nd alert to happen, php file is there and working returning 0 but the alert('finished post'); is not coming up. I think its some syntax I am missing.
$(function () {
$("#login_form").submit(function () {
alert('started js');
//get the username and password
var username = $('#username').val();
var password = $('#password').val();
//use ajax to run the check
$.post("../php/checklogin.php", { username: username, password: password },
function (result) {
alert('finished post');
//if the result is not 1
if (result == 0) {
//Alert username and password are wrong
$('#login').html('Credentials wrong');
alert('got 0');
}
});
});
});
Here is the php
session_start();
include 'anonconnect.php';
// username and password sent from form
$myusername= $_POST['username'];
$mypassword= $_POST['password'];
$sql = $dbh->prepare("SELECT * FROM Users WHERE UserLogin= :login");
$sql->execute(array(':login' => $myusername));
$sql = $sql->fetch();
$admin = $sql['admin'];
$password_hash = $sql['UserPass'];
$salt = $sql['salt'];
/*** close the database connection ***/
$dbh = null;
if(crypt($mypassword, $salt) == $password_hash){
// Register $myusername, $mypassword and redirect to file
$_SESSION['myusername'] = $myusername;
$_SESSION['loggedin'];
$_SESSION['loggedin'] = 1;
if($admin == 1){
$_SESSION['admin'] = 1;
}
header("location:search.php");
}
else {
$_SESSION['loggedin'];
$_SESSION['loggedin'] = 0;
echo 0;
}
Ok so I'll take a stab at this, see if we can work this out. First, let's clean up your code a little bit - clean code is always easiest to debug:
$(function () {
$("#login_form").on('submit', function(){
console.log('form submitted');
// get the username and password
var login_info = { username: $('#username').val(), password: $('#password').val() }
// use ajax to run the check
$.ajax({
url: '../php/checklogin.php',
type: 'POST',
data: login_info,
success: loginHandler
error: function(xhr, status, err){ console.log(xhr, status, err); }
});
return false;
});
function loginHandler(loggedIn){
if (!loggedIn) {
console.log('login incorrect');
} else {
console.log('logged in');
}
}
});
...ok great, we're looking a little better now. Let's go over the changes made quickly.
First, swapped alerts for console.logs - much less annoying. Open up your console to check this out -- command + optn + J if you're using Chrome.
Second, we compressed the login info a bit - this is just aesthetics and makes our code a little cleaner. Really you should be using variables when they need to be used again, and in this case you only use them once.
Next, we swapped the $.post function for $.ajax. This gives us two things -- one is a little finer control over the request details, and the second is an error callback, which in this case is especially important since you almost certainly are getting a server error which is your original problem. Here are the docs for $.ajax for any further clarification.
We're also pointing the success handler to a function to minimize the nesting here. You can see the function declared down below, and it will receive the data returned by the server.
Finally we're returning false so that the page doesn't refresh.
Now, let's get to the issue. When you use this code, you should see a couple things in your console. The first will probably be a red message with something like 500 internal server error, and the second should be the results of the error callback for the ajax function. You can get even more details on this in Chrome specifically if you click over to the Network Tab and look through the details of the request and response.
I can't fix your PHP because you didn't post it, but I'll assume you'll either follow up with an edit or figure that out yourself. Once you have the server issue ironed out, you should get back a clean console.log with the response you sent back, and you can move ahead.
Alternately, this will work because of the lack of page refresh in which case you can ignore the previous 2 paragraphs and declare victory : )
Hope this helps!
Ah, so damned obvious. You aren't cancelling the default submit action so the form is submitting normally. Add this
$("#login_form").submit(function (e) {
e.preventDefault();
// and so on
See http://api.jquery.com/event.preventDefault/
you need to change 2nd line and add the e.preventDefault to prevent the form from refreshing the whole page.
$("#login_form").submit(function (e) {
e.preventDefault();
Also I would change the AJAX request to use GET and change the code in PHP to read variables from GET so you can easily test the PHP page is working by running it in the browser like this
checklogin.php?username=x&password=y
try this:
$("#login_form").submit(function () {
alert('started js');
//get the username and password
var username = $('#username').val();
var password = $('#password').val();
//use ajax to run the check
$.post("../php/checklogin.php", { username: username, password: password }, function (result) {
alert('finished post');
//if the result is not 1
if (result == '0') {
//Alert username and password are wrong
$('#login').html('Credentials wrong');
alert('got 0');
}
}, 'text');
});
}, 'text');
maybe the server does not give the right data format. for example, if you request for json, and the jQuery cannot convert result sting to json. then the function would not be executed and then you would not able to get 'alert('got 0');' thing.

Jquery AJAX PHP login

I have a login form using jquery ajax and a php code. The issue is that is always returns an error instead of logging me into the system. I have spent days trying to find the error but I can't. The webpage displays no errors if I visit it directly. This used to work about a week ago until I accidentally deleted the jquery and now I can't get it to work.
Here is the PHP code:
include('.conf.php');
$user = $_POST['user'];
$pass = $_POST['pass'];
$result = mysql_query("SELECT * FROM accountController WHERE username = '$user'");
while ($row = mysql_fetch_array($result)) {
if (sha1($user.$pass) == $row['pword']) {
setcookie('temp', $row['username']);
session_start();
$_SESSION['login'] = 1;
$_SESSION['uname'] = $row['username'];
echo "success";
}
}
and here is the Jquery AJAX code:
var username = $('#main_username').val();
var password = $('#main_pword').val();
$('.mainlogin').submit(function() {
$.ajax({
url: 'log.php',
type: 'POST',
data: {
user: username,
pass: password
},
success: function(response) {
if(response == 'success') {
window.location.reload();
} else {
$('.logerror').fadeIn(250);
}
}
});
return false;
});
How would I check to see what is being returned like blank or success from the server. Is there any extension for safari? Thanks!
Put this in, instead. It will alert the server's response in a popup.
success: function(response) {
alert(response);
}
On your PHP side, try outputting more stuff - add an }else{ to your if statement that returns some useful data, for example
}else{
print("Post is: \n");
print_r($_POST);
print("\nMySQL gave me: \n");
print_r($row);
}
Just make sure you don't leave it in once it's working!
Look for:
hash is different
db field is different
db fields are blank for some reason
POST data is wrong / wrong field names
Edit: Here's another issue: Your first four lines should actually be:
$('.mainlogin').submit(function() {
var username = $('#main_username').val();
var password = $('#main_pword').val();
$.ajax({
Your code as it is gets the values before the form is submitted - at load - when they are blank, and as a result is sending blank strings to the server as username and password.
Take a look at the code i have in this answer here: user check availability with jQuery
You need to json encode your response, also Firefox has Firebug you can use to view your ajax post and response, chrome and IE both have developer tools
Safari also has dev tools: http://developer.apple.com/technologies/safari/developer-tools.html
Check the console to see what is happening with your AJAX

how to get the email address and the user Id in fbml using cake php

I have used one javascript function which is being called after login on facebook connect.
var FB_API_KEY = "api key";
var FB_CHANNEL_PATH = "xd_receiver.htm";
FB.init(FB_API_KEY, FB_CHANNEL_PATH, {permsToRequestOnConnect : "email"});
FB.Connect.ifUserConnected(FB_ConnectPostAuthorization);
function FB_ConnectPostAuthorization() {
var user_box = document.getElementById("user_id");
user_box.innerHTML =
"<span>"
+"<fb:profile-pic uid='loggedinuser' facebook-logo='true'></fb:profile-pic>"
+"Welcome , <fb:name uid ='loggedinuser' useyou='false'></fb:name>"
+"You are signed in with your facebook account"
+"</span>";
FB.XFBML.Host.parseDomTree();
FB_RequireFeatures(["Api"], function(){
var api = FB.Facebook.apiClient;
var fb_uid = api.get_session().uid;
$.post('/users/fb_login/', {'fb_uid': fb_uid}, function(response) {
if (response != "yes") {
api.users_hasAppPermission("email", function(result) {
if (!result) {
FB.Connect.showPermissionDialog("email", redirect_to_done_page);
} else {
redirect_to_done_page()
}
})
} else {
redirect_to_done_page()
}
});
});
}
function redirect_to_done_page() {
window.location = "xyz";
}
I have added a facebook connect button which calls the above function.
I am only able to get the user name and profile pic in through fbml tags. How do I get the user email and user id.
Please guide me.
I don't think you can get email through fbml, because with it you can just show it and there is no point.
Actually you need to have a PHP part of the FB API which you can help you with that task.
Although you can use this very good plugin for CakePHP. It's really easy to get it working and you can get the user's email for sure.
I've never used the FB api,but I'd be surprised if they gave out emails. Oh... it's Facebook. I eat my words.

Categories