Files
Ecobuddy/Models/AuthExample.php
2025-03-15 01:59:16 +00:00

112 lines
2.6 KiB
PHP

<?php
/**
* Example controller showing how to use the simplified authentication
*
* This file demonstrates how to use the User::checkAuth() and User::checkAdmin()
* methods to protect routes without using middleware.
*/
require_once('Models/User.php');
/**
* Example of a protected endpoint that requires authentication
*/
function protectedEndpoint() {
// Check if user is authenticated
$auth = User::checkAuth();
if (!$auth) {
// The checkAuth method already sent the error response
return;
}
// User is authenticated, proceed with the endpoint logic
$response = [
'status' => 'success',
'message' => 'You are authenticated',
'user' => [
'id' => $auth['uid'],
'username' => $auth['username']
]
];
// Send response
header('Content-Type: application/json');
echo json_encode($response);
}
/**
* Example of an admin-only endpoint
*/
function adminEndpoint() {
// Check if user is an admin
$auth = User::checkAdmin();
if (!$auth) {
// The checkAdmin method already sent the error response
return;
}
// User is an admin, proceed with the admin-only logic
$response = [
'status' => 'success',
'message' => 'You have admin access',
'user' => [
'id' => $auth['uid'],
'username' => $auth['username']
]
];
// Send response
header('Content-Type: application/json');
echo json_encode($response);
}
/**
* Example of a public endpoint that doesn't require authentication
* but can still use authentication data if available
*/
function publicEndpoint() {
// Check if user is authenticated, but don't require it
$auth = User::checkAuth(false);
$response = [
'status' => 'success',
'message' => 'This is a public endpoint'
];
// Add user info if authenticated
if ($auth) {
$response['user'] = [
'id' => $auth['uid'],
'username' => $auth['username']
];
} else {
$response['user'] = 'Guest';
}
// Send response
header('Content-Type: application/json');
echo json_encode($response);
}
/**
* Example of how to use these functions in a simple router
*/
function handleRequest() {
$route = $_GET['route'] ?? 'public';
switch ($route) {
case 'protected':
protectedEndpoint();
break;
case 'admin':
adminEndpoint();
break;
case 'public':
default:
publicEndpoint();
break;
}
}
// Call the router function
handleRequest();