accounts = $accounts; $this->authModel = $model; } /** * @param array $request * @return HttpResponse */ public function listUsers(array $request): HttpResponse { return Control::runCheckedFrom($request, [ 'start' => [DefaultValidators::isUnsignedInteger()], 'n' => [DefaultValidators::isUnsignedInteger()], 'search' => [DefaultValidators::lenBetween(0, 256)], ], function (HttpRequest $req) { $accounts = $this->accounts->searchAccounts(intval($req['start']), intval($req['n']), $req["search"]); $users = array_map(fn(Account $acc) => $acc->getUser(), $accounts); return new JsonHttpResponse([ "users" => $users, "totalCount" => $this->accounts->totalCount(), ]); }, true); } /** * @param int $userId * @return HttpResponse given user information. */ public function getUser(int $userId): HttpResponse { $acc = $this->accounts->getAccount($userId); if ($acc == null) { return new JsonHttpResponse([ValidationFail::notFound("User not found")], HttpCodes::NOT_FOUND); } return new JsonHttpResponse($acc->getUser()); } public function addUser(): HttpResponse { return Control::runChecked([ "username" => [DefaultValidators::name()], "email" => [DefaultValidators::email()], "password" => [DefaultValidators::password()], "isAdmin" => [DefaultValidators::bool()], ], function (HttpRequest $req) { $model = new AuthModel($this->accounts); $account = $model->register($req["username"], $req["password"], $req["email"]); if ($account == null) { return new JsonHttpResponse([new ValidationFail("already exists", "An account with provided email ")], HttpCodes::FORBIDDEN); } return new JsonHttpResponse([ "id" => $account->getUser()->getId(), ]); }, true); } public function removeUsers(): HttpResponse { return Control::runChecked([ "identifiers" => [DefaultValidators::array(), DefaultValidators::forall(DefaultValidators::isUnsignedInteger())], ], function (HttpRequest $req) { $this->accounts->removeAccounts($req["identifiers"]); return HttpResponse::fromCode(HttpCodes::OK); }, true); } public function updateUser(int $id): HttpResponse { return Control::runChecked([ "email" => [DefaultValidators::email()], "username" => [DefaultValidators::name()], "isAdmin" => [DefaultValidators::bool()], ], function (HttpRequest $req) use ($id) { $mailAccount = $this->accounts->getAccount($id); if ($mailAccount->getUser()->getId() != $id) { return new JsonHttpResponse([new ValidationFail("email exists", "The provided mail address already exists for another account.")], HttpCodes::FORBIDDEN); } $this->authModel->update($id, $req["email"], $req["username"], $req["isAdmin"]); return HttpResponse::fromCode(HttpCodes::OK); }, true); } }