Unable to verify password using password_verify - php

WHen user clicks submit button, ajax will pass data to a php scripts to check if login valid or invalid.
Below, password is not verified. The data passed(email,password) to the checkLogin class are correct, because other data can be retreived using the email address.It's only when it comes to
$flag=false;
if (password_verify($this->password, $hashAndSalt)) {
$flag=true;
}
its returning false. I couldn't spot the mistake.Can anyone see what is wrong in my script?
js
/*login user*/
$("document").ready(function(){
$("#login-user").submit(function(){
alert("submited");
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "text",
url: "login-this-user.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
console.log(data);
alert(data);
}
});//end success
return false;
});//end form
});
PHP
<?php
session_start();
include('config.php');
include('class.login.php');
//$return = $_POST;
$return ='{"email":"jane#ymail.com","pass":"jane","action":"test"}';
//$return['json']= json_encode($return);
//
//below code to store in database
$data = json_decode($return, true);
$login = new checkLogin();
$return_value = $login->checkLogin($data["email"],$data["pass"]);
echo $return_value;
?>
class to check login
<?php
class checkLogin
{
public $email;
public $password;
public $userId;
public $salt;
public $hpass;
public function __construct()
{
}
public function checkLogin($param1, $param2)
{
$this->email=$param1;
$this->password=$param2;
$sql = "SELECT *FROM agency WHERE agency_email='{$this->email}'";
$statement = connection::$pdo->prepare($sql);
$statement->execute();
while( $row = $statement->fetch()) {
echo "salt ".$salt=$row['agency_salt'];
echo "hash ".$hashAndSalt=$row['agency_pass'];
$user_id=$row['agency_id'];
}
$flag=false;
if (password_verify($this->password, $hashAndSalt)) {
$flag=true;
}
return $flag;
}
}
?>
Table structure
Hashing when signing up user and storing password:
/*....salting starts........*/
$cost = 10;
$salt = strtr(base64_encode(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM)), '+', '.');
//$salt = sprintf("$2a$%02d$", $cost) . $salt;
$options = array('cost' => $cost,'salt' => $salt);
//$password = crypt($data['password'], $salt);
$hash = password_hash($data['passsword'], PASSWORD_DEFAULT,$options);
/*..........salting ends..............*/

Related

Json returns undifined

