How to enter CSRF on ajax? - php

I have this code
---------- index.php ----------
<script>
function validLogin() {
var email=$('#memail').val();
var testEmail = /^[A-Z0-9._%+-]+#([A-Z0-9-]+\.)+[A-Z]{2,4}$/i;
var password=$('#mpass').val();
var dataString = email='+ email + '&password='+ password;
$.ajax({
type: "POST",
url: "processed.php",
data: dataString,
cache: false,
success: function(result){
var result=trim(result);
if(result=='correct'){
window.location='/';
} else {
}
}
});
return true;
}
function trim(str){
var str=str.replace(/^\s+|\s+$/,'');
return str;
}
</script>
<div class="login">
<div class="input-group">
<input type="text" id="memail" value="" placeholder="Email" class="memail">
</div>
<div class="input-group">
<input type="password" id="mpass" value="" placeholder="Password" class="mpassword">
</div>
<div class="checkout-submit-section">
<div class="payment-submit">
<div class="order-submit">
<button id="msubmit" type="submit" name="submit_button" class="greenx" style="margin-top:-20px;" onclick="validLogin()">
Login
</button>
</div>
</div>
</div>
</div>
and
------ processed.php ---------
<?php
session_start();
include_once('../db/ds.php');
$message=array();
if(isset($_POST['email']) && !empty($_POST['email'])){
$email = $mysqli->real_escape_string($_POST['email']);
$email= htmlentities($email);
}else{
$message[]='email';
}
if(isset($_POST['password']) && !empty($_POST['password'])){
$password = $mysqli->real_escape_string($_POST['password']);
$password= htmlentities($password);
}else{
$message[]='password';
}
$countError=count($message);
if($countError > 0){
for($i=0;$i<$countError;$i++){
}
}else{
$password=md5($password);
$query = "select * from user where email='$email' and password='$password'";
$res = $mysqli->query($query);
$checkUser = $res->num_rows;
if($checkUser > 0){
$lol = $res->fetch_array(MYSQLI_BOTH);
$iduser = $lol['id'];
$_SESSION['status']=true;
$_SESSION['id']=$iduser;
echo 'correct';
}else{
}
}
}
?>
maybe this code for CSRF, but I do not know how to use them
function createToken()
{
$token= base64_encode( openssl_random_pseudo_bytes(32));
$_SESSION['csrfvalue']=$token;
return $token;
}
function unsetToken()
{
unset($_SESSION['csrfvalue']);
}
function validation()
{
$csrfvalue = isset($_SESSION['csrfvalue']) ? mysql_real_escape_string($_SESSION['csrfvalue']) : '';
if(isset($_POST['csrf_name']))
{
$value_input=$_POST['csrf_name'];
if($value_input==$csrfvalue)
{
unsetToken();
return true;
}else{
unsetToken();
return false;
}
}else{
unsetToken();
return false;
}
}
<input type="hidden" name="csrf_name" value="<?php echo createToken();?>"/>
How to use CSRF without input <form action="" method="post">? Because when I test the security of this code, this code dangerous if not using CSRF.
I've been looking for to several sites , but they all use input form.
1.How to use CSRF in the above code ?
Whether my code is too simple? and could be tricked ? How do I secure it ?
If i use ajax , Whether I have to use CSRF ?
EDIT
--------------- processed.php ----------------
<?php
require '../../db/sessions.php';
require '../../db/ds.php';
require '../../db/error.php';
$user=$row['id'];
$message=array();
if(isset($_POST['emailx']) && !empty($_POST['emailx'])){
$emailx = $mysqli->real_escape_string($_POST['emailx']);
$emailx= htmlentities($emailx);
}else{
$message[]='email';
}
if(isset($_POST['hpx']) && !empty($_POST['hpx'])){
$hpx = $mysqli->real_escape_string($_POST['hpx']);
$hpx= htmlentities($hpx);
}else{
$message[]='hp';
}
if(isset($_POST['namax']) && !empty($_POST['namax'])){
$namax = $mysqli->real_escape_string($_POST['namax']);
$namax= htmlentities($namax);
}else{
$message[]='nama';
}
if(isset($_POST['token']) && !empty($_POST['token'])){
$tokens = $mysqli->real_escape_string($_POST['token']);
}else{
$message[]='email';
}
$countError=count($message);
if($countError > 0){
for($i=0;$i<$countError;$i++){
}
}else{
if(validation($tokens, $crsfa)==true) {
$query = "UPDATE user SET email='$emailx', nama='$namax', hp='$hpx' WHERE id='$user'";
$res = $mysqli->query($query);
echo 'OKS';
}else{
echo "Null";
return false;
}
}
?>
--------------- index.php ----------------
<meta name="csrf_token" content="<?php echo createToken();?>">
.
.
.
.
.
<script>
function validUbah() {
var hpx=$('#hp').val();
var emailx=$('#email').val();
var namax=$('#nama').val();
var token=$('[name="csrf_token"]').attr('content');
var dataString = 'hpx='+ hpx + '&emailx='+ emailx + '&namax='+ namax + '&token='+ token;
$.ajax({
type: "POST",
url: "processed.php",
data: dataString,
success: function(result){
var result=trim(result);
if(result=='OKS'){
$(".spinner").hide();
$(".spanlogin").show();
$(".spanlogin").html('Berhasil');
$(".nm7").html(namax);
} else {
$(".spinner").hide();
$(".spanlogin").show();
$(".spanlogin").html(result);
return false;
}
}
});
return true;
}
function trim(str){
var str=str.replace(/^\s+|\s+$/,'');
return str;
}
</script>
--------------- sessions.php ---------------------
function unsetToken()
{
unset($crsfa);
createToken();
}
function validation($varians, $crsfa)
{
$csrfvalue = isset($crsfa);
if(isset($varians))
{
$value_input=$varians;
if($value_input==$csrfvalue)
{
unsetToken();
return true;
}else{
unsetToken();
return false;
}
}else{
unsetToken();
return false;
}
}
$crsfa=$_SESSION['csrfvalue'];

