pica/handler/register.cpp

69 lines
2.3 KiB
C++

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