Good day guys I have the following login page. Which I access using ajax from my view page. The problem the data that is returned when I try to display on ajax I get an error on the console.
login.js:35 Uncaught TypeError: Cannot read property 'success' of
undefined
at Object.success (login.js:35)
at i (jquery-2.2.0.min.js:2)
at Object.fireWith [as resolveWith] (jquery-2.2.0.min.js:2)
at z (jquery-2.2.0.min.js:4)
at XMLHttpRequest. (jquery-2.2.0.min.js:4)
<?php
ob_start();
function __autoload($classname)
{
require_once("../../database/$classname.php");
}
class userlogin extends database
{
private $errors = array();
private $message = array();
private $redirect = array();
private $data = array();
private $username;
private $password;
function login()
{
if (empty($_POST['username']) || empty($_POST['password'])) {
$this->message['error'] = "Please enter username and password";
} else {
$this->username = $_POST['username'];
$this->password = $_POST['password'];
try {
$this->stmt = $this->dbh->prepare("SELECT adminID,adminEmail,adminPassword,admintype FROM admin where adminEmail = ? ");
$this->stmt->execute(array(
$this->username
));
$this->results = $this->stmt->fetchall();
if (count($this->results) > 0) {
foreach ($this->results as $key => $row) {
if (password_verify($this->password, $row['adminPassword'])) {
$_SESSION['user'] = $row['adminID'];
$_SESSION['email'] = $this->username;
$_SESSION['usertype'] = $row['admintype'];
switch ($row['admintype']) {
case 's':
$this->redirect['redirect'] = "seo/index.php?route=home";
break;
case 'a':
$this->redirect['redirect'] = "admin/index.php?route=home";
break;
}
$this->message['success'] = "ok";
} else {
$this->message['error'] = "Username and password does not match";
}
}
} else {
$this->message['error'] = "Username does not exist";
}
}
catch (PDOException $pdo) {
$this->error = $pdo->getMessage();
error_log($this->error);
}
$this->data['message'] = $this->message;
$this->data['redirects'] = $this->redirect;
ob_end_clean();
echo json_encode($this->data);
}
}
}
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$login = new userlogin();
$login->login();
}
?>
and my js
function proccessLogin(){
var username = $('input[type="email"][name="email"]').val();
var password = $('input[type="password"][name="upass"]').val();
$.ajax({
type : "POST",
data : {username:username,password:password},
url : "controller/login.php",
beforeSend : function(){
$('button').html('Checking...');
},
success : function(data){
console.log(data);
if(data.message.success == "ok"){
$('#results').removeClass('error');
$('#results').addClass('success');
$('#results').html('login Success, loading user data..');
$('button').html('Loading Profile.. i class="fa fa-spinner fa-pulse fa-1x fa-fw"></i>');
var redirectUrl = JSON.stringify(data.redirects);
redirectUrl = redirectUrl.replace(/[{"":}]/g, '');
var url = redirectUrl.replace('redirect','');
setTimeout(' window.location.href = "'+ url + '"; ', 6000);
}else{
$('button').html("Sign in");
$('#results').removeClass('success');
$('#results').addClass('error');
$('#results').html(data.message.error);
}
},
error : function(xhr){
console.log('Error : ' + xhr);
}
});
return false;
}
Console log results :
{"message":{"success":"ok"},"redirects":{"redirect":"seo\/index.php?route=home"}}
I want to be able to display the message from the json array if success is ok I will display custome message else display what is coming from response. the problem is property undefined.
line 35 :
if(data.message.success == "ok"){
I think the response data is String and you need to call
$.parseJSON(data);
before you can access message and then success
=============
If you want to use dataType: "json", you need to send your JSON as JSON by using PHP's header() function:
/* Send as JSON */
header("Content-Type: application/json", true);
/* Return JSON */
echo json_encode($json);
/* Stop Execution */
exit;

Retrieving Database Data during LogIn

I'm currently using Slim and Ajax to develop a mobile application. In my database I have a column which stores session codes for logins. I need to be able to once logged in, compare the username entered to the database and retrieve the sessionCode based on that.
My current PHP is this:
$app->post('/logIn/', 'logIn');
function logIn()
{
$request = \Slim\Slim::getInstance()->request();
$q = json_decode($request->getBody());
//$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "SELECT * FROM users where username=:username AND password=:password";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("username", $q->username);
$stmt->bindParam("password", $q->password);
$stmt->execute();
//$row=$stmt->fetch(PDO::FETCH_ASSOC);
$row=$stmt->fetch(PDO::FETCH_OBJ);
//$verify = password_verify($q->password, $row['password']);
$db = null;
echo json_encode($row);
} catch (PDOException $e) {
echo $e->getMessage();
}
} //PHP 5.4 LogIn
$app->get('/getSessionCode/:username','getSessionCode');
function getSessionCode($username)
{
$request = \Slim\Slim::getInstance()->request();
$q = json_decode($request->getBody());
$sql = "SELECT * FROM users WHERE username=:username";
try{
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("username", $username);
$stmt->execute();
$row=$stmt->fetchALL(PDO::FETCH_OBJ);
$dbh=null;
echo json_encode($row);
}
catch(PDOException $e){
if(db != null) $db = null;
echo $e->getMessage();
}
}
Ajax Code:
$("#checkLogIn").click(function()
{
username = $("#enterUser").val();
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + '/logIn/',
dataType: "json",
data: checkLogIn(),
success: function(data)
{
if(data != false)
{
$.ajax({
type: 'GET',
url: rootURL + "/getSessionCode/" + username,
dataType: "json",
success: sessionData
});
}
else
{
alert("Username and/or Password was incorrect");
}
}
})
});
function checkLogIn(data)
{
return JSON.stringify({
"username": $("#enterUser").val(),
"password": $("#enterPass").val(),
});
}
function sessionData(data){
session = data.sessionCode;
alert(username);
alert(session);
$.mobile.changePage("#mainMenu");
}
When I run the application and log in. It runs though no problem but when it reaches alert(session) it returns undefined. I have both session and username set globally as variables so that isn't an issue and when it reaches alert(username), it returns the username I entered.
I was able to solve my issue by adding in a for loop into the sessionData function
function sessionData(data){
for(var i = 0; i < 1; i++)
{
sessionStorage.code = data[i].sessionCode;
}
$.mobile.changePage("#mainMenu");
}