if you are implementing anti-CSRF techniques, you should use the token on every post/ajax request.
Maybe you can implement your token as meta-Tag:
<meta name="csrf-token" content="MERvRHE0MmVHcSU9OEUfPHs3JSALZQpcAC1ccBVcZA14KVlxN35xHQ==">
Whatever you do, do NOT use MD5 for hashing passwords.
Use PHP's crypt() or other means for password storage.
Cheers

Related

AJAX : PHP login ajax does'nt work

I have a login form using 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.
php :
<?php
include 'db.php';
$email = trim($_POST['email']);
$password = trim($_POST['password']);
$cek = mysqli_query($conn, "SELECT * FROM user_csr WHERE email='$email' AND csr_pwd='$password'");
if(mysqli_num_rows($cek)>0)
{
echo 'true';
}
else
{
echo 'false';
}
?>
ajax :
function ceklogin(){
var email = document.getElementById('mail').value;
var password = document.getElementById('pass').value;
$.ajax({
url: 'tes.php',
method: 'POST',
data: {email: email, password: password},
success: function(html) {
if(html == 'true')
{
alert("login success");
}
else
{
alert("login failed");
}
}
});
}
<form>
<input type="email" name="email" id="mail" required>
<input type="password" name="password" id="pass" required>
<button type="submit" class="w3ls-cart" onclick="ceklogin()">Sign In</button>
</form>
the result of an alert is 'login failed'. but email and passwords are in accordance with the database.Hope anyone can help me out on this one, thanks in advance.
This should work. Just make sure you have a DIV as identified below to show your result.
function ceklogin() {
var email = document.getElementById('mail').value;
var password = document.getElementById('pass').value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("resultDiv").innerHTML = this.responseText;
}
};
var sentInfo = "email=" + email + "&password=" + password;
xhttp.open("POST", "YourPHPFileHERE.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(sentInfo);
}
you should try adding "===" in your if condition.
` if(html === 'true')
{
alert("login success");
}
else
{
alert("login failed");
}`

JQuery.min.js: 4 POST 500 (Internal Server Error)

