Validate login form with JS/PHP - javascript

I want to be able to either send a user to a restricted area or return some text that says Email and or password do not exist or something similar. I'm having trouble getting this to work as whether or not the email and password are correct NOTHING happens. I'm sending the form to the index page where the script to run this sits. Not sure why I'm not redirecting or getting any kind of errors.
The restricted page checks if a $_SESSION variable isset(), if not then send them back home.
JS
loginBtn.addEventListener('click', e => {
e.preventDefault();
ajaxRequests.login(`login_email=${ loginEmail.value }&login_password=${ loginPassword.value }`);
});
ajaxRequests.login()
login(formData) {
return new Promise((resolve, reject) => {
this.xhr.open('POST', '//localhost/mouthblog/', true);
this.xhr.send(formData);
this.xhr.onload = () => {
if (this.xhr.status == 200) {
resolve();
} else {
reject(this.xhr.statusText);
}
};
this.xhr.onerror = () => {
reject(this.xhr.statusText);
};
});
}
this is the script that is supposed to run when form is sent
if (isset($_POST['login_email']) && isset($_POST['login_password'])) {
$email = htmlentities($_POST['login_email'], ENT_QUOTES, 'ISO-8859-15');
$password = htmlentities($_POST['login_password'], ENT_QUOTES, 'ISO-8859-15');
$login = new Login($email, $password);
unset($login);
}
check for valid $_SESSION vars
session_start();
if (!isset($_SESSION['id']) || !isset($_SESSION['name']) || !isset($_SESSION['email'])) {
header('Location: index.php');
}
login query (just incase it is needed)
class Login extends Connection {
public function __construct($email, $password) {
$this->connect();
$sql = "SELECT `id`, `name`, `email`, `password` FROM `users` WHERE `email`=:email";
$query = $this->connect()->prepare($sql);
$result = $query->execute(
[
':email' => htmlentities($email, ENT_QUOTES, 'ISO-8859-15'),
]
);
// check if EMAIL exists
if ($result) {
$row = $query->fetch(PDO::FETCH_OBJ);
$id = htmlentities($row->id, ENT_QUOTES, 'ISO-8859-15');
$name = htmlentities($row->name, ENT_QUOTES, 'ISO-8859-15');
$email = htmlentities($row->email, ENT_QUOTES, 'ISO-8859-15');
$hashed_password = htmlentities($row->password, ENT_QUOTES, 'ISO-8859-15');
// check if user input PASSWORD matches the unhashed PASSWORD in the database
if (password_verify($password, $hashed_password)) {
$_SESSION['id'] = htmlentities($id, ENT_QUOTES, 'ISO-8859-15');
$_SESSION['name'] = htmlentities($name, ENT_QUOTES, 'ISO-8859-15');
$_SESSION['email'] = htmlentities($email, ENT_QUOTES, 'ISO-8859-15');
header('Location: blog_roll.php');
} else {
header('Location: index.php');
}
} else {
echo 'THAT EMAIL ADDRESS DOES NOT EXIST';
}
}
}

You have to set the content type for your ajax request
this.xhr.open('POST', '//localhost/mouthblog/', true);
this.xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
this.xhr.send(formData);

Related

$_SESSION not working while successful login

