Skip to content

Commit

Permalink
test 3
Browse files Browse the repository at this point in the history
  • Loading branch information
KotsiosDimis committed Dec 27, 2024
1 parent 12ffb5a commit 1b8f1a2
Show file tree
Hide file tree
Showing 7 changed files with 132 additions and 196 deletions.
6 changes: 5 additions & 1 deletion archive/api/shema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,16 @@ CREATE TABLE `games` (
`game_id` INT AUTO_INCREMENT PRIMARY KEY,
`player1_id` INT NOT NULL,
`player2_id` INT,
'player3_id' INT,
'player4_id' INT,
`game_status` ENUM('waiting', 'in_progress', 'finished') DEFAULT 'waiting',
`game_type` VARCHAR(50),
`max_players` INT DEFAULT 2,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (`player1_id`) REFERENCES `users`(`id`),
FOREIGN KEY (`player2_id`) REFERENCES `users`(`id`)
FOREIGN KEY (`player2_id`) REFERENCES `users`(`id`),
FOREIGN KEY (`player3_id`) REFERENCES `users`(`id`),
FOREIGN KEY (`player4_id`) REFERENCES `users`(`id`)
);

-- Table to store game lobbies
Expand Down
55 changes: 47 additions & 8 deletions lib/users.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@

header('Content-Type: application/json');

