84 lines
2.5 KiB
PHP
84 lines
2.5 KiB
PHP
<?php
|
|
session_start();
|
|
require_once 'includes/globals.php';
|
|
require_once 'vendor/autoload.php';
|
|
|
|
use DJMixHosting\Database;
|
|
|
|
// Ensure the user is authenticated.
|
|
if (!isset($_SESSION['user'])) {
|
|
header("Location: login.php");
|
|
exit;
|
|
}
|
|
|
|
// Check for required POST fields.
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty($_POST['current_password']) || empty($_POST['new_password']) || empty($_POST['confirm_password'])) {
|
|
$_SESSION['error'] = "All password fields are required.";
|
|
header("Location: profile.php");
|
|
exit;
|
|
}
|
|
|
|
$current_password = $_POST['current_password'];
|
|
$new_password = $_POST['new_password'];
|
|
$confirm_password = $_POST['confirm_password'];
|
|
|
|
// Validate that the new password meets the requirements:
|
|
// - 8 to 32 characters
|
|
// - at least one uppercase letter
|
|
// - at least one lowercase letter
|
|
// - at least one number
|
|
// - at least one symbol
|
|
$pattern = '/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,32}$/';
|
|
if (!preg_match($pattern, $new_password)) {
|
|
$_SESSION['error'] = "New password must be 8-32 characters and include at least one uppercase letter, one lowercase letter, one number, and one symbol.";
|
|
header("Location: profile.php");
|
|
exit;
|
|
}
|
|
|
|
// Verify that new password and confirmation match.
|
|
if ($new_password !== $confirm_password) {
|
|
$_SESSION['error'] = "New password and confirmation do not match.";
|
|
header("Location: profile.php");
|
|
exit;
|
|
}
|
|
|
|
$db = new Database($config);
|
|
$userId = $_SESSION['user']['id'];
|
|
|
|
// Retrieve the current password hash from the database.
|
|
$stmt = $db->prepare("SELECT password FROM users WHERE id = ?");
|
|
$stmt->bind_param("i", $userId);
|
|
$stmt->execute();
|
|
$result = $stmt->get_result();
|
|
$userData = $result->fetch_assoc();
|
|
$stmt->close();
|
|
|
|
if (!$userData) {
|
|
$_SESSION['error'] = "User not found.";
|
|
header("Location: profile.php");
|
|
exit;
|
|
}
|
|
|
|
// Verify that the current password is correct.
|
|
if (!password_verify($current_password, $userData['password'])) {
|
|
$_SESSION['error'] = "Current password is incorrect.";
|
|
header("Location: profile.php");
|
|
exit;
|
|
}
|
|
|
|
// Hash the new password.
|
|
$hashed_new_password = password_hash($new_password, PASSWORD_DEFAULT);
|
|
|
|
// Update the user's password in the database.
|
|
$stmt = $db->prepare("UPDATE users SET password = ? WHERE id = ?");
|
|
$stmt->bind_param("si", $hashed_new_password, $userId);
|
|
if (!$stmt->execute()) {
|
|
$_SESSION['error'] = "Failed to update password. Please try again.";
|
|
header("Location: profile.php");
|
|
exit;
|
|
}
|
|
$stmt->close();
|
|
|
|
$_SESSION['success'] = "Password updated successfully.";
|
|
header("Location: profile.php");
|
|
exit;
|