index.php
<script>
$(document).ready(function(){
$("#login").click(function(e){
e.preventDefault();
email = $("#cs-username-1").val();
password = $("#cs-login-password-1").val();
if(email=='' || password=='')
{
$("#loginsuccess").html("<p id='red'>All fields are mandatory!<p>");
}
else
{
$.ajax({
type:"POST",
data:{"email":email,"password":password},
url:"login.php",
success: function(data)
{
if (typeof data !== 'object') {
data = JSON.parse(data);
}
if (data.redirect) {
window.location.replace(data.redirect);
} else {
$("#loginsuccess").html('<p id="red">' + data.error + '</p>');
}
}
});
}
});
});
</script>
login.php
<?php
include("config.php");
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = md5($_POST['password']);
$sql = mysqli_query($con,"select student_id from student where email='".$email."' and password='".$password."' and status='1'");
if (mysqli_num_rows($sql) > 0)
{
$results = mysqli_fetch_array($sql);
$_SESSION['student'] = $results['student_id'];
if (!isset($_POST))
{
header ("Location: dashboard.php");
}
else
{
echo json_encode(array('redirect' => "dashboard.php"));
}
}
else
{
echo json_encode(array('error' => 'Wrong email or password or may be your account not activated.'));
}
?>
dashboard.php
<?php
session_start();
echo $_SESSION['student'];
/*if(!isset($_SESSION['student']))
{
header("location: index.php");
}*/
include('assets/db/config.php');
?>
In this code I am simply create login module. Here, what happen I am create login via jQuery where I have login.php file and I am storing student_id inside the session variable but when I redirect to dashboard.php and echo $_SESSION['student'] then it throw an error i.e. Notice: Undefined index: student in C:\xampp\htdocs\test\dashboard.php on line 3 I don't know why where am I doing wrong? Please help me.
Thank You
Please start the session in login.php file :
include("config.php");
session_start();
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = md5($_POST['password']);
Or put the session_start in config.php file

Sessions in AngularJS and PHP application

