#pragma once #include #include #include #include #include #include "IExecutor.h" #include "../DAO/IUserDAO.h" namespace uad { template class AuthRegistrationExecutor : public IExecutor { mysqlx::Session& session_; std::shared_ptr user_dao_; public: AuthRegistrationExecutor(mysqlx::Session& session, std::shared_ptr user_dao) : session_(session), user_dao_(user_dao) { } boost::beast::http::response operator ()( boost::beast::http::request>&& req ) override { using namespace boost; using namespace boost::json; using namespace boost::beast; using namespace std::string_literals; auto body = req.body(); value req_json; value response_body; response_body.emplace_object(); try { req_json = json::parse(body); } catch (const system::system_error& err) { http::response res{http::status::bad_request, req.version()}; response_body.as_object().emplace("Result", "cannot deserialize json"); res.body() = serialize(response_body); res.set(http::field::content_type, "application/json"); res.content_length(res.body().size()); return res; } std::string login = req_json.as_object().at("login").as_string().c_str(); std::string password = req_json.as_object().at("password").as_string().c_str(); if (!ValidateLogin(login) || !ValidatePassword(password)) { http::response res{http::status::unprocessable_entity, req.version()}; response_body.as_object().emplace( "Result", "Validations failed. Login should have length from 3 to 50. Password from 5 characters length." ); res.body() = serialize(response_body); res.set(http::field::content_type, "application/json"); res.content_length(res.body().size()); return res; } if (user_dao_->GetByLogin(login).has_value()) { http::response res{http::status::conflict, req.version()}; response_body.as_object().emplace( "Result", "user with login "s + login + " exists"s ); res.body() = serialize(response_body); res.set(http::field::content_type, "application/json"); res.content_length(res.body().size()); return res; } User user; user.SetLogin(login); user.SetPassword(password); const auto uuid_stringified = user_dao_->Create(user); http::response res{ http::status::created, req.version() }; response_body.as_object().emplace( "uuid", uuid_stringified ); response_body.as_object().emplace( "login", user.GetLogin() ); 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; } }; }