AJAX not running success function

I've got an AJAX script that lets the user login on the login page however the script seems to stop after it runs the beforeSend.
<script>
$(document).ready(function()
{
$('#login').click(function() {
var username=$("#username").val();
var password=$("#password").val();
var dataString = 'username='+username+'&password='+password;
if($.trim(username).length>0 && $.trim(password).length>0) {
$.ajax({
type: "POST",
url: "login.php",
data: dataString,
cache: false,
beforeSend: function(){
$("#login").val('Connecting...');
},
success: function(data){
if(data) {
$("body").load("<?php echo $dom; ?>").hide().fadeIn(1500).delay(6000);
window.location.href = "<?php echo $dom; ?>";
} else {
$('#shakeme').shake();
$("#login").val('Login')
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}
});
} return false;
});
});
</script>
The AJAX script sends the data to login.php
if(isset($_POST['username']) && isset($_POST['password'])) {
$username=clean($_POST['username']);
$password=clean($_POST['password']));
$sql = "SELECT password FROM user WHERE username='" . $username . "'";
$result = $conn->query($sql)->fetch_assoc();
$pass = $result['password'];
$salt = getSalt($pass);
$password = $salt . $password;
$password = $salt . hash('sha256', $password);
if(strcmp($pass,$password)==0) {
$_SESSION['login_user']=$username;
}
}
Am I doing something wrong with the PHP script? Am I meant to return data somehow? This is my first time using AJAX.
You need to return values from your login.php file as
login.php
if(strcmp($pass,$password)==0) {
$_SESSION['login_user']=$username;
echo true;
}else{
echo false;
}
exit;
and within js
success: function(data){
if (data == true) {
$("body") . load("<?php echo $dom; ?>") . hide() . fadeIn(1500) . delay(6000);
window.location.href = "<?php echo $dom; ?>";
} else {
$('#shakeme') . shake();
$("#login").val('Login')
$("#error") . html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
}
}

How to indirect call php file by ajax with post type and get json return then parse it to table

