87 lines
2.1 KiB
PHP
87 lines
2.1 KiB
PHP
<?php
|
|
|
|
namespace Api\Register;
|
|
|
|
use Exception;
|
|
use Khofmann\Api\Api;
|
|
use Khofmann\ApiError\ApiError;
|
|
use Khofmann\Input\Input;
|
|
use Khofmann\Response\Response;
|
|
use Khofmann\Models\User\User;
|
|
|
|
/**
|
|
* Register route handlers
|
|
*/
|
|
class Register extends Api
|
|
{
|
|
/**
|
|
* Register POST handler
|
|
*
|
|
* Register a new user. Required inputs are `username`, `email`, and `password`.
|
|
*
|
|
* Returns user.
|
|
*
|
|
* @throws 400 Missing fields
|
|
* @throws 400 Duplicate
|
|
* @throws 404 Failure to create
|
|
*/
|
|
public function post(): void
|
|
{
|
|
// Fetch all required inputs.
|
|
// Throw 400 error if a required one is missing.
|
|
$missing = [];
|
|
$username = Input::post("username");
|
|
$email = Input::post("email");
|
|
$password = Input::post("password");
|
|
if (empty($username)) array_push($missing, "username");
|
|
if (empty($email)) array_push($missing, "email");
|
|
if (empty($password)) array_push($missing, "password");
|
|
if (count($missing) > 0) throw ApiError::missingField($missing);
|
|
|
|
// Try and create a new user, 400 if duplicate.
|
|
try {
|
|
Response::json(User::create($username, $email, $password));
|
|
} catch (Exception $err) {
|
|
switch ($err->getMessage()) {
|
|
case "NotFound":
|
|
throw ApiError::failed("Failed to create user");
|
|
case "Duplicate":
|
|
throw ApiError::duplicate("user");
|
|
default:
|
|
throw $err;
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Register PATCH handler
|
|
*
|
|
* Confirms a user. Required input is `code`.
|
|
*
|
|
* Returns user.
|
|
*
|
|
* @throws 400 Missing field
|
|
* @throws 404 User not found
|
|
* @throws 404 User already confirmed
|
|
*/
|
|
public function patch(): void
|
|
{
|
|
// Fetch all required inputs.
|
|
// Throw 400 error if a required one is missing.
|
|
$code = Input::post("code");
|
|
if (empty($code)) throw ApiError::missingField(["code"]);
|
|
|
|
// Try and confirm user, 404 if user not found.
|
|
try {
|
|
Response::json(User::confirm($code));
|
|
} catch (Exception $err) {
|
|
switch ($err->getMessage()) {
|
|
case "NotFound":
|
|
throw ApiError::notFound("user");
|
|
default:
|
|
throw $err;
|
|
}
|
|
}
|
|
}
|
|
}
|