Files
UpAndDown/src/endpoints_handlers/AuthLoginExecutor.h
T

88 lines
2.5 KiB
C++

#pragma once
#include <boost/log/trivial.hpp>
#include <regex>
#include <boost/json.hpp>
#include <mysqlx/xdevapi.h>
#include <mysqlx/common/api.h>
#include <boost/uuid.hpp>
#include "IExecutor.h"
#include "../DAO/IUserDAO.h"
#include "../DAO/IAuthDAO.h"
#include "../helpers/helpers.h"
#include "../exceptions/session_exception.h"
namespace uad
{
template <class Body, class Allocator, class ResponseType>
class AuthLoginExecutor : public IExecutor<Body, Allocator, ResponseType>
{
mysqlx::Session& session_;
const std::shared_ptr<IUserDAO>& user_dao_;
const std::shared_ptr<IAuthDAO>& auth_dao_;
public:
AuthLoginExecutor(mysqlx::Session& session,
const std::shared_ptr<IUserDAO>& user_dao,
const std::shared_ptr<IAuthDAO>& auth_dao)
: session_(session), user_dao_(user_dao), auth_dao_(auth_dao)
{
}
boost::beast::http::response<ResponseType> operator ()(
boost::beast::http::request<Body, boost::beast::http::basic_fields<Allocator>>&& req
) override
{
using namespace boost;
using namespace boost::json;
using namespace boost::beast;
using namespace std::string_literals;
BOOST_LOG_TRIVIAL(info) << "POST /api/v1/Auth/Login - Request";
const auto body = req.body();
value req_json;
try
{
req_json = json::parse(body);
}
catch (const system::system_error& err)
{
throw session_exception(http::status::bad_request, "cannot deserialize json");
}
const std::string login = req_json.as_object().at("login").as_string().c_str();
const std::string password = req_json.as_object().at("password").as_string().c_str();
if (login.empty() || password.empty())
{
throw session_exception(http::status::unprocessable_entity, "Login or password are empty"s);
}
const std::optional<user> maybe_user = user_dao_->GetByLogin(login);
if (!maybe_user.has_value() && maybe_user.value().hashed_password != HashPassword(password))
{
throw session_exception(http::status::forbidden,"Incorrect login or password");
}
const std::string token = GenerateUUID();
auth_dao_->Login(maybe_user.value().uuid, token);
http::response<ResponseType> res{http::status::ok, req.version()};
value response_body;
response_body.emplace_object();
response_body.as_object().emplace("token", token);
res.body() = serialize(response_body);
res.set(http::field::content_type, "application/json");
res.content_length(res.body().size());
return res;
}
};
}