I have an AngularJS application that I am updating to use PHP 7. Currently I have a custom session handler setup for sessions:
Custom Session Handler (session.php)
function sess_open( $path, $name ) {
return true;
}
function sess_close( ) {
$sessionId = session_id();
return true;
}
function sess_read( $id ) {
$db = dbConn::getConnection();
$stmt = "SELECT session_data FROM session where session_id =" . $db->quote($id);
$result = $db->query($stmt);
$data = $result->fetchColumn();
$result->closeCursor();
return $data;
}
function sess_write( $id, $data ) {
$db = dbConn::getConnection();
$tstData = sess_read( $id );
if (!is_null($tstData)) {
// if it does then do an update
$stmt = "UPDATE session SET session_data =" . $db->quote($data) . " WHERE session_id=" . $db->quote($id);
$db->query($stmt);
}
else {
// else do an insert
$stmt = "INSERT INTO session (session_id, session_data) SELECT ". $db->quote($id) . ", ". $db->quote($data) . " WHERE NOT EXISTS (SELECT 1 FROM session WHERE session_id=" . $db->quote($id) . ")";
$db->query($stmt);
}
return true;
}
function sess_destroy( $id ) {
$db = dbConn::getConnection();
$stmt = "DELETE FROM session WHERE session_id =" . $db->quote($id);
setcookie(session_name(), "", time() - 3600);
return $db->query($stmt);
}
function sess_gc( $lifetime ) {
$db = dbConn::getConnection();
$stmt = "DELETE FROM session WHERE timestamp < NOW() - INTERVAL '" . $lifetime . " second'";
return $db->query($stmt);
}
session_name('PROJECT_CUPSAW_WEB_APP');
session_set_save_handler("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc");
session_start();
ob_flush();
In my app.js I have a continuous check to see if the user is authenticated and can access the application.
App.js
/*
* Continuous check for authenticated permission to access application and route
*/
app.run(function($rootScope, $state, authenticationService, ngToast) {
$rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams) {
authenticationService.isAuthenticated()
.success(function () {
if(toState.permissions) {
ngToast.dismiss();
event.preventDefault();
$state.go("logout"); // NEEDS TO CHANGE - Unauthorized access view
return;
}
})
.error(function () {
ngToast.dismiss();
event.preventDefault();
localStorage.clear();
$state.go("authentication"); // User is not authenticated; return to login view
return;
});
ngToast.dismiss();
});
});
In the code above, isAuthenticated runs isUserAuthorized.php
isAuthenticated
/*
* Check if user is authenticated; set role/permissions
*/
this.isAuthenticated = function() {
return $http.post(baseUrl + '/isUserAuthorized.php');
};
isUserAuthorized.php
<?php
require_once 'session.php';
// Check to ensure user is authenticated to initiate request
if (array_key_exists('authenticated', $_SESSION) && $_SESSION['authenticated']) {
return http_response_code(200);
} else {
// Clear out all cookies and destroy session
if( array_key_exists('HTTP_COOKIE', $_SERVER)){
$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
foreach($cookies as $cookie) {
$parts = explode('=', $cookie);
$name = trim($parts[0]);
setcookie($name, '', time()-1000);
setcookie($name, '', time()-1000, '/');
}
}
session_destroy();
return http_response_code(401);
}
The session should be started when session.php is required. It appears that this is not happening though. Upon accessing the application, the login page is displayed, but isUserAuthorized.php is throwing a warning:
Warning: session_start(): Failed to read session data: user (path: /var/lib/php/mod_php/session) in session.php
When I select the Login button, login.php is called, but the user gets brought right into the application, despite incorrect credentials.
login.php
<?php
require_once '../database.php';
require_once 'session.php';
require_once 'ldap.php';
$_SESSION['authenticated'] = false;
//$conn = connect_db();
try {
$data = json_decode(file_get_contents('php://input'));
$username = strtolower($data->username);
$password = $data->password;
// Check domain credentials; return user token if verified
if(ldap_authenticate($username, $password)) {
$_SESSION['authenticated'] = true;
}
else {
echo('Invalid username and/or password!');
return http_response_code(400);
}
}
catch(PDOException $e) {
return http_response_code(400);
}
I'm not entirely sure what's causing this odd behavior, and why the session isn't being created. Do I need to explicitly call the sess_write function?
Update
I discovered that removing the require_once 'session.php' from login.php causes the proper behavior. The user is able to login when they provide valid credentials. However, the session data is still never being written to the database. Any idea why?
The issues came down to my session handler. As of PHP 7, the sess_read function must return a string. This was causing the warning:
Warning: session_start(): Failed to read session data: user (path: /var/lib/php/mod_php/session) in session.php
I fixed this by returning '' when $data was null.
This caused issues with my sess_write function knowing when to insert and when to update. I fixed this by changing the SQL.
Ultimately I ended up making the session handler a class, as shown in the final result:
<?php
require_once ('../database.php');
class CustomSessionHandler implements SessionHandlerInterface{
public function open( $path, $name ) {
return true;
}
public function close( ) {
return true;
}
public function read( $id ) {
$db = dbConn::getConnection();
$stmt = "SELECT session_data FROM session where session_id =" . $db->quote($id);
$result = $db->query($stmt);
$data = $result->fetchColumn();
$result->closeCursor();
if(!$data){
return '';
}
return $data;
}
public function write( $id, $data ) {
$db = dbConn::getConnection();
//Works with Postgres >= 9.5
//$stmt = "INSERT INTO session (session_id, session_data) VALUES (" . $db->quote($id) . ", " . $db->quote($data) . ") ON CONFLICT (session_id) DO UPDATE SET session_data=" . $db->quote($data) . ";";
//Works with Postgres < 9.5
$stmt = "UPDATE session SET session_data=" . $db->quote($data) . " WHERE session_id=" . $db->quote($id) . ";";
$db->query($stmt);
$stmt = "INSERT INTO session (session_id, session_data) SELECT ". $db->quote($id) . ", ". $db->quote($data) . " WHERE NOT EXISTS (SELECT 1 FROM session WHERE session_id=" . $db->quote($id) . ");";
$db->query($stmt);
return true;
}
public function destroy( $id ) {
$db = dbConn::getConnection();
$stmt = "DELETE FROM session WHERE session_id =" . $db->quote($id);
setcookie(session_name(), "", time() - 3600);
$data = $db->query($stmt);
return true;
}
public function gc( $lifetime ) {
$db = dbConn::getConnection();
$stmt = "DELETE FROM session WHERE timestamp < NOW() - INTERVAL '" . $lifetime . " second'";
$data = $db->query($stmt);
return true;
}
}
session_name('PROJECT_CUPSAW_WEB_APP');
$handler = new CustomSessionHandler();
session_set_save_handler($handler, false);
session_start();
ob_flush();