It works on localhost but not in server I. Another warning is
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check...
Here is my form:
<form action ="" method="post" id="frmlogin" class="text" onsubmit="return flogin();">
<input type="text" name="user" id="email" placeholder="Username*" required>
<input type="password" name="pass" id="password" placeholder="Password*" required>
<input type="submit" name="login" class="login loginmodal-submit" value="Login">
Here is my Javascript:
<script>
function flogin() {
$("#errorlog").html("");
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
var request = $.ajax({
type: 'post',
url: 'action/login_action.php',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {email: email, password: password, login: "login"},
success: function (response) {
var res = parseInt(response.trim());
alert(response);
if (response.trim() == "10") {
$("#errorlog").html("Email and Password is must");
//alert(response);
}
else if (res >= 1) {
//alert(response);
document.getElementById('email').value = "";
document.getElementById('password').value = "";
window.location = "index.php";
}
else {
$("#errorlog").html("E-mail or Password is incorrect");
}
}, error: function (response) {
alert("FAIL");
alert(response);
//alert(response[0]);
//response is json you need to parse it
// var json = response,
// obj = JSON.parse(json);
// alert(response.length);
// alert(response.length);
}
});
return false;
}
</script>
The php code:
<?php
error_reporting(1);
if (!isset($_SESSION)) {
session_start();
}
require_once("../config/encrypt.php");
require_once '../config/functions.inc';
require_once '../config/database.php';
///////////////login check////////////
if ($_POST['login'] == "login") {
echo "fdgdffdf";
if (empty($_POST['password']) or empty($_POST['email'])) {
echo "10";
exit;
} else {
$en = new Encryption();
$password = trim($_POST['password']);
$email = $en->removeBadChars(trim($_POST['email']));
$db = new Database();
if ($db->open())
$password = sha1($password);
{
$sql = "select * from phpap105_signup where email='$email' and password='$password'";
// echo "select * from phpap105_signup where email='$email' and password='$password'";
//exit;
$res = mysqli_query($db->resourse(), $sql);
$cou = mysqli_num_rows($res);
if ($cou >= 1) {
$row = mysqli_fetch_array($res);
$_SESSION['client_user_id'] = $row[0];
$_SESSION['client_user_id1'] = $row[0];
$_SESSION['client_username'] = $row[1];
$_SESSION['client_logged'] = true;
// $_SESSION['adm_status'] = $row['status'];
$r = "success";
} else {
$r = "fail";
}
echo $cou;
// exit;
}
}
echo $r;
}
/////login end/////////////////
?>

username availability PDO not working

This is my HTML Code
<input type="text" class="form-control" id="stfmail" name="staffmail" placeholder="E-Mail" required="required"><span id="result"></span>
In jQuery Ajax
<script type="text/javascript">
$(document).ready(function(){
$("#stfmail").keyup(function() {
var name = $(this).val();
if(name.length > 1)
{
$("#result").html('checking...');
$.ajax({
type : 'POST',
url : '../include/check_availability.php',
data : $(this).serialize(),
success : function(data)
{
$("#result").html(data);
}
});
return false;
}
else
{
$("#result").html('');
}
});
});
</script>
PHP
if($_POST)
{
$username = $_POST['name'];
$ob->useravailable($username);
}
public function useravailable($username)
{
$stmt=$this->conn->prepare("select user_name from users where user_name=:uname and delet='0'");
$stmt->execute(array(':uname'=>$username));
if($stmt->rowCount()>0)
{
echo "<span style='color:brown;'>Sorry username already taken !!!</span>";
}
else
{
echo "<span style='color:green;'>available</span>";
}
}
Here i type a username..but in useravailable function only else part is working.. I type Existing username it works the else part available message is shown..
Please help me
thanks
<script type="text/javascript">
$(document).ready(function(){
$("#stfmail").keyup(function() {
var name = $(this).val();
if(name.length > 1)
{
$("#result").html('checking...');
$.ajax({
type : 'POST',
url : '../include/check_availability.php',
data : $(this).serialize(),
success : function(data)
{
$("#result").html(data);
if(data) {
$(".redbold").html('already this username is there ').show();
$("#username").focus();
}
}
});
return false;
}
else
{
$("#result").html('');
}
});
});
</script>
if($_POST)
{
$username = $_POST['name'];
$query = mysql_query("SELECT user_name from users where user_name ='".$username ."' ", $con);
while ($row = mysql_fetch_assoc($query)) {
echo $row['user_name '];
}
}

