api/
ved/
admin/
modules/
gyar/
admin/
cron/
api/gyar/auth/authorization.php1 lines
<?php
# authorization.php
# Funktion som API endpoints använder för att kontrollera authorization token.
enum AuthLevel
{
case STATION;
case ADMIN;
}
# Hämtar vilken nivå av tillåtelse som förfrågas.
function getAuthLevel()
{
$headers = getallheaders();
if (!isset($headers["Authorization"]))
return [null, null];
$authData = explode(" ", $headers["Authorization"]);
if (sizeof($authData) != 2)
return [null, null];
$authType = $authData[0];
$authToken = $authData[1];
require "gyar/modules/database.php";
$hashed = hash("sha256", $authToken);
if ($authType == "Bearer") {
$token = $db->query("SELECT tokenId, userId FROM authToken WHERE tokenHash=:tokenHash AND expiresAt>CURRENT_TIMESTAMP AND (revokedAt IS NULL OR revokedAt>CURRENT_TIMESTAMP)", array("tokenHash" => $hashed));
if (!$token)
return [null, null];
return [AuthLevel::ADMIN, $token["userId"]];
} elseif ($authType == "Station") {
$station = $db->query("SELECT stationId FROM weatherStation WHERE apiKeyHash=:apiKeyHash", array("apiKeyHash" => $hashed));
if (!$station)
return [null, null];
return [AuthLevel::STATION, $station["stationId"]];
}
return [null, null];
}
function acceptAuthorizationLevels($allowedLevels)
{
if (!is_array($allowedLevels))
$allowedLevels = [$allowedLevels];
[$requestedLevel, $data] = getAuthLevel();
if (!$requestedLevel)
throw new APIError(401, "Invalid authorization.");
foreach ($allowedLevels as $level) {
if ($level == $requestedLevel)
return $data;
}
throw new APIError(403, "Missing access to the requested resource.");
}
?>