Session-based authentication module in PHP:
users = [
[
'id' => 1,
'username' => 'john',
'password' => '$2y$10$0GKz5tsm1Wjdd5.HdH5OJ.3Pbc4kSPzwoXJbh4vK7WR1nXrMZn.R6', // Password: secret
'name' => 'John Doe',
],
[
'id' => 2,
'username' => 'jane',
'password' => '$2y$10$d9RfS1cIoo1t3DcTCNFiYO1Qa8h9m1qP4ktL7/F4P77arT60av/di', // Password: password
'name' => 'Jane Smith',
],
];
}
public function login($username, $password)
{
// Find the user with the provided username
$user = $this->getUserByUsername($username);
if (!$user) {
return false;
}
// Verify the password
if (!password_verify($password, $user['password'])) {
return false;
}
// Start a new session
session_start();
// Store user information in the session
$_SESSION['user'] = $user;
return true;
}
public function logout()
{
// Start the session if it's not already started
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
// Destroy the session data
session_destroy();
}
public function isAuthenticated()
{
// Start the session if it's not already started
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
// Check if the 'user' key exists in the session
return isset($_SESSION['user']);
}
public function getCurrentUser()
{
// Start the session if it's not already started
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
// Return the user data if authenticated, otherwise return null
return $this->isAuthenticated() ? $_SESSION['user'] : null;
}
private function getUserByUsername($username)
{
foreach ($this->users as $user) {
if ($user['username'] === $username) {
return $user;
}
}
return null;
}
}
Here’s how you can use the AuthModule
class in your PHP application:
login($username, $password)) {
// Login successful
header('Location: /dashboard.php');
exit;
} else {
// Login failed
header('Location: /login.php?error=1');
exit;
}
// Example logout usage
$auth->logout();
// Example authentication check
if ($auth->isAuthenticated()) {
// User is authenticated
$currentUser = $auth->getCurrentUser();
echo 'Welcome, ' . $currentUser['name'];
} else {
// User is not authenticated
echo 'Please log in.';
}
This module uses PHP’s session
mechanism to store the user’s authentication status. It provides methods for login, logout, checking authentication status, and getting the current authenticated user. The module includes a basic example of user data stored in an array, but you can replace it with your own user data source (e.g., database).
Please note that this is a basic example, and in a real-world application, you would typically handle password hashing, implement more secure session handling, and customize the logic based on your specific requirements.