generated from Sithas/conan_template
110 lines
2.7 KiB
C++
110 lines
2.7 KiB
C++
#pragma once
|
|
|
|
#include <regex>
|
|
#include <boost/json.hpp>
|
|
#include <mysqlx/xdevapi.h>
|
|
#include <boost/log/trivial.hpp>
|
|
|
|
#include "IExecutor.h"
|
|
#include "../DAO/IUserDAO.h"
|
|
#include "../exceptions/session_exception.h"
|
|
|
|
namespace uad
|
|
{
|
|
template <class Body, class Allocator, class ResponseType>
|
|
class AuthRegistrationExecutor : public IExecutor<Body, Allocator, ResponseType>
|
|
{
|
|
mysqlx::Session& session_;
|
|
const std::shared_ptr<IUserDAO>& user_dao_;
|
|
|
|
public:
|
|
AuthRegistrationExecutor(mysqlx::Session& session,
|
|
const std::shared_ptr<IUserDAO>& user_dao)
|
|
: session_(session), user_dao_(user_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;
|
|
|
|
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 (!ValidateLogin(login) || !ValidatePassword(password))
|
|
{
|
|
throw session_exception(
|
|
http::status::unprocessable_entity,
|
|
"Validations failed. Login should have length from 3 to 50. Password from 5 characters length."s
|
|
);
|
|
}
|
|
|
|
if (user_dao_->GetByLogin(login).has_value())
|
|
{
|
|
throw session_exception(http::status::conflict, "user with login "s + login + " exists"s);
|
|
}
|
|
|
|
user user;
|
|
|
|
user.login = login;
|
|
user.hashed_password = HashPassword(password);
|
|
|
|
const std::string uuid_stringified = user_dao_->Create(user);
|
|
|
|
http::response<ResponseType> res{
|
|
http::status::created, req.version()
|
|
};
|
|
value response_body;
|
|
|
|
response_body.emplace_object();
|
|
|
|
response_body.as_object().emplace(
|
|
"uuid",
|
|
uuid_stringified
|
|
);
|
|
response_body.as_object().emplace(
|
|
"login",
|
|
user.login
|
|
);
|
|
|
|
res.body() = serialize(response_body);
|
|
res.set(http::field::content_type, "application/json");
|
|
res.content_length(res.body().size());
|
|
|
|
return res;
|
|
}
|
|
|
|
private:
|
|
bool ValidateLogin(const std::string& login)
|
|
{
|
|
if (login.size() < 3 || login.size() > 50) return false;
|
|
|
|
std::regex pattern(std::string("^[A-Za-z0-9_]+$"));
|
|
|
|
return std::regex_match(login, pattern);
|
|
}
|
|
|
|
bool ValidatePassword(const std::string& password)
|
|
{
|
|
return password.size() >= 5;
|
|
}
|
|
};
|
|
}
|