# Authentication System - Implementatie Voorbeelden ## Code Voorbeelden ### 1. Login Pagina (auth/login.php) ```php load(); $db = new PDO( "mysql:host={$_ENV['DB_HOST']};dbname={$_ENV['DB_NAME']}", $_ENV['DB_USER'], $_ENV['DB_PASS'] ); $error = ''; $redirect = $_GET['redirect'] ?? 'index.php'; if ($_SERVER['REQUEST_METHOD'] === 'POST') { $username = $_POST['username'] ?? ''; $password = $_POST['password'] ?? ''; // Check brute force $stmt = $db->prepare(" SELECT COUNT(*) FROM login_attempts WHERE username = ? AND success = 0 AND attempted_at > DATE_SUB(NOW(), INTERVAL 15 MINUTE) "); $stmt->execute([$username]); $failedAttempts = $stmt->fetchColumn(); if ($failedAttempts >= 5) { $error = 'Te veel mislukte pogingen. Probeer het over 15 minuten opnieuw.'; } else { // Verify credentials $stmt = $db->prepare(" SELECT id, username, email, password_hash, role, is_active FROM users WHERE (username = ? OR email = ?) AND is_active = 1 "); $stmt->execute([$username, $username]); $user = $stmt->fetch(); if ($user && password_verify($password, $user['password_hash'])) { // Success - create session session_regenerate_id(true); $_SESSION['user_id'] = $user['id']; $_SESSION['user'] = [ 'id' => $user['id'], 'username' => $user['username'], 'email' => $user['email'], 'role' => $user['role'] ]; // Log success $stmt = $db->prepare(" INSERT INTO login_attempts (username, ip_address, success) VALUES (?, ?, 1) "); $stmt->execute([$username, $_SERVER['REMOTE_ADDR']]); // Update last login $stmt = $db->prepare("UPDATE users SET last_login = NOW() WHERE id = ?"); $stmt->execute([$user['id']]); header("Location: ../$redirect"); exit; } else { // Failed login $error = 'Ongeldige gebruikersnaam of wachtwoord'; $stmt = $db->prepare(" INSERT INTO login_attempts (username, ip_address, success) VALUES (?, ?, 0) "); $stmt->execute([$username, $_SERVER['REMOTE_ADDR']]); } } } ?> Login - Telvero Talpa

Telvero Talpa

Planning System

Telvero ©
``` ### 2. Authenticatie Functies (auth/auth_functions.php) ```php load(); /** * Get database connection */ function getAuthDb() { static $db = null; if ($db === null) { $db = new PDO( "mysql:host={$_ENV['DB_HOST']};dbname={$_ENV['DB_NAME']}", $_ENV['DB_USER'], $_ENV['DB_PASS'] ); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } return $db; } /** * Check if user is logged in */ function isLoggedIn() { return isset($_SESSION['user_id']) && isset($_SESSION['user']); } /** * Get current logged in user */ function getCurrentUser() { return $_SESSION['user'] ?? null; } /** * Check if user has specific role */ function hasRole($role) { if (!isLoggedIn()) { return false; } return $_SESSION['user']['role'] === $role; } /** * Check if user is admin */ function isAdmin() { return hasRole('admin'); } /** * Check if user is guest */ function isGuest() { return hasRole('guest'); } /** * Require user to be logged in */ function requireLogin() { if (!isLoggedIn()) { $currentUrl = $_SERVER['REQUEST_URI']; $redirect = urlencode($currentUrl); header("Location: /auth/login.php?redirect=$redirect"); exit; } } /** * Require user to have specific role */ function requireRole($role) { requireLogin(); if (!hasRole($role)) { http_response_code(403); echo ' Geen Toegang

Geen Toegang

Je hebt geen toegang tot deze pagina.

Terug naar Dashboard
'; exit; } } /** * Require admin role */ function requireAdmin() { requireRole('admin'); } /** * Logout user */ function logout() { $_SESSION = []; if (isset($_COOKIE[session_name()])) { setcookie(session_name(), '', time() - 3600, '/'); } session_destroy(); } /** * Check if user can perform write operations */ function canWrite() { return isLoggedIn() && isAdmin(); } /** * Check if user can only read */ function canOnlyRead() { return isLoggedIn() && isGuest(); } ``` ### 3. Middleware (auth/middleware.php) ```php ``` ### 5. Voorbeeld: Dashboard met Role-based UI ```php
Je bent ingelogd als Guest. Je kunt alleen informatie bekijken.
1. Infomercial Registreren
``` ### 6. API Beveiliging Voorbeeld ```php false, 'error' => 'Niet geautoriseerd. Log eerst in.' ]); exit; } // Check authorization (admin only for write operations) if (!isAdmin()) { http_response_code(403); echo json_encode([ 'success' => false, 'error' => 'Geen toegang. Alleen admins kunnen uitzendingen aanmaken.' ]); exit; } // Continue with existing logic... ``` ### 7. Gebruikersbeheer Interface (admin/users.php) ```php prepare(" INSERT INTO users (username, email, password_hash, role) VALUES (?, ?, ?, ?) "); $stmt->execute([$username, $email, $passwordHash, $role]); header("Location: users.php?success=created"); exit; } // Handle user update if (isset($_POST['update_user'])) { $userId = $_POST['user_id']; $username = $_POST['username']; $email = $_POST['email']; $role = $_POST['role']; $isActive = isset($_POST['is_active']) ? 1 : 0; $stmt = $db->prepare(" UPDATE users SET username = ?, email = ?, role = ?, is_active = ? WHERE id = ? "); $stmt->execute([$username, $email, $role, $isActive, $userId]); header("Location: users.php?success=updated"); exit; } // Get all users $users = $db->query(" SELECT id, username, email, role, is_active, last_login, created_at FROM users ORDER BY created_at DESC ")->fetchAll(); ?> Gebruikersbeheer - Telvero Talpa

Gebruikersbeheer

Gebruiker succesvol !
Gebruikersnaam Email Rol Status Laatste Login Acties
``` ### 8. JavaScript voor Guest Mode (calendar-init.js aanpassing) ```javascript // In assets/js/calendar-init.js // Check if user is guest const isGuest = ; // Disable drag and drop for guests if (isGuest) { // Disable external events document.querySelectorAll('.infomercial-item').forEach(item => { item.style.cursor = 'not-allowed'; item.style.opacity = '0.6'; item.removeAttribute('draggable'); }); // Make calendar read-only calendar = new FullCalendar.Calendar(calendarEl, { // ... existing config editable: false, droppable: false, eventStartEditable: false, eventDurationEditable: false, eventResourceEditable: false }); // Show tooltip on hover document.querySelectorAll('.infomercial-item').forEach(item => { item.title = 'Alleen admins kunnen infomercials slepen'; }); } ``` ## Visuele Voorbeelden ### Login Pagina ``` ┌─────────────────────────────────────┐ │ │ │ 📺 Telvero Talpa │ │ Planning System