PHP-Course/exam/api/Login/Login.php
2024-07-29 22:06:57 +02:00

58 lines
1.4 KiB
PHP

<?php
namespace Api\Login;
use Exception;
use Khofmann\Api\Api;
use Khofmann\ApiError\ApiError;
use Khofmann\Input\Input;
use Khofmann\Response\Response;
use Khofmann\Models\User\User;
/**
* Login route handlers
*/
class Login extends Api
{
/**
* Login POST handler
*
* Log in a user. Required inputs are `email` and `password`.
*
* Returns user and tokens
*
* @throws 400 Missing field
* @throws 401 Invalid credentials (login fails)
* @throws 404 User not found
* @throws 500 Failed to log in user
*/
public function post(): void
{
// Fetch all required inputs.
// Throw 400 error if a required one is missing.
$missing = [];
$email = Input::post("email");
$password = Input::post("password");
if (empty($email)) array_push($missing, "email");
if (empty($password)) array_push($missing, "password");
if (count($missing) > 0) throw ApiError::missingField($missing);
// Try and log in user.
// Throw errors according to situation.
try {
Response::json(User::logIn($email, $password));
} catch (Exception $err) {
switch ($err->getMessage()) {
case "Failed":
throw ApiError::failed("Login failed");
case "NotFound":
throw ApiError::notFound("user");
case "Invalid":
throw ApiError::notAllowed("Invalid username or password");
default:
throw $err;
}
}
}
}