How can i get result from PHP fetch assoc

// Request password
$app->get('/api/admin/forgot', function(Request $request, Response $response){
$email = $request->getParam('email');
$sql = "SELECT admin_password FROM administrators WHERE admin_email = '$email' ";
try{
$db = new db();
$db = $db->connect();
$stmt = $db->query($sql);
$admin = $stmt->fetch(PDO::FETCH_ASSOC);
$db = null;
if($admin == null){
echo json_encode(array(
"errno" => 1,
"message" => "No account",
)
);
return;
}
echo $admin;
require_once "vendor/autoload.php";
//PHPMailer Object
$mail = new PHPMailer;
//From email address and name
$mail->From = "contact#SMS.com";
$mail->FromName = "SAMPLES Management Software";
//To address and name
$mail->addAddress($email);
//Address to which recipient will reply
$mail->addReplyTo("contact#SMS.com", "SAMPLE Management Software");
//Send HTML or Plain Text email
$mail->isHTML(true);
$mail->Subject = "Password recovery";
$mail->Body = "<h3>Password recovery<h3></br><p>Hi there, your password is '$admin'</p>";
if(!$mail->send()) {
echo json_encode(array(
"errno" => 0,
"message" => "Email not sent.",
)
);
} else {
echo json_encode(array(
"errno" => 0,
"message" => "Email sent.",
)
);
}
} catch(PDOException $e) {
echo json_encode(array(
"errno" => 1,
"feedback" => $e->getMessage(),
"message" => "Error occured",
)
);
}
}
);
Okay so i have this code to retrieve passwords and send to mail directly, it works great and i get the mail but the only problem is i am getting the password as 'array'. The password is $admin. Any help? Thanks in advance
With $stmt->fetch(PDO::FETCH_ASSOC); you get a row ( in this case the first row) and not the column values
for get the column values you should use
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$admin = $row['admin_password'];
and if you retunr more than a value you shold loop over the query result

Session variables are not being set, php sql

