pica/handler/login.cpp

80 lines
2.9 KiB
C++

//SPDX-FileCopyrightText: 2023 Yury Gubich <blue@macaw.me>
//SPDX-License-Identifier: GPL-3.0-or-later
#include "login.h"
#include "server/server.h"
#include "database/exceptions.h"
Handler::Login::Login(std::weak_ptr<Server> server):
Handler("login", Request::Method::post),
server(server)
{}
void Handler::Login::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);
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);
std::shared_ptr<Server> srv = server.lock();
if (!srv)
return error(request, Result::unknownError, Response::Status::internalError);
bool success = false;
try {
success = srv->validatePassword(login, password);
} catch (const DB::NoLogin& e) {
std::cerr << "Exception on logging in:\n\t" << e.what() << std::endl;
return error(request, Result::wrongCredentials, Response::Status::badRequest);
} catch (const std::exception& e) {
std::cerr << "Exception on logging in:\n\t" << e.what() << std::endl;
return error(request, Result::unknownError, Response::Status::internalError);
} catch (...) {
std::cerr << "Unknown exception on ogging in" << std::endl;
return error(request, Result::unknownError, Response::Status::internalError);
}
if (!success)
return error(request, Result::wrongCredentials, Response::Status::badRequest);
nlohmann::json body = nlohmann::json::object();
body["result"] = Result::success;
try {
Session& session = srv->openSession(login);
body["accessToken"] = session.getAccessToken();
body["renewToken"] = session.getRenewToken();
} catch (const std::exception& e) {
std::cerr << "Exception on opening a session:\n\t" << e.what() << std::endl;
return error(request, Result::unknownError, Response::Status::internalError);
} catch (...) {
std::cerr << "Unknown exception on opening a session" << std::endl;
return error(request, Result::unknownError, Response::Status::internalError);
}
Response& res = request.createResponse();
res.setBody(body);
res.send();
}
void Handler::Login::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();
}