1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
| <?php
header('Content-Type: application/json');
$authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
if (!preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) { http_response_code(401); echo json_encode([ 'success' => false, 'error' => 'Missing or invalid authorization header' ]); exit; }
$accessToken = $matches[1];
function verify_access_token($token) { $oauth_server = 'https://oauth.example.com/introspect';
$response = file_get_contents($oauth_server, false, stream_context_create([ 'http' => [ 'method' => 'POST', 'header' => 'Content-Type: application/x-www-form-urlencoded', 'content' => http_build_query(['token' => $token]) ] ]));
$data = json_decode($response, true);
if (!$data['active']) { return false; }
return $data; }
$tokenData = verify_access_token($accessToken);
if (!$tokenData) { http_response_code(401); echo json_encode([ 'success' => false, 'error' => 'Invalid or expired access token' ]); exit; }
$currentUserId = $tokenData['user_id']; $currentUserRole = $tokenData['role']; $scopes = $tokenData['scope'] ?? [];
function has_scope($required_scope, $token_scopes) { return in_array($required_scope, $token_scopes); }
function check_rate_limit_redis($user_id) { $redis = new Redis(); $redis->connect('127.0.0.1', 6379);
$key = "api_rate_limit:user:$user_id";
$current = time(); $window = 60; $limit = 100;
$redis->zRemRangeByScore($key, 0, $current - $window);
$count = $redis->zCard($key);
if ($count >= $limit) { return false; }
$redis->zAdd($key, $current, uniqid()); $redis->expire($key, $window);
return true; }
if (!check_rate_limit_redis($currentUserId)) { http_response_code(429); echo json_encode([ 'success' => false, 'error' => 'Rate limit exceeded', 'retry_after' => 60 ]); exit; }
$method = $_SERVER['REQUEST_METHOD']; $path = $_SERVER['PATH_INFO'] ?? '';
if ($method == 'GET' && preg_match('/^\/users\/(\d+)$/', $path, $matches)) {
$userId = $matches[1];
if (!has_scope('users:read', $scopes)) { http_response_code(403); echo json_encode([ 'success' => false, 'error' => 'Insufficient permissions: users:read scope required' ]); exit; }
if ($currentUserRole !== 'admin' && $currentUserId != $userId) { http_response_code(403); echo json_encode([ 'success' => false, 'error' => 'Forbidden: You can only view your own data' ]);
logSecurityEvent('Unauthorized API access', [ 'user_id' => $currentUserId, 'target_user_id' => $userId, 'endpoint' => $path, 'method' => $method, 'ip' => $_SERVER['REMOTE_ADDR'] ]);
exit; }
$stmt = $db->prepare('SELECT user_id, user, first_name, last_name, email FROM users WHERE user_id = :id'); $stmt->bindParam(':id', $userId, PDO::PARAM_INT); $stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user) { logAPIAccess($currentUserId, 'GET', $path, 200);
echo json_encode([ 'success' => true, 'data' => $user ]); } else { http_response_code(404); echo json_encode([ 'success' => false, 'error' => 'User not found' ]); }
} elseif ($method == 'PUT' && preg_match('/^\/users\/(\d+)$/', $path, $matches)) {
$userId = $matches[1]; $input = json_decode(file_get_contents('php://input'), true);
if (!has_scope('users:write', $scopes)) { http_response_code(403); echo json_encode([ 'success' => false, 'error' => 'Insufficient permissions: users:write scope required' ]); exit; }
if ($currentUserRole !== 'admin' && $currentUserId != $userId) { http_response_code(403); echo json_encode([ 'success' => false, 'error' => 'Forbidden: You can only update your own data' ]); exit; }
$allowedFields = ['first_name', 'last_name', 'email'];
if ($currentUserRole === 'admin' && has_scope('users:admin', $scopes)) { $allowedFields[] = 'role'; }
$updates = []; $params = [':id' => $userId];
foreach ($input as $key => $value) { if (in_array($key, $allowedFields)) { if ($key === 'email' && !filter_var($value, FILTER_VALIDATE_EMAIL)) { http_response_code(400); echo json_encode([ 'success' => false, 'error' => 'Invalid email format' ]); exit; }
$updates[] = "$key = :$key"; $params[":$key"] = $value; } }
if (empty($updates)) { http_response_code(400); echo json_encode([ 'success' => false, 'error' => 'No valid fields to update' ]); exit; }
$query = "UPDATE users SET " . implode(', ', $updates) . " WHERE user_id = :id"; $stmt = $db->prepare($query);
if ($stmt->execute($params)) { logAPIAccess($currentUserId, 'PUT', $path, 200);
echo json_encode([ 'success' => true, 'message' => 'User updated' ]); } else { http_response_code(500); echo json_encode([ 'success' => false, 'error' => 'Failed to update user' ]); }
} else { http_response_code(404); echo json_encode([ 'success' => false, 'error' => 'Endpoint not found' ]); }
?>
|