static function authenticate() { // figure out if we need to challenge the user if (empty($_SERVER['PHP_AUTH_DIGEST'])) { header('HTTP/1.1 401 Unauthorized'); header('WWW-Authenticate: Digest realm="' . self::$AUTH_REALM . '",qop="auth",nonce="' . uniqid() . '",opaque="' . md5(self::$AUTH_REALM) . '"'); // show the error if they hit cancel die(self::$CANCELED); } // now, analayze the PHP_AUTH_DIGEST var if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) || $auth_username != $data['username']) { // show the error due to bad auth die(rest_utils::sendResponse(401)); } // so far, everything's good, let's now check the response a bit more... $A1 = md5($data['username'] . ':' . self::$AUTH_REALM . ':' . $auth_pass); $A2 = md5($_SERVER['REQUEST_METHOD'] . ':' . $data['uri']); $valid_response = md5($A1 . ':' . $data['nonce'] . ':' . $data['nc'] . ':' . $data['cnonce'] . ':' . $data['qop'] . ':' . $A2); // last check.. if ($data['response'] != $valid_response) { die(rest_utils::sendResponse(401)); } return true; // all fine! }
// no id, ad new entity to model $done = newObj('model_' . $modelId)->append($in); if (!$done) { rest_utils::sendResponse($data, 500); } else { rest_utils::sendResponse($data, 201, $done); $tags = http_request::getString('tags'); if ($tags) { tag::set($modelId, $done, $tags); } } } break; case 'put': rest_utils::authenticate(); $in = newObj('entity_' . $modelId)->validate($data->getRequestVars(), sprintf('madr_%s_%s', $data->getMethod(), $modelId)); if (!$in) { rest_utils::sendResponse($data, 400); } $post_vars = $data->getRequestVars(); newObj('model_' . $modelId)->update($in); rest_utils::sendResponse($data, 201, $done); $tags = http_request::getString('tags'); if ($tags) { tag::set($modelId, $post_vars['id'], $tags); } break; case 'delete': rest_utils::sendResponse($data, 501, $done); break; }
function logAPIAction($data = false, $status) { if (is_int($data)) { $method = $data; $vs = array(); } else { $method = $data->getMethod(); $vs = $data->getRequestVars(); } $out = sprintf("[%s] %s %s %s %s [%s]\n", date('Y-m-d H:i:s', time()), strtoupper($method), $_SERVER['REQUEST_URI'], $status, rest_utils::getStatusCodeMessage($status), implode(',', array_keys($vs))); file_put_contents(ROOT . '/log/api.log', $out, FILE_APPEND); }