function registerUser($username, $password, $email) {
// **Registration Function (Register a new user)**
function registerUser($username, $email, $password) {
try {
$pdo = getDatabaseConnection();
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
Expand All @@ -24,19 +25,24 @@ function registerUser($username, $password, $email) {
}
}


// **Login Function (Authenticate User)**
function loginUser($username, $password) {
session_start();

try {
$pdo = getDatabaseConnection();
$sql = "SELECT user_id , username, password_hash FROM users WHERE username = :username";

// Fetch the user details from the database using the provided username
$sql = "SELECT user_id , username, password FROM users WHERE username = :username";
$stmt = $pdo->prepare($sql);
$stmt->execute([':username' => $username]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if ($user) {
// Compare the entered password with the stored password
if ($password === $user['password_hash']) {
// Verify the entered password with the stored hashed password
if (password_verify($password, $user['password'])) {
// If login is successful, store the user details in session
$_SESSION['user_id'] = $user['user_id'];
$_SESSION['username'] = $user['username'];
echo json_encode(['success' => true, 'message' => 'Login successful']);
Expand All @@ -51,7 +57,39 @@ function loginUser($username, $password) {
}
}

// **Login Provider (Helper Function to Get User from DB)**
function loginUserFromDB($username, $password) {
try {
$pdo = getDatabaseConnection();

// SQL query to fetch the user data by username
$sql = "SELECT user_id, username, password FROM users WHERE username = :username";
$stmt = $pdo->prepare($sql);
$stmt->execute([':username' => $username]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if ($user) {
// Use password_verify to compare the entered password with the stored hash
if (password_verify($password, $user['password'])) {
// Return user data if login is successful
return [
'success' => true,
'user_id' => $user['user_id'],
'username' => $user['username']
];
} else {
return ['success' => false, 'message' => 'Invalid username or password'];
}
} else {
return ['success' => false, 'message' => 'User not found'];
}
} catch (PDOException $e) {
// Log the error and return a failure response
return ['success' => false, 'message' => 'Error: ' . $e->getMessage()];
}
}

// **Logout Function (Destroy User Session)**
function logoutUser() {
session_start();
session_unset();
Expand All @@ -60,6 +98,7 @@ function logoutUser() {
echo json_encode(['success' => true, 'message' => 'User logged out successfully']);
}

// **Check Session Function (Check if User is Logged In)**
function checkSession() {
session_start();

Expand All @@ -70,7 +109,7 @@ function checkSession() {
}
}


// **Reset Password Function (Send Password Reset Email)**
function resetPassword($email) {
try {
$pdo = getDatabaseConnection();
Expand All @@ -80,7 +119,7 @@ function resetPassword($email) {
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if ($user) {
$resetToken = bin2hex(random_bytes(16));
$resetToken = bin2hex(random_bytes(16)); // Generate a reset token
$sql = "UPDATE users SET reset_token = :token, reset_expiry = :expiry WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->execute([
Expand All @@ -101,6 +140,7 @@ function resetPassword($email) {
}
}

// **Update Password Function (Update User's Password)**
function updatePassword($userId, $newPassword) {
try {
$pdo = getDatabaseConnection();
Expand All @@ -119,5 +159,4 @@ function updatePassword($userId, $newPassword) {
}
}


?>
?>
20 changes: 0 additions & 20 deletions public/gametect.html

This file was deleted.

70 changes: 32 additions & 38 deletions public/index.html
Original file line number Diff line number Diff line change
@@ -1,62 +1,59 @@
<!DOCTYPE html>
<html lang="en">



<head>
<meta charset="UTF-8" />
<meta name="viewport"
content="width=device-width,
initial-scale=1,
shrink-to-fit=no" />
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" />
<link rel="icon" href="assets/icon.ico" type="image/ico"> <!-- Favicon icon -->
<title>Blokus</title>

<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- External JS File -->
<script src="js/checkSession.js"></script>
<script src="js/login.js"></script>

</head>

<body>
<h1 class="text-success text-center">
Welcome to Blokus !!!
</h1>
<h1 class="text-success text-center">Welcome to Blokus !!!</h1>
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-body">
<form id="registrationForm">
<form id="loginForm">
<h4 class="text-center">Login</h4>
<div class="form-group">
<label for="username">
Username
</label>
<input type="text"
class="form-control"
id="username"
placeholder="Username" required />
<label for="username">Username</label>
<input type="text" class="form-control" id="username" placeholder="Username" required />
</div>
<div class="form-group">
<label for="password">
Password
</label>
<input type="password"
class="form-control"
id="password"
placeholder="Password" required />
<label for="password">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password" required />
</div>
<button type="submit" class="btn btn-danger">
Login
</button>
<button type="submit" class="btn btn-danger">Login</button>
</form>

<p class="mt-3">Not registered? <a href="#" id="showRegister">Create an account</a></p>
<hr />
<form id="registerForm" style="display: none;">
<h4 class="text-center">Register</h4>
<div class="form-group">
<label for="reg_username">Username</label>
<input type="text" class="form-control" id="reg_username" placeholder="Username" required />
</div>
<div class="form-group">
<label for="reg_email">Email</label>
<input type="email" class="form-control" id="reg_email" placeholder="Email" required />
</div>
<div class="form-group">
<label for="reg_password">Password</label>
<input type="password" class="form-control" id="reg_password" placeholder="Password" required />
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
<p class="mt-3">
Not registered? <a href="#">Create an account</a>
</p>
</div>
</div>
</div>
Expand All @@ -65,9 +62,6 @@ <h1 class="text-success text-center">

<!-- Debug Info -->
<div id="debugInfo" class="mt-3"></div>



</body>

</html>
57 changes: 48 additions & 9 deletions public/js/login.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,21 @@
$(document).ready(function () {
// Handle form submission
$('#registrationForm').on('submit', function (e) {
// Handle login form submission
$('#loginForm').on('submit', function (e) {
e.preventDefault(); // Prevent default form submission

// Get the values of username and password
const username = $('#username').val();
const password = $('#password').val();

// Display input values for debugging
$('#debugInfo').append(`<p>Attempting to log in with: Username - <b>${username}</b></p>`);

// Send POST request to the server
$.ajax({
url: 'https://users.iee.ihu.gr/~iee2020202/ADISE24_DreamTeam/blokus.php/users/login',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ username: username, password: password }),
success: function (response) {
// Display the response for debugging
$('#debugInfo').append(`<p>Response received from server: <pre>${JSON.stringify(response)}</pre></p>`);

// Handle the server response
if (response.success) {
$('#debugInfo').append(`<p class="text-success">Login successful. Redirecting to dashboard.html...</p>`);
window.location.href = 'dashboard.html';
Expand All @@ -29,7 +24,6 @@ $(document).ready(function () {
}
},
error: function (xhr, status, error) {
// Display error details for debugging
$('#debugInfo').append(`
<p class="text-danger">Error during AJAX request:</p>
<p>Status: ${xhr.status}</p>
Expand All @@ -40,5 +34,50 @@ $(document).ready(function () {
}
});
});
});

// Handle register form submission
$('#registerForm').on('submit', function (e) {
e.preventDefault(); // Prevent default form submission

const username = $('#reg_username').val();
const email = $('#reg_email').val();
const password = $('#reg_password').val();

$('#debugInfo').append(`<p>Attempting to register with: Username - <b>${username}</b>, Email - <b>${email}</b></p>`);

$.ajax({
url: 'https://users.iee.ihu.gr/~iee2020202/ADISE24_DreamTeam/blokus.php/users/register',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ username: username, email: email, password: password }),
success: function (response) {
$('#debugInfo').append(`<p>Response received from server: <pre>${JSON.stringify(response)}</pre></p>`);

if (response.success) {
$('#debugInfo').append(`<p class="text-success">Registration successful. You can now log in.</p>`);
$('#registerForm')[0].reset(); // Clear the registration form
$('#registerForm').hide();
$('#loginForm').show();
} else {
$('#debugInfo').append(`<p class="text-danger">Registration failed: ${response.message}</p>`);
}
},
error: function (xhr, status, error) {
$('#debugInfo').append(`
<p class="text-danger">Error during AJAX request:</p>
<p>Status: ${xhr.status}</p>
<p>Status Text: ${xhr.statusText}</p>
<p>Response Text: <pre>${xhr.responseText}</pre></p>
`);
alert('An error occurred. Please try again later.');
}
});
});

// Show register form when "Create an account" link is clicked
$('#showRegister').on('click', function (e) {
e.preventDefault();
$('#loginForm').hide();
$('#registerForm').show();
});
});
34 changes: 0 additions & 34 deletions public/welcome.html

This file was deleted.

Loading

0 comments on commit 1b8f1a2

Please sign in to comment.