Auth
The Auth
module handles user registration, login, session management, and role-based access control (RBAC). It provides a secure foundation for managing user accounts.
Constructor
Creates a new Auth module instance with database access, event system, CSRF protection, and configurable security options.
Parameters
$db | Database | Yes | Database connection instance |
$events | Events | Yes | Event system for authentication events |
$csrf | CSRF | Yes | CSRF protection service |
$config | array | No | Configuration options for security settings |
Example
<?php
$config = [
'db' => [
'dsn' => 'mysql:host=localhost;dbname=schoolkit;charset=utf8mb4',
'user' => 'your_username',
'pass' => 'your_password'
],
'storage_path' => __DIR__ . '/storage'
];
$schoolKit = SchoolKit::start($config);
$auth = $schoolKit->auth();
// Auth module is now ready for user management
echo "Auth module initialized successfully";
?>
Quick Reference
Authenticates user and returns true/false for success
Initiates password reset and returns token
Completes password reset with token
User Management
Creates a new user account.
Parameters
Name | Type | Required | Description |
---|---|---|---|
$data |
array |
Yes | Associative array with user data: email , password , first_name , last_name , and optional role . |
Returns
The ID of the newly created user.
Example
<?php
try {
$userId = $schoolKit->auth()->register([
'email' => 'new.teacher@school.edu',
'password' => 'a-very-strong-password',
'first_name' => 'Jane',
'last_name' => 'Smith',
'role' => 'staff'
]);
echo "User registered with ID: " . $userId;
} catch (Exception $e) {
echo "Registration failed: " . $e->getMessage();
}
?>
Attempts to log a user in with their email and password.
Parameters
Name | Type | Required | Description |
---|---|---|---|
$email | string | Yes | The user's email address. |
$password | string | Yes | The user's password. |
$remember | bool | No | If true, sets a "remember me" cookie for persistent login. |
Returns
true
on successful login, false
on failure.
Example
<?php
if ($schoolKit->auth()->login('teacher@school.edu', 'password123', true)) {
header('Location: /dashboard');
exit;
} else {
echo "Invalid login credentials.";
}
?>
Logs the current user out, destroying their session and removing their "remember me" cookie.
Example
<?php
$schoolKit->auth()->logout();
header('Location: /login');
exit;
?>
Checks if there is a currently authenticated user.
Returns
true
if a user is logged in, false
otherwise.
Example
<?php
if ($schoolKit->auth()->check()) {
echo "Welcome, you are logged in.";
} else {
echo "Please log in to continue.";
}
?>
Gets the database record for the currently authenticated user.
Returns
An associative array of the user's data, or null
if not authenticated.
Example
<?php
if ($user = $schoolKit->auth()->user()) {
echo "Hello, " . htmlspecialchars($user['first_name']);
}
?>
Role-Based Access Control
Checks if the current user has a specific role.
Parameters
Name | Type | Required | Description |
---|---|---|---|
$role | string | Yes | The role to check (e.g., 'admin', 'staff'). |
Returns
true
if the user has the role, false
otherwise.
Example
<?php
if ($schoolKit->auth()->hasRole('admin')) {
echo 'Admin Settings';
}
?>
Enforces role-based access. Throws a RuntimeException
if the user does not have the required role.
Parameters
Name | Type | Required | Description |
---|---|---|---|
$role | string | Yes | The required role. |
Example
<?php
// At the top of a page that requires admin access
try {
$schoolKit->auth()->requireRole('admin');
} catch (RuntimeException $e) {
header('HTTP/1.1 403 Forbidden');
die('Access Denied');
}
?>
Changes the role of a user.
Parameters
Name | Type | Required | Description |
---|---|---|---|
$userId | int | Yes | The ID of the user to modify. |
$role | string | Yes | The new role to assign. |
Returns
true
on success, false
otherwise.
Example
<?php
// Promote a staff member to an admin
$schoolKit->auth()->setRole(789, 'admin');
?>
Deactivates a user account, preventing them from logging in.
Parameters
Name | Type | Required | Description |
---|---|---|---|
$userId | int | Yes | The ID of the user to deactivate. |
Returns
true
on success, false
otherwise.
Example
<?php
// An admin deactivates a user who has left the school
$schoolKit->auth()->deactivateUser(456);
?>
Password Reset
Initiates the password reset process for a user and returns a unique reset token.
Parameters
Name | Type | Required | Description |
---|---|---|---|
$email | string | Yes | The email address of the user requesting a reset. |
Returns
The password reset token string, or null
if user not found (for security).
Example
<?php
$token = $schoolKit->auth()->beginPasswordReset('user@school.edu');
if ($token) {
// Send an email to the user with a link containing this token
$resetUrl = "https://school.edu/reset-password?token=" . $token;
$schoolKit->mail()->send([
'to' => 'user@school.edu',
'subject' => 'Password Reset Request',
'html' => 'Click to reset your password'
]);
}
// Always show a generic success message to the user.
?>
Completes the password reset process using a valid token.
Parameters
Name | Type | Required | Description |
---|---|---|---|
$token | string | Yes | The token from the password reset link. |
$newPassword | string | Yes | The user's new password. |
Returns
true
on success, false
if the token is invalid or expired.
Example
<?php
$token = $_GET['token'];
$newPassword = $_POST['password'];
if ($schoolKit->auth()->completePasswordReset($token, $newPassword)) {
echo "Password has been reset successfully.";
} else {
echo "Invalid or expired reset link.";
}
?>
Email Verification
Generates an email verification link for a user account.
Parameters
Name | Type | Required | Description |
---|---|---|---|
$userId | int | Yes | The ID of the user who needs email verification. |
Returns
The email verification token string.
Example
<?php
$userId = $schoolKit->auth()->register([
'email' => 'student@school.edu',
'password' => 'secure-password',
'first_name' => 'Alex',
'last_name' => 'Johnson'
]);
$verificationToken = $schoolKit->auth()->emailVerificationLink($userId);
$verificationUrl = "https://school.edu/verify-email?token=" . $verificationToken;
// Send verification email with the URL
$schoolKit->mail()->send([
'to' => 'student@school.edu',
'subject' => 'Please verify your email',
'html' => 'Click to verify'
]);
?>
Verifies a user's email address using a verification token.
Parameters
Name | Type | Required | Description |
---|---|---|---|
$token | string | Yes | The email verification token from the verification link. |
Returns
true
on successful verification, false
if the token is invalid or expired.
Example
<?php
$token = $_GET['token'] ?? '';
if ($schoolKit->auth()->verifyEmail($token)) {
echo "Email verified successfully! You can now log in.";
header('Location: /login?verified=1');
exit;
} else {
echo "Invalid or expired verification token.";
}
?>
Admin Impersonation
Allows an admin user to impersonate another user for support or debugging purposes.
Parameters
Name | Type | Required | Description |
---|---|---|---|
$adminId | int | Yes | The ID of the admin user performing the impersonation. |
$targetUserId | int | Yes | The ID of the user to impersonate. |
Returns
true
on successful impersonation, false
if unauthorized or user not found.
Example
<?php
// Admin wants to impersonate a user to debug their issue
if ($schoolKit->auth()->hasRole('admin')) {
$adminId = $schoolKit->auth()->user()['id'];
$targetUserId = 789; // ID of user experiencing issues
if ($schoolKit->auth()->impersonate($adminId, $targetUserId)) {
echo "Now impersonating user. Session switched.";
header('Location: /dashboard');
exit;
} else {
echo "Impersonation failed.";
}
}
?>
Stops an active impersonation session and returns to the original admin user.
Returns
true
on successful return to original session, false
if not currently impersonating.
Example
<?php
// Admin is done debugging and wants to return to their own session
if ($schoolKit->auth()->stopImpersonating()) {
echo "Returned to your admin session.";
header('Location: /admin/dashboard');
exit;
} else {
echo "Not currently impersonating anyone.";
}
?>
Checks if the current session is impersonating another user.
Returns
true
if currently impersonating, false
otherwise.
Example
<?php
// Display an impersonation banner in the UI
if ($schoolKit->auth()->isImpersonating()) {
echo '';
echo 'You are impersonating another user. ';
echo 'Return to your account';
echo '';
}
?>
All Available Methods
Constructor
- __construct($db, $events, $csrf, array $config = []) - Initialize Auth module
User Management (5 methods)
- register() - Creates a new user account
- login() - Authenticates user with email and password
- logout() - Logs out the current user
- check() - Checks if user is authenticated
- user() - Returns current user data
Role-Based Access Control (4 methods)
- hasRole() - Checks if user has specific role
- requireRole() - Enforces role-based access
- setRole() - Changes user role
- deactivateUser() - Deactivates a user account
Password Reset (2 methods)
- beginPasswordReset() - Initiates password reset process
- completePasswordReset() - Completes password reset with token
Email Verification (2 methods)
- emailVerificationLink() - Generates email verification token
- verifyEmail() - Verifies email with token
Admin Impersonation (3 methods)
- impersonate() - Admin impersonates another user
- stopImpersonating() - Stops active impersonation
- isImpersonating() - Checks if currently impersonating
Total: 17 methods documented (including constructor)