Files
UpAndDown/src/endpoints_handlers/AuthRegistrationExecutor.h
T

109 lines
2.7 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#pragma once
#include <regex>
#include <boost/json.hpp>
#include <mysqlx/xdevapi.h>
#include <mysqlx/common/api.h>
#include "IExecutor.h"
#include "../DAO/IUserDAO.h"
namespace uad
{
template <class Body, class Allocator, class ResponseType>
class AuthRegistrationExecutor : public IExecutor<Body, Allocator, ResponseType>
{
mysqlx::Session& session_;
std::shared_ptr<IUserDAO> user_dao_;
public:
AuthRegistrationExecutor(mysqlx::Session& session,
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;
auto body = req.body();
value req_json;
try
{
req_json = json::parse(body);
}
catch (const system::system_error& err)
{
http::response<ResponseType> res{http::status::bad_request, req.version()};
res.body() = "{ \"Result\": \"cannot deserialize json\"}";
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<ResponseType> res{http::status::unprocessable_entity, req.version()};
res.body() = "{ \"Result\": \"validations failed\"}";
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<ResponseType> res{http::status::conflict, req.version()};
res.body() = "{ \"Result\": \"user with login " + login + " exists\" }";
res.set(http::field::content_type, "application/json");
res.content_length(res.body().size());
return res;
}
User user;
user.SetLogin(login);
user.SetPassword(password);
http::response<ResponseType> res{
http::status::created, req.version()
};
res.body() = "{ \"Result\": \"ok\"}";
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("[az09._-]");
return std::regex_match(login, pattern);
}
bool ValidatePassword(const std::string& password)
{
return password.size() >= 5;
}
};
}