So my problem is that i'm trying to check if some session variables are set, and they should be, but when I check them they dont have a value.
So first of I have this HTML form that takes an Email and Password input
HTML CODE:
<form class="login_form" action="includes/process_login.php" method="POST" name="login_form">
<input type="text" placeholder="Email" name="email">
<input type="password" placeholder="Password" name="password" >
<input type="button" value="LOGIN" class="login_button" onclick="formhash(this.form, this.form.password);">
</form>
And as you can see my submit button first of all goes to a javascript that hashes the input.
JAVASCRIPT CODE:
function formhash(form, password) {
// Create a new element input, this will be our hashed password field.
var p = document.createElement("input");
// Add the new element to our form.
form.appendChild(p);
p.name = "p";
p.type = "hidden";
p.value = hex_sha512(password.value);
// Make sure the plaintext password doesn't get sent.
password.value = "";
// Finally submit the form.
form.submit();
}
And after it is done hashing the password it sends the form information to the target which is "includes/process_login.php"
PROCESS_LOGIN.PHP CODE:
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start(); // Our custom secure way of starting a PHP session.
if (isset($_POST['email'], $_POST['p'])) {
$email = $_POST['email'];
$password = $_POST['p']; // The hashed password.
if (login($email, $password, $mysqli) == true) {
// Login success
header('Location: ../protected_page.php');
} else {
// Login failed
header('Location: ../index.php?error=1['.$email.', '.$password.']');
}
} else {
// The correct POST variables were not sent to this page.
echo 'Invalid Request';
}
?>
And from here it sends the $email and $password values into the function login:
FUNCTION LOGIN CODE:
function login($email, $password, $mysqli){
if($stmt = $mysqli->prepare("SELECT id, username, password FROM users WHERE email = ? LIMIT 1")){
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($user_id, $username, $db_password);
$stmt->fetch();
if($stmt->num_rows == 1){
if(checkbrute($user_id, $mysqli) == true){
return false;
}else{
if (password_verify($password, $db_password)) {
$user_browser = $_SERVER['HTTP_USER_AGENT'];
$user_id = preg_replace("/[^0-9]+/", "", $user_id);
$_SESSION['user_id'] = $user_id;
$username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username);
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512',
$db_password . $user_browser);
return true;
}else{
$now = time();
$mysqli->query("INSERT INTO login_attempts(user_id, time)
VALUES ('$user_id', '$now')");
return false;
}
}
}else{
return false;
}
}
}
Now here comes part of the problem, in this code it stores a session:user_id values, session:username value and session:login_string value.
But the problem is that the session does not get stored anything.
Because when I then get redirected to the so called "protected_page.php" it then checks if these values are set or not and returns that they are not set.
THE LOGIN_CHECK CODE ( that checks if we are logged in or not)
function login_check($mysqli){
if (isset($_SESSION['user_id'],
$_SESSION['username'],
$_SESSION['login_string']
)) {
$user_id = $_SESSION['user_id'];
$login_string = $_SESSION['login_string'];
$username = $_SESSION['username'];
echo $user_id;
$user_browser = $_SERVER['HTTP_USER_AGENT'];
if ($stmt = $mysqli->prepare("SELECT password
FROM users
WHERE id = ? LIMIT 1")) {
$stmt->bind_param('i', $user_id);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
$stmt->bind_result($password);
$stmt->fetch();
$login_check = hash('sha512', $password . $user_browser);
if (hash_equals($login_check, $login_string) ){
return true;
}else{
return false;
}
}else{
return false;
}
}else{
return false;
}
}else{
return false;
}
}
Sorry about this post being very long, but I could really need some new angles. Thanks!
PS Here is the "custom set session function"
function sec_session_start(){
$session_name = 'sec_session_id';
session_name($session_name);
$secure = true;
$httponly = true;
if(ini_set('session.use_only_cookies', 1) === FALSE){
header("Location: ../error.php?err=Could not initiate a safe session (ini_set)");
exit();
}
$cookieParams = session_get_cookie_params();
session_set_cookie_params($cookieParams["lifetime"],
$cookieParams["path"],
$cookieParams["domain"],
$secure,
$httponly);
session_start();
session_regenerate_id(true);
}

Error when comparing hashes when logging in

i'm creating a simple login system, i has the passwords using sha256 and store a salt using a random number in the database. However when i try to log in, when it goes to compare the hashes it fails. Can anyone see why?
<?php
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$mysql_db_hostname = "localhost";
$mysql_db_user = "root";
$mysql_db_database = "login";
$con = mysql_connect($mysql_db_hostname, $mysql_db_user) or die("Could not connect database");
mysql_select_db($mysql_db_database, $con) or die("Could not select database");
$query = "SELECT password, salt FROM registered_users WHERE username='$username'";
$result = mysql_query($query);
if(mysql_num_rows($result) < 1) //no such user exists
{
echo 'false';
header('Location: index.php');
}
$userData = mysql_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );
if($hash != $userData['password']) //incorrect password
{
echo 'false';
header('Location: index.php');
}
else
{
echo 'true';
$_SESSION['username']=$row['username'];
}
session_write_close();
Heres how i hash my pass
// hash the password using sha256 a string of 64 characters
$hash = hash('sha256', $password);
// create the salt, random string of characters appened to hash
function createSalt()
{
$string = md5(uniqid(rand(), true));
return substr($string, 0, 3);
}
$salt = createSalt();
$hash = hash('sha256', $salt . $hash);
Heres how i insert my data
mysql_query("INSERT INTO registered_users(username, name, email, password,salt)VALUES('$username', '$name', '$email', '$hash', '$salt')");
header("location: index.php?remarks-success");
mysql_close($con);
?>
Make sure you are storing the password in the database the same way you are checking it here.
So to put it in you should create the hash by first hashing the password, then rehashing it with a salt. If they don't match, then there is your problem.

Categories

Resources