Skip to content

Commit

Permalink
Use Symfony Response HTTP status code constants (#3472)
Browse files Browse the repository at this point in the history
  • Loading branch information
tadhgboyle committed Dec 16, 2023
1 parent c04dca1 commit fcaa517
Show file tree
Hide file tree
Showing 12 changed files with 43 additions and 36 deletions.
7 changes: 4 additions & 3 deletions core/classes/Endpoints/Endpoints.php
@@ -1,4 +1,5 @@
<?php
use Symfony\Component\HttpFoundation\Response;
/**
* Endpoint management class.
*
Expand Down Expand Up @@ -49,7 +50,7 @@ public function handle(string $route, string $method, Nameless2API $api): void {
? Nameless2API::ERROR_INVALID_API_KEY
: Nameless2API::ERROR_NOT_AUTHORIZED,
null,
403
Response::HTTP_UNAUTHORIZED
);
}

Expand All @@ -74,10 +75,10 @@ public function handle(string $route, string $method, Nameless2API $api): void {
}

if ($matched_endpoint !== null) {
$api->throwError(Nameless2API::ERROR_INVALID_API_METHOD, "The $route endpoint only accepts " . implode(', ', $available_methods) . ", $method was used.", 405);
$api->throwError(Nameless2API::ERROR_INVALID_API_METHOD, "The $route endpoint only accepts " . implode(', ', $available_methods) . ", $method was used.", Response::HTTP_METHOD_NOT_ALLOWED);
}

$api->throwError(Nameless2API::ERROR_INVALID_API_METHOD, 'If you are seeing this while in a browser, this means your API is functioning!', 404);
$api->throwError(Nameless2API::ERROR_INVALID_API_METHOD, 'If you are seeing this while in a browser, this means your API is functioning!', Response::HTTP_NOT_FOUND);
}

/**
Expand Down
8 changes: 4 additions & 4 deletions core/classes/Endpoints/KeyAuthEndpoint.php
@@ -1,4 +1,5 @@
<?php
use Symfony\Component\HttpFoundation\Response;
/**
* Allows an endpoint to require an API key to be present (and valid) in the request.
*
Expand Down Expand Up @@ -31,23 +32,22 @@ final public function isAuthorised(Nameless2API $api): bool {
// Some hosting providers remove the Authorization header, fall back to non-standard X-API-Key heeader
$api_key_header = HttpUtils::getHeader('X-API-Key');
if ($api_key_header === null) {
$api->throwError(Nameless2API::ERROR_MISSING_API_KEY, 'Missing authorization header');
$api->throwError(Nameless2API::ERROR_MISSING_API_KEY, 'Missing authorization header', Response::HTTP_UNAUTHORIZED);
}

$api_key = $api_key_header;
}

return $this->validateKey($api, $api_key);
return $this->validateKey($api_key);
}

/**
* Validate provided API key to make sure it matches.
*
* @param Nameless2API $api Instance of API to use for database connection.
* @param string $api_key API key to check.
* @return bool Whether it matches or not.
*/
private function validateKey(Nameless2API $api, string $api_key): bool {
private function validateKey(string $api_key): bool {
$correct_key = Settings::get('mc_api_key');
if ($correct_key === null) {
die('API key is null');
Expand Down
4 changes: 2 additions & 2 deletions core/includes/image_upload.php
Expand Up @@ -119,7 +119,7 @@
Redirect::to(URL::build('/profile/' . urlencode($user->data()->username)));
}

http_response_code(500);
http_response_code(\Symfony\Component\HttpFoundation\Response::HTTP_BAD_REQUEST);
$error = $image->getError() ?: 'Unknown error, check logs for more details';
ErrorHandler::logWarning('Image upload error: ' . $error);
die($error);
Expand Down Expand Up @@ -155,7 +155,7 @@

die('OK');
} catch (Exception $e) {
http_response_code(500);
http_response_code(\Symfony\Component\HttpFoundation\Response::HTTP_BAD_REQUEST);
$error = $e->getMessage() ?: 'Unknown error, check logs for more details';
ErrorHandler::logWarning('Image upload exception: ' . $error);
die($error);
Expand Down
8 changes: 4 additions & 4 deletions modules/Core/classes/Misc/Nameless2API.php
@@ -1,4 +1,5 @@
<?php
use Symfony\Component\HttpFoundation\Response;
/**
* NamelessMC API v2 class
*
Expand Down Expand Up @@ -53,9 +54,8 @@ public function __construct(string $route, Language $api_language, Endpoints $en
$_SERVER['REQUEST_METHOD'],
$this
);

} catch (Exception $e) {
$this->throwError(self::ERROR_UNKNOWN_ERROR, $e->getMessage());
$this->throwError(self::ERROR_UNKNOWN_ERROR, $e->getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR);
}
}

Expand All @@ -67,7 +67,7 @@ public function __construct(string $route, Language $api_language, Endpoints $en
* @param int $status HTTP status code
* @return never
*/
public function throwError(string $error, $meta = null, int $status = 400): void {
public function throwError(string $error, $meta = null, int $status = Response::HTTP_BAD_REQUEST): void {
$this->returnArray(
array_merge(['error' => $error], $meta ? ['meta' => $meta] : []),
$status
Expand Down Expand Up @@ -112,7 +112,7 @@ public function getLanguage(): Language {
* @param int $status HTTP status code
* @return never
*/
public function returnArray(array $array, int $status = 200): void {
public function returnArray(array $array, int $status = Response::HTTP_OK): void {
http_response_code($status);

die(self::encodeJson($array));
Expand Down
5 changes: 3 additions & 2 deletions modules/Core/includes/endpoints/RegisterEndpoint.php
@@ -1,4 +1,5 @@
<?php
use Symfony\Component\HttpFoundation\Response;

/**
* @param string $username The username of the new user to create
Expand Down Expand Up @@ -171,7 +172,7 @@ private function createUser(Nameless2API $api, string $username, string $email,
return ['user_id' => $user_id];

} catch (Exception $e) {
$api->throwError(CoreApiErrors::ERROR_UNABLE_TO_CREATE_ACCOUNT, $e->getMessage());
$api->throwError(CoreApiErrors::ERROR_UNABLE_TO_CREATE_ACCOUNT, $e->getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR);
}
}

Expand Down Expand Up @@ -210,7 +211,7 @@ private function sendRegistrationEmail(Nameless2API $api, string $username, stri
'user_id' => $user_id
]);

$api->throwError(CoreApiErrors::ERROR_UNABLE_TO_SEND_REGISTRATION_EMAIL);
$api->throwError(CoreApiErrors::ERROR_UNABLE_TO_SEND_REGISTRATION_EMAIL, null, Response::HTTP_INTERNAL_SERVER_ERROR);
}

$api->returnArray(['message' => $api->getLanguage()->get('api', 'finish_registration_email')]);
Expand Down
7 changes: 4 additions & 3 deletions modules/Core/includes/endpoints/ServerInfoEndpoint.php
@@ -1,4 +1,5 @@
<?php
use Symfony\Component\HttpFoundation\Response;

class ServerInfoEndpoint extends KeyAuthEndpoint {

Expand Down Expand Up @@ -61,7 +62,7 @@ public function execute(Nameless2API $api): void {
file_put_contents(ROOT_PATH . DIRECTORY_SEPARATOR . 'cache' . DIRECTORY_SEPARATOR . sha1('server_query_cache') . '.cache', json_encode($to_cache));
}
} catch (Exception $e) {
$api->throwError(CoreApiErrors::ERROR_UNABLE_TO_UPDATE_SERVER_INFO, $e->getMessage(), 500);
$api->throwError(CoreApiErrors::ERROR_UNABLE_TO_UPDATE_SERVER_INFO, $e->getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR);
}

$cache = new Cache(['name' => 'nameless', 'extension' => '.cache', 'path' => ROOT_PATH . '/cache/']);
Expand All @@ -83,7 +84,7 @@ public function execute(Nameless2API $api): void {
}
}
} catch (Exception $e) {
$api->throwError(CoreApiErrors::ERROR_UNABLE_TO_UPDATE_SERVER_INFO, $e->getMessage(), 500);
$api->throwError(CoreApiErrors::ERROR_UNABLE_TO_UPDATE_SERVER_INFO, $e->getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR);
}
}

Expand All @@ -105,7 +106,7 @@ public function execute(Nameless2API $api): void {
], intval($_POST['interval_seconds'] ?? 10) * 2);
}
} catch (Exception $e) {
$api->throwError(CoreApiErrors::ERROR_UNABLE_TO_UPDATE_SERVER_INFO, $e->getMessage(), 500);
$api->throwError(CoreApiErrors::ERROR_UNABLE_TO_UPDATE_SERVER_INFO, $e->getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR);
}

$api->returnArray(array_merge(['message' => $api->getLanguage()->get('api', 'server_info_updated')]));
Expand Down
3 changes: 2 additions & 1 deletion modules/Core/includes/endpoints/UpdateUsernameEndpoint.php
@@ -1,4 +1,5 @@
<?php
use Symfony\Component\HttpFoundation\Response;

/**
* @param int $id The NamelessMC user to update
Expand Down Expand Up @@ -27,7 +28,7 @@ public function execute(Nameless2API $api, User $user): void {
try {
$api->getDb()->update('users', $user->data()->id, $fields);
} catch (Exception $e) {
$api->throwError(CoreApiErrors::ERROR_UNABLE_TO_UPDATE_USERNAME, null, 500);
$api->throwError(CoreApiErrors::ERROR_UNABLE_TO_UPDATE_USERNAME, null, Response::HTTP_INTERNAL_SERVER_ERROR);
}

$api->returnArray(['message' => $api->getLanguage()->get('api', 'username_updated')]);
Expand Down
16 changes: 8 additions & 8 deletions modules/Core/queries/reactions.php
Expand Up @@ -5,20 +5,20 @@
// Validate form input
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
if (!isset($_GET['reactable_id']) || !is_numeric($_GET['reactable_id'])) {
http_response_code(400);
http_response_code(\Symfony\Component\HttpFoundation\Response::HTTP_BAD_REQUEST);
die('Invalid input');
}
$reactable_id = $_GET['reactable_id'];
$context = $_GET['context'];
} else {
// User must be logged in to proceed
if (!$user->isLoggedIn()) {
http_response_code(401);
http_response_code(\Symfony\Component\HttpFoundation\Response::HTTP_UNAUTHORIZED);
die('Not logged in');
}

if (!isset($_POST['reactable_id'], $_POST['reaction_id']) || !is_numeric($_POST['reactable_id']) || !is_numeric($_POST['reaction_id'])) {
http_response_code(400);
http_response_code(\Symfony\Component\HttpFoundation\Response::HTTP_BAD_REQUEST);
die('Invalid input');
}
$reactable_id = $_POST['reactable_id'];
Expand All @@ -28,14 +28,14 @@
$reaction_context = ReactionContextsManager::getInstance()->getContext($context);

if (!$reaction_context->isEnabled()) {
http_response_code(400);
http_response_code(\Symfony\Component\HttpFoundation\Response::HTTP_BAD_REQUEST);
die('Reactions disabled in this context');
}

// Ensure exists
$reactable = $reaction_context->validateReactable($reactable_id, $user);
if (!$reactable) {
http_response_code(400);
http_response_code(\Symfony\Component\HttpFoundation\Response::HTTP_BAD_REQUEST);
die('Invalid reactable');
}

Expand Down Expand Up @@ -131,7 +131,7 @@

// add reaction
if (!Token::check()) {
http_response_code(400);
http_response_code(\Symfony\Component\HttpFoundation\Response::HTTP_BAD_REQUEST);
die('Invalid token');
}

Expand All @@ -145,7 +145,7 @@
$reaction_context->name(),
));

http_response_code(200);
http_response_code(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
die('Reaction deleted');
}

Expand All @@ -158,5 +158,5 @@
$reaction_context->name(),
));

http_response_code(200);
http_response_code(\Symfony\Component\HttpFoundation\Response::HTTP_OK);
die('Reaction added');
8 changes: 4 additions & 4 deletions modules/Core/queries/tinymce_image_upload.php
@@ -1,12 +1,12 @@
<?php

if (!$user->isLoggedIn()) {
http_response_code(400);
http_response_code(\Symfony\Component\HttpFoundation\Response::HTTP_UNAUTHORIZED);
die('Not logged in');
}

if (!Token::check()) {
http_response_code(400);
http_response_code(\Symfony\Component\HttpFoundation\Response::HTTP_BAD_REQUEST);
die('Invalid token');
}

Expand All @@ -18,7 +18,7 @@

if ($image['file']) {
if (!$image->upload()) {
http_response_code(500);
http_response_code(\Symfony\Component\HttpFoundation\Response::HTTP_INTERNAL_SERVER_ERROR);
$error = $image->getError() ?: 'Unknown error, check logs for more details';
ErrorHandler::logWarning('TinyMCE image upload error: ' . $error);
die($error);
Expand All @@ -29,5 +29,5 @@
]));
}

http_response_code(400);
http_response_code(\Symfony\Component\HttpFoundation\Response::HTTP_BAD_REQUEST);
die('No file uploaded');
@@ -1,4 +1,5 @@
<?php
use Symfony\Component\HttpFoundation\Response;

/**
* @param string $roles An array of Discord Roles with their name and ID
Expand All @@ -24,7 +25,7 @@ public function execute(Nameless2API $api): void {
try {
Discord::saveRoles($roles);
} catch (Exception $e) {
$api->throwError(DiscordApiErrors::ERROR_UNABLE_TO_UPDATE_DISCORD_ROLES, $e->getMessage(), 500);
$api->throwError(DiscordApiErrors::ERROR_UNABLE_TO_UPDATE_DISCORD_ROLES, $e->getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR);
}

$api->returnArray(['message' => Discord::getLanguageTerm('discord_settings_updated')]);
Expand Down
@@ -1,4 +1,5 @@
<?php
use Symfony\Component\HttpFoundation\Response;

/**
* @param string $url New Discord bot URL
Expand All @@ -20,23 +21,23 @@ public function execute(Nameless2API $api): void {
try {
Settings::set('discord_bot_url', $_POST['url']);
} catch (Exception $e) {
$api->throwError(DiscordApiErrors::ERROR_UNABLE_TO_SET_DISCORD_BOT_URL, $e->getMessage(), 500);
$api->throwError(DiscordApiErrors::ERROR_UNABLE_TO_SET_DISCORD_BOT_URL, $e->getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR);
}
}

if (isset($_POST['guild_id'])) {
try {
Settings::set('discord', $_POST['guild_id']);
} catch (Exception $e) {
$api->throwError(DiscordApiErrors::ERROR_UNABLE_TO_SET_DISCORD_GUILD_ID, $e->getMessage(), 500);
$api->throwError(DiscordApiErrors::ERROR_UNABLE_TO_SET_DISCORD_GUILD_ID, $e->getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR);
}
}

if (isset($_POST['bot_username'])) {
try {
Settings::set('discord_bot_username', $_POST['bot_username']);
} catch (Exception $e) {
$api->throwError(DiscordApiErrors::ERROR_UNABLE_TO_SET_DISCORD_BOT_USERNAME, $e->getMessage(), 500);
$api->throwError(DiscordApiErrors::ERROR_UNABLE_TO_SET_DISCORD_BOT_USERNAME, $e->getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR);
}
}

Expand Down
@@ -1,4 +1,5 @@
<?php
use Symfony\Component\HttpFoundation\Response;

/**
* @param string $user JSON Array of user ID -> Discord username to update
Expand Down Expand Up @@ -35,7 +36,7 @@ public function execute(Nameless2API $api): void {
}
}
} catch (Exception $e) {
$api->throwError(DiscordApiErrors::ERROR_UNABLE_TO_SET_DISCORD_BOT_USERNAME, $e->getMessage(), 500);
$api->throwError(DiscordApiErrors::ERROR_UNABLE_TO_SET_DISCORD_BOT_USERNAME, $e->getMessage(), Response::HTTP_INTERNAL_SERVER_ERROR);
}

$api->returnArray(['message' => Discord::getLanguageTerm('discord_usernames_updated'), 'updated_users' => $updated]);
Expand Down

0 comments on commit fcaa517

Please sign in to comment.