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

__construct
__construct($db, $events, $csrf, array $config = [])

Creates a new Auth module instance with database access, event system, CSRF protection, and configurable security options.

Parameters

$dbDatabaseYesDatabase connection instance
$eventsEventsYesEvent system for authentication events
$csrfCSRFYesCSRF protection service
$configarrayNoConfiguration 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

register()
register(array $data): int

Creates new user account with email and password

login()
login(string $email, string $password, bool $remember = false): bool

Authenticates user and returns true/false for success

logout()
logout(): void

Destroys user session and logs out current user

user()
user(): ?array

Returns currently authenticated user data

check()
check(): bool

Checks if user is currently authenticated

hasRole()
hasRole(string $role): bool

Checks if user has specific role

setRole()
setRole(int $userId, string $role): bool

Changes the role of a user

beginPasswordReset()
beginPasswordReset(string $email): ?string

Initiates password reset and returns token

completePasswordReset()
completePasswordReset(string $token, string $newPassword): bool

Completes password reset with token

verifyEmail()
verifyEmail(string $token): bool

Verifies user email with token

User Management

register
register(array $data): int

Creates a new user account.

Parameters

NameTypeRequiredDescription
$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();
}
?>
login
login(string $email, string $password, bool $remember = false): bool

Attempts to log a user in with their email and password.

Parameters

NameTypeRequiredDescription
$emailstringYesThe user's email address.
$passwordstringYesThe user's password.
$rememberboolNoIf 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.";
}
?>
logout
logout(): void

Logs the current user out, destroying their session and removing their "remember me" cookie.

Example

<?php
$schoolKit->auth()->logout();
header('Location: /login');
exit;
?>
check
check(): bool

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.";
}
?>
user
user(): ?array

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

hasRole
hasRole(string $role): bool

Checks if the current user has a specific role.

Parameters

NameTypeRequiredDescription
$rolestringYesThe 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';
}
?>
requireRole
requireRole(string $role): void

Enforces role-based access. Throws a RuntimeException if the user does not have the required role.

Parameters

NameTypeRequiredDescription
$rolestringYesThe 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');
}
?>
setRole
setRole(int $userId, string $role): bool

Changes the role of a user.

Parameters

NameTypeRequiredDescription
$userIdintYesThe ID of the user to modify.
$rolestringYesThe new role to assign.

Returns

true on success, false otherwise.

Example

<?php
// Promote a staff member to an admin
$schoolKit->auth()->setRole(789, 'admin');
?>
deactivateUser
deactivateUser(int $userId): bool

Deactivates a user account, preventing them from logging in.

Parameters

NameTypeRequiredDescription
$userIdintYesThe 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

beginPasswordReset
beginPasswordReset(string $email): ?string

Initiates the password reset process for a user and returns a unique reset token.

Parameters

NameTypeRequiredDescription
$emailstringYesThe 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.
?>
completePasswordReset
completePasswordReset(string $token, string $newPassword): bool

Completes the password reset process using a valid token.

Parameters

NameTypeRequiredDescription
$tokenstringYesThe token from the password reset link.
$newPasswordstringYesThe 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

verifyEmail
verifyEmail(string $token): bool

Verifies a user's email address using a verification token.

Parameters

NameTypeRequiredDescription
$tokenstringYesThe 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

impersonate
impersonate(int $adminId, int $targetUserId): bool

Allows an admin user to impersonate another user for support or debugging purposes.

Parameters

NameTypeRequiredDescription
$adminIdintYesThe ID of the admin user performing the impersonation.
$targetUserIdintYesThe 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.";
    }
}
?>
stopImpersonating
stopImpersonating(): bool

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.";
}
?>
isImpersonating
isImpersonating(): bool

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

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)

Password Reset (2 methods)

Email Verification (2 methods)

Admin Impersonation (3 methods)

Total: 17 methods documented (including constructor)