Make API work with user/pass combo

master
Skylar Ittner hace 5 años
padre d7ca7125ce
commit d36b340692

@ -48,20 +48,27 @@ function getCensoredKey() {
/**
* Check if the request is allowed
* @global type $VARS
* @global type $database
* @global array $VARS
* @return bool true if the request should continue, false if the request is bad
*/
function authenticate(): bool {
global $VARS, $database;
if (empty($VARS['key'])) {
global $VARS;
// HTTP basic auth
if (!empty($_SERVER['PHP_AUTH_USER']) && !empty($_SERVER['PHP_AUTH_PW'])) {
$user = User::byUsername($_SERVER['PHP_AUTH_USER']);
if (!$user->checkPassword($_SERVER['PHP_AUTH_PW'])) {
return false;
}
return true;
}
// Form auth
if (empty($VARS['username']) || empty($VARS['password'])) {
return false;
} else {
$key = $VARS['key'];
if ($database->has('apikeys', ['key' => $key]) !== TRUE) {
engageRateLimit();
http_response_code(403);
Log::insert(LogType::API_BAD_KEY, null, "Key: " . $key);
$username = $VARS['username'];
$password = $VARS['password'];
$user = User::byUsername($username);
if ($user->exists() !== true || Login::auth($username, $password) !== Login::LOGIN_OK) {
return false;
}
}

@ -25,13 +25,14 @@ if (json_last_error() == JSON_ERROR_NONE) {
if (strpos($_SERVER['REQUEST_URI'], "/api.php") === FALSE) {
$route = explode("/", substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], "api/") + 4));
if (count($route) > 1) {
if (count($route) >= 1) {
$VARS["action"] = $route[0];
}
if (count($route) >= 2 && strpos($route[1], "?") !== 0) {
$VARS["key"] = $route[1];
for ($i = 2; $i < count($route); $i++) {
for ($i = 1; $i < count($route); $i++) {
if (empty($route[$i]) || strpos($route[$i], "=") === false) {
continue;
}
$key = explode("=", $route[$i], 2)[0];
$val = explode("=", $route[$i], 2)[1];
$VARS[$key] = $val;
@ -49,8 +50,9 @@ if (strpos($_SERVER['REQUEST_URI'], "/api.php") === FALSE) {
}
if (!authenticate()) {
http_response_code(403);
die("403 Unauthorized");
header('WWW-Authenticate: Basic realm="' . $SETTINGS['site_title'] . '"');
header('HTTP/1.1 401 Unauthorized');
die("401 Unauthorized: you need to supply valid credentials.");
}
if (empty($VARS['action'])) {

Cargando…
Cancelar
Guardar