jQuery AJAX php Login Not passing data properly

I get a Failure object Object notice. I have looked at multiple examples and still can't figure out the error. I believe my AJAX is not set up properly. The PHP should be good to go, I have a local database and use jQuery with AJAX to handle the request and the response. The page should redirect to the dashboard.php when I have success with logging in.
Here is the form:
<div class="row">
<div class="col-xs-12 text-center">
<h1 class="text_white bad_login">
Log In Please
</h1>
</div>
<div class="col-xs-12 col-sm-4 col-sm-offset-4">
<form class="text_white" method="post" action="/login.php">
<div class="form-group">
<label for="username">User Name:</label>
<input name="username" type="text" class="form-control" id="username" placeholder="User Name">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input name="password" type="password" class="form-control" id="password" placeholder="Password">
</div>
<button type="submit" class="btn btn-default" id="login" name="login">Log In</button>
</form>
</div>
</div>
Here is the PHP:
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// grab form fields and save as php variables
$username = '';
$password = '';
// if (isset($_POST['name'], $_POST['passphrase'])){
// $username = $_POST['name'];
// echo $username;
//
// $password = $_POST['pass'];
// echo $password;
// }
// else {
// $username = null;
// $password = null;
// }
if (isset($_POST['password'])){
$password = $_POST['password'];
//echo $password;
}
else {
$password = null;
}
if (isset($_POST['username'])){
$username = $_POST['username'];
//echo $username;
}
else {
$username = null;
}
// create query to run on database
$qry = "SELECT username, password FROM user WHERE username='".$username. "' AND password='".$password. "' ";
$result = mysqli_query($conn, $qry) or die(mysqli_error($conn));
$num_row = mysqli_num_rows($result);
$row = mysqli_fetch_assoc($result);
// check to see if it is only 1 match and then save that information to the session for later use
if( $num_row == 1 ) {
$_SESSION['username'] = $row['username'];
//echo $_SESSION['username'];
$_SESSION['password'] = $row['password'];
//echo $_SESSION['password'];
}
else {
echo ' FALSE! ';
}
// $result->json_encode($result);
echo json_encode($result);
}
//close the connection
$conn->close();
Here is the AJAX which i believe contains the error:
//jQuery(document).ready(function($){
// $('#login').click(function(event){
// event.preventDefault();
// var username = $('#username').val();
// var password = $('#password').val();
//
// if ( $('#username').val() === '' || $('#password').val() === '') {
// $('.bad_login').text('PLEASE ENTER BOTH USERNAME AND PASSWORD');
// }
//
// $.ajax({
// type: 'POST',
// url: '/ChurchCheckIn/login.php',
// dataType: 'json',
// data: 'username='+username+'&password='+password,
//// data: { username : username, password : password},
// success: function(data){
//// if(data === 'true') {
// window.location='/ChurchCheckIn/dashboard.php';
// console.log('if true.... ' + data);
//// }
//// else {
//// $('.bad_login').text('WRONG USERNAME OR PASSWORD TRY AGAIN PLEASE...');
//// console.log('bad html test for other stuff' + data);
//// }
// },
//// fail: function(data){
//// jQuery.parseJSON(data);
//// console.log('failure' + data);
//// $('.bad_login').text('WRONG USERNAME OR PASSWORD TRY AGAIN PLEASE...');
//// },
//// done: function() {
//// console.log('success' + data);
//// window.location='/ChurchCheckIn/dashboard.php';
//// },
// beforeSend:function() {
// $('.bad_login').text('Loading....');
// }
// });
// return false;
// });
//});
jQuery(document).ready(function ($) {
$('#login').click(function (event) {
event.preventDefault();
var username = $('#username').val();
var password = $('#password').val();
var response = {};
if ($('#username').val() === '' || $('#password').val() === '') {
$('.bad_login').text('PLEASE ENTER BOTH USERNAME AND PASSWORD');
}
var request = $.ajax({
url: '/ChurchCheckIn/login.php',
type: 'POST',
data: 'username='+username+'&password='+password,
dataType: 'json'
});
request.done(function (data) {
response = $.parseJSON(data);
console.log(response);
if (response.success == 'true') {
console.log('success' + data);
window.location = '/ChurchCheckIn/dashboard.php';
} else {
console.log('data came back false');
}
});
request.fail(function (data) {
console.log('failure' + data);
$('.bad_login').text('WRONG USERNAME OR PASSWORD TRY AGAIN PLEASE...');
});
});
});
I have tried multiple ways, i believe one sends an object and the other expects to receive a string. I don't believe I am way offbase, I even made sure to use the newest practices. mysqli in my php and the newer form of success with my jQuery.
Try using data as Javascript object
var request = $.ajax({
url: '/ChurchCheckIn/login.php',
type: 'POST',
data: {username: username, password: password}
dataType: 'json'
});
if that didn't work, use JSON.stringify around the data object, but it should work because jQuery converts the data object automatically.
I believe in a row:
if (response.success == 'true') {
}
there is no element success try check if response variable is not empty.

