Skip to content

Commit

Permalink
reformated php code!
Browse files Browse the repository at this point in the history
  • Loading branch information
neeraj-395 committed Mar 20, 2024
1 parent b76ee69 commit f543676
Show file tree
Hide file tree
Showing 8 changed files with 276 additions and 231 deletions.
7 changes: 4 additions & 3 deletions assets/js/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
var baseURL = getBaseURL('/nsp-dbms-project'); // Define root folder name with forward slash (/) !importatant

$(function () {
$('<div id="cover-spin"></div>').appendTo('body'); // spinner
$("input[type='password'][data-eye]").each(function (i) {
var $this = $(this),
id = 'eye-password-' + i,
Expand Down Expand Up @@ -64,7 +65,6 @@ $(function () {
}));
}
});
$('<div id="cover-spin"></div>').appendTo('body'); // spinner
});
});

Expand Down Expand Up @@ -140,7 +140,7 @@ function authenticate(form, filepath) {
})
.then(result => {
switch(result.status){
case 200: if(result.message.length) alert(result.message);
case 200: if(result.message) alert(result.message);
if(result.redirect) window.location.href = baseURL + result.redirect;
break;
case 500: alert(result.message); // Bad response
Expand All @@ -156,7 +156,8 @@ function authenticate(form, filepath) {
`An error has occurred, most likely due to an attempt to execute`,
`server-side scripts on a GitHub page, which is not permitted.`,
`Please run this project on a PHP-supported server for seamless functionality.`,
`\nThank you for your understanding and cooperation.`
`\nThank you for your understanding and cooperation.`,
`\nError: ${error}`
];
alert(err_msg.join(" "));
window.location.reload();
Expand Down
43 changes: 36 additions & 7 deletions assets/js/user.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
const initApp = () => {
const droparea = document.querySelector('.droparea');
document.addEventListener("DOMContentLoaded", initApp);

const active = () => droparea.classList.add("green-border");
document.addEventListener("DOMContentLoaded", ()=>{
});

const inactive = () => droparea.classList.remove("green-border");

function initApp () {
const droparea = document.querySelector('.droparea');
if(!droparea) return;
const active = () => droparea.classList.add("green-border");
const inactive = () => droparea.classList.remove("green-border");
const prevents = (e) => e.preventDefault();

['dragenter', 'dragover', 'dragleave', 'drop'].forEach(evtName => {
Expand All @@ -23,12 +27,37 @@ const initApp = () => {

}

document.addEventListener("DOMContentLoaded", initApp);

const handleDrop = (e) => {
const dt = e.dataTransfer;
const files = dt.files;
const fileArray = [...files];
console.log(files); // FileList
console.log(fileArray);
}
}

/*
const editBtn = document.querySelector('.edit-btn');
editBtn.addEventListener("click",()=>{
const userInputBlocks = document.querySelectorAll('.person .row > :nth-child(2)');
userInputBlocks.forEach(inputBlock => {
const name = inputBlock.getAttribute('name');
const Data = inputBlock.textContent.trim();
const input = `<input id="${name}" type="text" class="form-control" value="${Data}" required>`;
inputBlock.innerHTML = input;
});
const newBtn = `<button id="changes" class="btn btn-primary px-4">Save Changes</button>`
editBtn.parentElement.innerHTML= newBtn;
document.getElementById('changes').addEventListener('click',()=>{
const userInputBlocks = document.querySelectorAll('.person .row > :nth-child(2)');
const inputData = {};
userInputBlocks.forEach(inputBlock=>{
let name = inputBlock.firstChild.getAttribute('name');
let value = inputBlock.firstChild.getAttribute('value');
inputData[name] = value;
});
console.log(inputData);
});
});
*/
98 changes: 44 additions & 54 deletions backend/login.inc.php
Original file line number Diff line number Diff line change
@@ -1,62 +1,52 @@
<?php
require_once "../database/connect.php";
set_error_handler('HANDLE_EXCEPTIONS'); // for any unexpected error
require_once "../database/connect.php";

/* ERROR MESSAGES AND CONSTANTS */
define('HOME_PAGE', '/index.html');
define('LOGIN_ERROR','Invalid username or password.');

try{
if($_SERVER["REQUEST_METHOD"] !== "POST") EXIT_WITH_JSON(BAD_RESPONSE, INVALID_METHOD, null, $conn);

if($_SERVER["REQUEST_METHOD"] === "POST")
{
$username = (isset($_POST['username'])) ? trim($_POST['username']) : null;
$password = (isset($_POST['password'])) ? trim($_POST['password']) : null;

// Checking Validity. Although it already checked by the javascript logic
if(!isValid($username, $password)) {
$err_msg = "Did you bypass the pattern rules of this login page?";
EXIT_WITH_JSON(500, $err_msg, null, $conn);
}
if(!isValid($username, $password)) EXIT_WITH_JSON(BAD_RESPONSE, VALIDATION_FAILURE, null, $conn);

// Prepare a select statement
$sql = "SELECT user_id, username, name, password FROM user_data WHERE username = ?";

if($stmt = $conn->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("s", $username);

// Attempt to execute the prepared statement
if($stmt->execute()){
// Store result
$stmt->store_result();

// Check if username exists, if yes then verify password
if($stmt->num_rows == 1){
// Bind result variables
$stmt->bind_result($id, $username, $name, $hashed_password);

if($stmt->fetch()){
if(password_verify($password, $hashed_password)){
session_start();
// Store data in session variables
$_SESSION["user_id"] = $id;
$_SESSION["username"] = $username;
$_SESSION["name"] = $name;
$_SESSION["isLoggedIn"] = true;

EXIT_WITH_JSON(200, "", "/index.html", $conn, $stmt);
} else {
// Password is not valid, display a generic error message
$login_err = "Invalid username or password.";
EXIT_WITH_JSON(500, $login_err, null, $conn, $stmt);
}
}
} else{
// Username doesn't exist, display a generic error message
$login_err = "Invalid username or password.";
EXIT_WITH_JSON(500, $login_err, null, $conn, $stmt);
}
} else{
$err_msg = "Oops! something went wrong. Please try again later.\n";
EXIT_WITH_JSON(500, $err_msg, null, $conn, $stmt);
}
} else {
$err_msg = "Oops! something went wrong. Please try again later.\n";
EXIT_WITH_JSON(500, $err_msg, null, $conn);
$sql = "SELECT * FROM user_data WHERE username = ?";
$stmt = $conn->prepare($sql);

if(!$stmt) EXIT_WITH_JSON(BAD_RESPONSE, EXECUTION_FAILURE, null, $conn);

// Bind variables to the prepared statement as parameters
$stmt->bind_param("s", $username);

// Attempt to execute the prepared statement
if(!$stmt->execute()) EXIT_WITH_JSON(BAD_RESPONSE, EXECUTION_FAILURE, null, $conn, $stmt);

$user = $stmt->get_result();

if($user->num_rows != 1) EXIT_WITH_JSON(BAD_RESPONSE, LOGIN_ERROR, null, $conn, $stmt);

$user_data = $user->fetch_assoc();

if(!password_verify($password, $user_data['password']))
EXIT_WITH_JSON(BAD_RESPONSE, LOGIN_ERROR, null, $conn, $stmt);

session_start();

foreach ($user_data as $key => $value) {
if($key !== "password") $_SESSION[$key] = $value;
}
} else exit(500);

$_SESSION["isLoggedIn"] = true;

EXIT_WITH_JSON(GOOD_RESPONSE, null, HOME_PAGE, $conn, $stmt);

} catch (Exception $error) {
$err_msg = "An unexpected error has occurred.\n"
. "Please disregard the following error and try again later:\n"
. $error->getMessage();
EXIT_WITH_JSON(BAD_RESPONSE, $err_msg);
}
114 changes: 50 additions & 64 deletions backend/signup.inc.php
Original file line number Diff line number Diff line change
@@ -1,78 +1,64 @@
<?php
require_once "../database/connect.php";
set_error_handler('HANDLE_EXCEPTIONS'); // for any unexpected error
/* ERROR MESSAGES */
define('USERNAME_EXIST','This username is already taken.');

/* GOOD RESPONSE MESSAGES AND CONSTANTS */
define('SIGNUP_SUCCESS', "Congratulations! Your signup was successful.\nThank you for joining us!");
define('LOGIN_PAGE','/pages/auth/login.html');


try {
if($_SERVER["REQUEST_METHOD"] !== "POST") EXIT_WITH_JSON(BAD_RESPONSE, INVALID_METHOD, null, $conn);

if($_SERVER["REQUEST_METHOD"] === "POST")
{
$name = (isset($_POST['name'])) ? trim($_POST['name']) : null;
$username = (isset($_POST['username'])) ? trim($_POST['username']) : null;
$email = (isset($_POST['email'])) ? trim($_POST['email']) : null;
$username = (isset($_POST['username'])) ? trim($_POST['username']) : null;
$password = (isset($_POST['password'])) ? trim($_POST['password']) : null;

// Checking Validity. Although it already checked by the javascript logic
if(!isValid($username, $password, $name, $email)) {
$err_msg = "Did you bypass the pattern rules of this signup page?";
EXIT_WITH_JSON(500, $err_msg, null, $conn);
EXIT_WITH_JSON(BAD_RESPONSE, $err_msg, null, $conn);
}

// Prepare a select statement for username availablity check.
$sql = "SELECT user_id FROM user_data WHERE username = ?";

// Preparing mysql connection and sql statement.
if($stmt = $conn->prepare($sql)) {
// Binding username parameter with sql statement.
$stmt->bind_param("s", $username);

// Trying to execute the statement
if($stmt->execute()){
// Storing the result.
$stmt->store_result();

// If username exist end the script.
if($stmt->num_rows() === 1) {
$err_msg = "This username is already taken.";
EXIT_WITH_JSON(500, $err_msg, null, $conn, $stmt);
} else {
$stmt->close();// Close statement.
}
} else {
$err_msg = "Oops! something went wrong. Please try again later.";
EXIT_WITH_JSON(500, $err_msg, null, $conn, $stmt);
}

} else {
$err_msg = "Oops! something went wrong. Please try again later.";
EXIT_WITH_JSON(500, $err_msg, null, $conn);
}

$stmt = $conn->prepare($sql);

if(!$stmt) EXIT_WITH_JSON(BAD_RESPONSE, EXECUTION_FAILURE, null, $conn);

$stmt->bind_param("s", $username);

if(!$stmt->execute()) EXIT_WITH_JSON(BAD_RESPONSE, EXECUTION_FAILURE, null, $conn, $stmt);

$stmt->store_result();

if($stmt->num_rows() === 1) EXIT_WITH_JSON(500, USERNAME_EXIST, null, $conn, $stmt);
else $stmt->close(); // closing current statement.

// Prepare an insert statement.
$sql = "INSERT INTO user_data (
username,
name,
password,
email_id
) VALUES (?,?,?,?)";

if($stmt = $conn->prepare($sql)){
// Bind variables to the prepared statement as parameter.
$stmt->bind_param("ssss", $username, $name, $hash_password, $email);

// Hashing password.
$hash_password = password_hash($password, PASSWORD_BCRYPT);

// Attempt to execute the prepared statement.
if($stmt->execute()){
$msg = "Congratulations! Your signup was successful.\nThank you for joining us!";
$redirect_to = "/pages/auth/login.html";
EXIT_WITH_JSON(200, $msg, $redirect_to, $conn, $stmt);
} else {
$err_msg = "Oops! something went wrong. Please try again later.";
EXIT_WITH_JSON(500, $err_msg, null, $conn, $stmt);
}

} else {
$err_msg = "Oops! something went wrong. Please try again later.";
EXIT_WITH_JSON(500, $err_msg, null, $conn);
}
} else exit(500);
username,
name,
password,
email_id
) VALUES (?,?,?,?)";
// Preparing mysql connection and sql statement.
$stmt = $conn->prepare($sql);

if(!$stmt) EXIT_WITH_JSON(BAD_RESPONSE, EXECUTION_FAILURE, null, $conn);

// Bind variables to the prepared statement as parameter.
$stmt->bind_param("ssss", $username, $name, $hash_password, $email);

// ENCRYPT PASSWORD
$hash_password = password_hash($password, PASSWORD_BCRYPT);

if(!$stmt->execute()) EXIT_WITH_JSON(BAD_RESPONSE, EXECUTION_FAILURE, null, $conn, $stmt);

EXIT_WITH_JSON(GOOD_RESPONSE, SIGNUP_SUCCESS, LOGIN_PAGE, $conn, $stmt);

} catch (Exception $error) {
$message = "An unexpected error has occurred.\n"
. "Please disregard the following error and try again later:\n"
. $error->getMessage();
EXIT_WITH_JSON(BAD_RESPONSE, $message);
}
15 changes: 6 additions & 9 deletions backend/utils.inc.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
<?php
define('INVALID_METHOD', 'Unexpected Request Method');
define('VALIDATION_FAILURE','Invalid details please try after sometime.');
define('EXECUTION_FAILURE', 'Oops! something went wrong. Please try again later.');

function isValid(?string $username = "skip", ?string $password = "skip",
?string $name = "skip", ?string $email = "skip") {
Expand All @@ -22,8 +25,8 @@ function isValid(?string $username = "skip", ?string $password = "skip",
return true;
}

function EXIT_WITH_JSON(int $status_code, string $message, string $redirect = null,
?mysqli $conn = null, ?mysqli_stmt $stmt = null){
function EXIT_WITH_JSON(int $status_code, ?string $message = null, string $redirect = null,
?mysqli $conn = null, ?mysqli_stmt $stmt = null) {
if($stmt !== null) $stmt->close(); // Close statement
if($conn !== null) $conn->close(); // Close connection
$response = array(
Expand All @@ -35,10 +38,4 @@ function EXIT_WITH_JSON(int $status_code, string $message, string $redirect = nu
echo json_encode($response);
exit;
}

function HANDLE_EXCEPTIONS($errno, $errstr, $errfile, $errline){
$message = "An issue has occurred($errno).
Please disregard the following error code and try again later:\n
$errstr\nErrorline = $errline\nFile: $errfile";
EXIT_WITH_JSON(500, $message);
}
?>
Loading

0 comments on commit f543676

Please sign in to comment.