pica/handler/register.cpp

65 lines
2.2 KiB
C++
Raw Normal View History

2023-12-14 22:17:28 +00:00
// SPDX-FileCopyrightText: 2023 Yury Gubich <blue@macaw.me>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "register.h"
2023-12-20 22:42:13 +00:00
#include "server/server.h"
2023-12-22 23:25:20 +00:00
#include "database/exceptions.h"
2023-12-20 22:42:13 +00:00
Handler::Register::Register(Server* server):
Handler("register", Request::Method::post),
server(server)
2023-12-14 22:17:28 +00:00
{}
void Handler::Register::handle(Request& request) {
std::map form = request.getForm();
2023-12-20 22:42:13 +00:00
std::map<std::string, std::string>::const_iterator itr = form.find("login");
if (itr == form.end())
2023-12-22 23:25:20 +00:00
return error(request, Result::noLogin, Response::Status::badRequest);
2023-12-20 22:42:13 +00:00
const std::string& login = itr->second;
if (login.empty())
2023-12-22 23:25:20 +00:00
return error(request, Result::emptyLogin, Response::Status::badRequest);
2023-12-20 22:42:13 +00:00
//TODO login policies checkup
itr = form.find("password");
if (itr == form.end())
2023-12-22 23:25:20 +00:00
return error(request, Result::noPassword, Response::Status::badRequest);
2023-12-20 22:42:13 +00:00
const std::string& password = itr->second;
if (password.empty())
2023-12-22 23:25:20 +00:00
return error(request, Result::emptyPassword, Response::Status::badRequest);
2023-12-20 22:42:13 +00:00
//TODO password policies checkup
try {
server->registerAccount(login, password);
2023-12-29 17:40:00 +00:00
} catch (const DB::DuplicateLogin& e) {
2023-12-22 23:25:20 +00:00
std::cerr << "Exception on registration:\n\t" << e.what() << std::endl;
return error(request, Result::loginExists, Response::Status::conflict);
2023-12-20 22:42:13 +00:00
} catch (const std::exception& e) {
std::cerr << "Exception on registration:\n\t" << e.what() << std::endl;
2023-12-22 23:25:20 +00:00
return error(request, Result::unknownError, Response::Status::internalError);
} catch (...) {
2023-12-20 22:42:13 +00:00
std::cerr << "Unknown exception on registration" << std::endl;
2023-12-22 23:25:20 +00:00
return error(request, Result::unknownError, Response::Status::internalError);
2023-12-20 22:42:13 +00:00
}
2023-12-14 22:17:28 +00:00
2023-12-22 23:25:20 +00:00
Response& res = request.createResponse();
2023-12-20 22:42:13 +00:00
nlohmann::json body = nlohmann::json::object();
body["result"] = Result::success;
res.setBody(body);
res.send();
}
2023-12-14 22:17:28 +00:00
2023-12-22 23:25:20 +00:00
void Handler::Register::error(Request& request, Result result, Response::Status code) {
Response& res = request.createResponse(code);
2023-12-14 22:17:28 +00:00
nlohmann::json body = nlohmann::json::object();
2023-12-20 22:42:13 +00:00
body["result"] = result;
2023-12-14 22:17:28 +00:00
res.setBody(body);
res.send();
}