Can't figure out what I'm doing wrong with this php conditional

I'm trying to do a really simple login system using php. I have two files at the moment: index.php and verifyCredentials.php
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test Site</title>
</head>
<body>
<h1>Welcome to My Test Homepage!</h1>
<?php if ($_SESSION['logged_in'] != "true") : ?>
<form method="post" action="verifyCredentials.php">
Username: <input type="text" name="username" value=""/><br>
Password: <input type="password" name="password" value=""/><br>
<input type="submit" name="submit" value="Submit"/><br>
</form>
<?php else : ?>
<h2>You're logged in! :)</h2>
<?php endif ?>
<?php if($_GET['verferr']==1){echo "<b>Login failed: incorrect username or password.</b>";} ?>
</body>
</html>
verifyCredentials.php
<?php
$username = $_POST['username'];
$password = $_POST['password'];
if($username == "myusername" && $password == "letmein")
{
$_SESSION['logged_in'] = "true";
header("Location: index.php");
exit;
}
else
{
$loginfailed_param = "?verferr=1";
header("Location: index.php" . $loginfailed_param);
exit;
}
?>
I've successfully made it so that if your username/password were incorrect (i.e. not equal to myusername and letmein), then it redirects to the login page and echo's an error message under the form.
I'm trying to make it so that when they do verify that the form on index.php, the form disappears and is replaced with some success text. But, when I type in myusername and letmein, it just redirects to the login without an error and the form still showing.
From the research I've done, I'm required to use the if-else php structure as shown in my index.php file if I want to have html in between my php nodes, but am I doing this incorrectly?
Can anyone tell what I am doing wrong here?
PHP Sessions require that you call session_start() at the top of every page where you use $_SESSION. I don't see it in your example.
If you are going to use sessions to store data make sure you have session_start(); at the top of every page you call. Otherwise it won't read in the session identifier and will assume you want to start a new one.
So at the top of your index.php and verifyCredentials.php add the command. But make sure you have it as the first line of code on the page. You will then need to add it to any page that is directly requested.
For example, if you have index.php and it includes form.php and nav.php, then only index.php will need the session_start(), but if you have a link to form_processing.php, then form_processing.php will need to have session_start() as well.
Aww, you accepted right as I had this ready. :(
Here is what you need to use. anyway..
(Also, you should use jQuery for better transitional effects, see below)
<?php
session_start();
$args = array(
'username' => FILTER_SANITIZE_SPECIAL_CHARS,
'password' => FILTER_SANITIZE_SPECIAL_CHARS);
$post = filter_input_array(INPUT_POST, $args);
if ($post) {
$username = $post['username'];
$password = $post['password'];
if($username == "myusername" && $password == "letmein") {
$_SESSION['logged_in'] = true;
header("Location: index.php");
exit;
} else {
$loginfailed_param = "?verferr=1";
header("Location: index.php" . $loginfailed_param);
exit;
}
}
if ($_SESSION['logged_in'] === true) {
//User has logged in
}
?>
Using jQuery
HTML
<div id="loginForm">
<form id="myLoginForm">
<input id="username">
<input id="password">
<button id="formSubmit" name="formSubmit">Submit Form</button>
<input style="display: none;" type="text" id="realSubmit" name="realSubmit" value="hidden">
</form>
</div>
<div id="successPage">
Thank you for loggging in...
</div>
<div id="loginHome">
Login Homepage
Welcome <span id="displayUsername"></span>
</div>
jQuery
(function($){
$(function(){
$("#formSubmit").on('click', function() {
var username= $("#username").val();
var password = $("#password").val();
var data = {username: username, password: password};
delegateAjax('../myAjax.php', data, 'POST');
});
});
function delegateAjax(url, data, responseType, dataType, callback) {
function successHandler(data) {
console.log("Ajax Success");
var responseData = $.parseJSON(data);
if (responseData.status === 'Success') {
$("#loginForm").fadeOut(1500, function() {
$("#successPage").fadeIn(1500, function() {
$(this).fadeOut(1500, function() {
$("#displayUsername").html(responseData.username);
$("#loginHome").fadeIn(1500);
});
});
});
}
};
function failureHandler(xhr, status, error) {
console.log("Ajax Error");
console.log(status);
console.log(error);
console.dir(xhr);
};
function handler404(xhr, status, error) {
console.log("404 Error");
console.log(status);
console.log(error);
console.dir(xhr);
};
function handler500(xhr, status, error) {
console.log("500 Error");
console.log(status);
console.log(error);
console.dir(xhr);
};
url = typeof url !== 'undefined' ? url : 'js/ajaxDefault.php';
data = typeof data !== 'undefined' ? data : new Object();
responseType = typeof responseType !== 'undefined' ? responseType : 'GET';
dataType = typeof dataType !== 'undefined' ? dataType : 'json';
callback = typeof callback !== 'undefined' ? callback : 'callback';
var jqxhr = $.ajax({url: url, type: responseType, cache: true, data: data, dataType: dataType, jsonp: callback,
statusCode: { 404: handler404, 500: handler500 }});
jqxhr.done(successHandler);
jqxhr.fail(failureHandler);
};
})(jQuery);
PHP
myAjax.php
<?php
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if (!IS_AJAX) {
$response['status'] = 'Error';
$response['message'] = 'Same Origin Policy Error';
echo json_encode($response);
exit;
}
$pos = strpos($_SERVER['HTTP_REFERER'], getenv('HTTP_HOST'));
if ($pos === false) {
$response['status'] = 'Error';
$response['message'] = 'Same Origin Policy Error';
echo json_encode($response);
exit;
}
function validUser($data) {
//connect to db and validate user
$dbi = new mysqliObject();
$params['string'] = $data['username'];
$dbi->newSelect($params);
$table = 'users';
$select = '*';
$where = '`username` = ? LIMIT 1';
if ($dbi->exec($table, $select, $where)) {
$result = $dbi->result[0];
return passwordVerify($result['password']); //true/false
} else {
//for debugging
//echo 'Last Error: '.$dbi->get('lastError').'<br>'."\r\n";
//echo 'Last Query: '.$dbi->get('lastQuery').'<br>'."\r\n";
return false;
}
}
$args = array(
'username' => FILTER_SANITIZE_SPECIAL_CHARS,
'password' => FILTER_SANITIZE_SPECIAL_CHARS);
$post = filter_input_array(INPUT_POST, $args);
if ($post) {
if (validUser($post)) {
$response['status'] = 'success';
$response['username'] = $username;
echo json_encode($response);
exit;
} else {
$response['status'] = 'Failed';
$response['message'] = 'Username/Password Invalid';
echo json_encode($response);
exit;
}
}
$response['status'] = 'Error';
$response['message'] = 'POST Data Invalid';
echo json_encode($response);
exit;

Categories