I have 2 php file, one is "Db_function.php" and "index.php", "index.php" will make a function call in "Db_function.php".
I want to make a call to "index.php" by ajax, here's my code
Html file
<Html>
<body>
<script type="text/javascript" src="js/index.js"></script>
<input type="button" value="Get" onclick="get()">
</body>
</html>
Js file
function get() {
$.ajax({ url: 'index.php',
data: {tag:'get_backup', email:'mail#mail.com', password:'123'},
type: 'post',
datatype:'json'
success: function(output) {
alert(output);
}
});
}
index.php
/*with connect value*/
if ($tag == 'get_backup'){
// store user
$email = $_POST['email'];
$password = $_POST['password'];
$user = $db->get_backup($email, $password);
Db_funtion.php
public function get_backup($email, $password) {
$result = mysql_query("SELECT * FROM users WHERE email = '$email'") or die(mysql_error());
// check for result
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$result = mysql_fetch_array($result);
$salt = $result['salt'];
$encrypted_password = $result['encrypted_password'];
$hash = $this->checkhashSSHA($salt, $password);
// check for password equality
if ($encrypted_password == $hash) {
// user authentication details are correct
$response = array();
$result2 = mysql_query("SELECT * FROM contact_store WHERE (email ='$email' AND backup_name='$email')") or die(mysql_error());
if (mysql_num_rows($result2) > 0) {
// looping through all results
// contact_stores node
$response["contact_stores"] = array();
while ($row = mysql_fetch_array($result2)) {
// temp user array
$contact_store = array();
$contact_store["backup_name"] = $row["backup_name"];
$contact_store["email"] = $row["email"];
$contact_store["data"] = $row["data"];
// push single contact_store into final response array
array_push($response["contact_stores"], $contact_store);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no contact_stores found
$response["success"] = 0;
$response["message"] = "No contact_stores found";
// echo no users JSON
echo json_encode($response);
}
}
} else {
// user not found
return false;
}
}
Json return like this
{"contact_stores":[{"backup_name":"nhi#gmail.com","email":"nhi#gmail.com","data":"[]"}],"success":1}
But my problem is when i press get button in html file, nothing happen.
Any help for me ?
It seems like you are not defining the get() function that you provide in the input element.
Try this HTML:
<input id="get" type="button" value="Get">
with this javascript:
$('#get').click(function() {
$.ajax({ url: 'index.php',
data: {tag:'get_backup', email:'mail#mail.com', password:'123'},
type: 'post',
datatype:'json'
success: function(output) {
alert(output);
}
})
});

php ajax login form

i want to make login form with session (with PHP + ajax), i send username from controller with json but it doesn't work. i don't know whats wrong, please help
this is the function in controller :
public function actionLogin()
{
$username = isset($_POST['username'])?$_POST['username']:null;
$password = isset($_POST['password'])?sha1($_POST['password']):null;
$json = new JsonHelper();
$result = array();
if($username && $password !=''){
$checkLogin = Administrator::model()->findByAttributes(
array('username'=>$username, 'password'=>$password));
$checkUser = Administrator::model()->findByAttributes(
array('username'=>$username));
$checkPass = Administrator::model()->findByAttributes(
array('password'=>$password));
$login = count($checkLogin);
$user = count($checkUser);
$pass= count($checkPass);
if($login==1)
{
$result['status'] = 'success';
$result['username'] = $username;
$json->addData('ajax', $result);
}
elseif($user == 1 && $pass == 0)
{
$result['status'] = 'wrongPass';
$json->addData('ajax', $result);
}
elseif($user == 0 && $pass == 1)
{
$result['status'] = 'wrongUser';
$json->addData('ajax', $result);
}
}
echo json_encode($json->getJson());
}
and this is the form_login.js file :
function login(){
var form = $('#login-form');
var formId = form.attr('id');
var action = form.attr('data-action');
var method = form.attr('data-method');
var formData = serializer(form); //don't mind this function
$.ajax(
{
url: action,
cache: false,
processData: false,
contentType: false,
type: method,
data: formData,
success: function(json)
{
// AJAX SUCCESS
var json = JSON.parse(result);
if(json['result']['ajax']['status']=='success')
{
//$_SESSION['username'] =json['username'];
window.location = baseUrl + "/appsterize/dashboard/index";
}
else if(json['result']['ajax']['status']=='wrongPass')
{
// Password wrong
alert("The password you entered is incorrect.");
}
else if(json['result']['ajax']['status']=='wrongUser')
{
// Username isn't exist
alert("Username isn't exist");
}
},
error: function(xhr, status, error)
{
// AJAX ERROR
var string = "<strong>Error!</strong> " + xhr['responseText'];
$(alertError).attr('data-text', string);
$(alertError).click();
},
});
}
some error is 'Uncaught ReferenceError: alertError is not defined'
Have an element with id = 'alertError'?
Could this be the solution:
$("#alertError").attr('data-text', string);
...
Basically, what #serakfalcon said above:
...
error: function(xhr, status, error)
{
// AJAX ERROR
var errorMsg = "<strong>Error!</strong> " + xhr['responseText'];
alert(errorMsg);
},
...

Categories