The Auth
class in JiFramework provides a robust authentication system for managing user and administrator logins. It handles essential authentication tasks such as logging in, logging out, session management, and "remember me" functionality. This class integrates seamlessly with the QueryBuilder
for database interactions, making it straightforward to authenticate users and admins in your application.
Method: adminLogin(string $email, string $password, bool $remember = false): bool
Description: Attempts to log in an administrator using their email and password. Optionally sets a "remember me" token for persistent login.
Parameters:
- $email (
string
): The administrator's email address. - $password (
string
): The administrator's password. - $remember (
bool
, optional): Whether to remember the admin across sessions. Defaults tofalse
.
Returns: bool
indicating whether the login was successful.
Usage:
// Initialize the Auth class
$auth = new Auth();
// Get credentials from a login form
$email = $_POST['email'];
$password = $_POST['password'];
$remember = isset($_POST['remember']); // Checkbox for "Remember Me"
if ($auth->adminLogin($email, $password, $remember)) {
// Login successful
header('Location: /admin/dashboard.php');
exit();
} else {
// Login failed
echo 'Invalid admin credentials.';
}
Method: userLogin(string $email, string $password, bool $remember = false): bool
Description: Attempts to log in a user using their email and password. Optionally sets a "remember me" token for persistent login.
Parameters:
- $email (
string
): The user's email address. - $password (
string
): The user's password. - $remember (
bool
, optional): Whether to remember the user across sessions. Defaults tofalse
.
Returns: bool
indicating whether the login was successful.
Usage:
// Initialize the Auth class
$auth = new Auth();
// Get credentials from a login form
$email = $_POST['email'];
$password = $_POST['password'];
$remember = isset($_POST['remember']); // Checkbox for "Remember Me"
if ($auth->userLogin($email, $password, $remember)) {
// Login successful
header('Location: /dashboard.php');
exit();
} else {
// Login failed
echo 'Invalid user credentials.';
}
Method: adminLogout(): void
Description: Logs out the currently authenticated administrator by clearing their session and removing the "remember me" cookie.
Parameters: None
Returns: void
Usage:
// Initialize the Auth class
$auth = new Auth();
// Log out the admin
$auth->adminLogout();
// Redirect to the admin login page
header('Location: /admin/login.php');
exit();
Method: userLogout(): void
Description: Logs out the currently authenticated user by clearing their session and removing the "remember me" cookie.
Parameters: None
Returns: void
Usage:
// Initialize the Auth class
$auth = new Auth();
// Log out the user
$auth->userLogout();
// Redirect to the user login page
header('Location: /login.php');
exit();
Method: isAdminLoggedIn(): bool
Description: Checks whether an administrator is currently logged in.
Parameters: None
Returns: bool
indicating whether an admin is logged in.
Usage:
// Initialize the Auth class
$auth = new Auth();
if ($auth->isAdminLoggedIn()) {
// Admin is logged in
echo 'Welcome, Administrator!';
} else {
// Admin is not logged in
header('Location: /admin/login.php');
exit();
}
Method: isUserLoggedIn(): bool
Description: Checks whether a user is currently logged in.
Parameters: None
Returns: bool
indicating whether a user is logged in.
Usage:
// Initialize the Auth class
$auth = new Auth();
if ($auth->isUserLoggedIn()) {
// User is logged in
echo 'Welcome, User!';
} else {
// User is not logged in
header('Location: /login.php');
exit();
}
Method: getAdminId(): int|null
Description: Retrieves the ID of the currently authenticated administrator.
Parameters: None
Returns: The admin's ID (int
) if logged in, or null
if not logged in.
Usage:
// Initialize the Auth class
$auth = new Auth();
$adminId = $auth->getAdminId();
if ($adminId !== null) {
echo 'Admin ID: ' . $adminId;
} else {
echo 'No admin is currently logged in.';
}
Method: getUserId(): int|null
Description: Retrieves the ID of the currently authenticated user.
Parameters: None
Returns: The user's ID (int
) if logged in, or null
if not logged in.
Usage:
// Initialize the Auth class
$auth = new Auth();
$userId = $auth->getUserId();
if ($userId !== null) {
echo 'User ID: ' . $userId;
} else {
echo 'No user is currently logged in.';
}
Method: getAdmin(): array|null
Description: Retrieves the details of the currently authenticated administrator from the database.
Parameters: None
Returns: An associative array containing the admin's details, or null
if not logged in.
Usage:
// Initialize the Auth class
$auth = new Auth();
$admin = $auth->getAdmin();
if ($admin !== null) {
echo 'Admin Name: ' . htmlspecialchars($admin['name']);
echo 'Admin Email: ' . htmlspecialchars($admin['email']);
} else {
echo 'No admin is currently logged in.';
}
Method: getUser(): array|null
Description: Retrieves the details of the currently authenticated user from the database.
Parameters: None
Returns: An associative array containing the user's details, or null
if not logged in.
Usage:
// Initialize the Auth class
$auth = new Auth();
$user = $auth->getUser();
if ($user !== null) {
echo 'User Name: ' . htmlspecialchars($user['name']);
echo 'User Email: ' . htmlspecialchars($user['email']);
} else {
echo 'No user is currently logged in.';
}
Method: clearExpiredTokens(): void
Description: Removes expired "remember me" tokens from the database to maintain security and performance.
Parameters: None
Returns: void
Usage:
// Initialize the Auth class
$auth = new Auth();
// Clear expired tokens (can be scheduled via a cron job)
$auth->clearExpiredTokens();
Configuration
The Auth
class relies on configuration constants defined in the Config
class. Ensure these constants are properly set:
Session Keys:
class Config {
// Session keys
const ADMIN_SESSION_KEY = 'admin_id';
const USER_SESSION_KEY = 'user_id';
}
Remember Me Cookie Names:
class Config {
// Remember me cookie names
const ADMIN_REMEMBER_COOKIE = 'admin_remember_token';
const USER_REMEMBER_COOKIE = 'user_remember_token';
}
Database Schema
Ensure your database has the required tables:
Tokens Table (tokens
):
CREATE TABLE tokens (
id INT PRIMARY KEY AUTO_INCREMENT,
user_id INT NOT NULL,
token VARCHAR(255) NOT NULL,
expire_datetime DATETIME NOT NULL,
type ENUM('user', 'admin') NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);