14 Commits

26 changed files with 577 additions and 198 deletions
+120 -106
View File
@@ -1,4 +1,4 @@
cmake_minimum_required(VERSION 3.29.8) cmake_minimum_required(VERSION 3.28.3)
project(UpAndDown) project(UpAndDown)
set(CMAKE_CXX_STANDARD 23) set(CMAKE_CXX_STANDARD 23)
@@ -8,12 +8,14 @@ if (POLICY CMP0167)
cmake_policy(SET CMP0167 OLD) cmake_policy(SET CMP0167 OLD)
endif () endif ()
set(Boost_USE_STATIC_LIBS ON)
set(Boost_USE_MULTITHREADED ON) set(Boost_USE_MULTITHREADED ON)
set(Boost_INCLUDE_DIR ${BOOST_ROOT})
set(Boost_LIBRARY_DIR "${BOOST_ROOT}/stage/lib")
find_package(Boost 1.88.0 REQUIRED COMPONENTS filesystem json log system filesystem url) if (WIN32)
set(Boost_INCLUDE_DIR ${BOOST_ROOT})
set(Boost_LIBRARY_DIR "${BOOST_ROOT}/stage/lib")
endif ()
find_package(Boost 1.88.0 REQUIRED COMPONENTS filesystem json log system url log_setup)
if (Boost_FOUND) if (Boost_FOUND)
include_directories(${Boost_INCLUDE_DIR}) include_directories(${Boost_INCLUDE_DIR})
endif () endif ()
@@ -23,53 +25,56 @@ find_package(mysql-concpp REQUIRED)
set(THREADS_PREFER_PTHREAD_FLAG ON) set(THREADS_PREFER_PTHREAD_FLAG ON)
find_package(Threads REQUIRED) find_package(Threads REQUIRED)
add_executable(App ./src/main.cpp add_executable(App
./src/helpers/helpers.h ${CMAKE_SOURCE_DIR}/src/main.cpp
./src/helpers/helpers.cpp ${CMAKE_SOURCE_DIR}/src/helpers/helpers.h
./src/endpoints_handlers/HandleRequest.h ${CMAKE_SOURCE_DIR}/src/helpers/helpers.cpp
./src/endpoints_handlers/IController.h ${CMAKE_SOURCE_DIR}/src/endpoints_handlers/HandleRequest.h
./src/endpoints_handlers/Controller.h ${CMAKE_SOURCE_DIR}/src/endpoints_handlers/IController.h
./src/session/HttpSession.h ${CMAKE_SOURCE_DIR}/src/endpoints_handlers/Controller.h
./src/session/HttpSession.cpp ${CMAKE_SOURCE_DIR}/src/session/HttpSession.h
./src/session/WebsocketSession.h ${CMAKE_SOURCE_DIR}/src/session/HttpSession.cpp
./src/session/WebsocketSession.cpp ${CMAKE_SOURCE_DIR}/src/session/WebsocketSession.h
./src/listener/Listener.h ${CMAKE_SOURCE_DIR}/src/session/WebsocketSession.cpp
./src/listener/Listener.cpp ${CMAKE_SOURCE_DIR}/src/listener/Listener.h
./src/db/mysql_connector.cpp ${CMAKE_SOURCE_DIR}/src/listener/Listener.cpp
./src/db/mysql_connector.h ${CMAKE_SOURCE_DIR}/src/db/mysql_connector.cpp
./src/DAO/IUserDAO.h ${CMAKE_SOURCE_DIR}/src/db/mysql_connector.h
src/dtos/user_dto.h ${CMAKE_SOURCE_DIR}/src/DAO/IUserDAO.h
src/dtos/medication_dto.h ${CMAKE_SOURCE_DIR}/src/dtos/user_dto.h
./src/DAO/MySQLUserDAO.cpp ${CMAKE_SOURCE_DIR}/src/dtos/medication_dto.h
./src/DAO/MySQLUserDAO.h ${CMAKE_SOURCE_DIR}/src/DAO/MySQLUserDAO.cpp
./src/endpoints_handlers/IExecutor.h ${CMAKE_SOURCE_DIR}/src/DAO/MySQLUserDAO.h
./src/endpoints_handlers/AuthRegistrationExecutor.h ${CMAKE_SOURCE_DIR}/src/endpoints_handlers/IExecutor.h
./src/endpoints_handlers/RootExecutor.h ${CMAKE_SOURCE_DIR}/src/endpoints_handlers/AuthRegistrationExecutor.h
./src/DAO/IAuthDAO.h ${CMAKE_SOURCE_DIR}/src/endpoints_handlers/RootExecutor.h
./src/DAO/MemoryAuthDAO.cpp ${CMAKE_SOURCE_DIR}/src/DAO/IAuthDAO.h
./src/DAO/MemoryAuthDAO.h ${CMAKE_SOURCE_DIR}/src/DAO/MemoryAuthDAO.cpp
./src/endpoints_handlers/AuthLogoutExecutor.h ${CMAKE_SOURCE_DIR}/src/DAO/MemoryAuthDAO.h
./src/endpoints_handlers/AuthLoginExecutor.h ${CMAKE_SOURCE_DIR}/src/endpoints_handlers/AuthLogoutExecutor.h
./src/exceptions/session_exception.cpp ${CMAKE_SOURCE_DIR}/src/endpoints_handlers/AuthLoginExecutor.h
./src/exceptions/session_exception.h ${CMAKE_SOURCE_DIR}/src/exceptions/session_exception.cpp
src/log/Log.h ${CMAKE_SOURCE_DIR}/src/exceptions/session_exception.h
src/log/Log.cpp ${CMAKE_SOURCE_DIR}/src/log/Log.h
tests/fixtures/AuthFixture.h ${CMAKE_SOURCE_DIR}/src/log/Log.cpp
src/endpoints_handlers/GetUserMedicationsExecutor.h ${CMAKE_SOURCE_DIR}/tests/fixtures/AuthFixture.h
src/DAO/IMedicationsDAO.h ${CMAKE_SOURCE_DIR}/src/endpoints_handlers/GetUserMedicationsExecutor.h
src/DAO/MySQLMedicationsDAO.h ${CMAKE_SOURCE_DIR}/src/DAO/IMedicationsDAO.h
src/DAO/MySQLMedicationsDAO.cpp ${CMAKE_SOURCE_DIR}/src/DAO/MySQLMedicationsDAO.h
src/dtos/user_treatment_scheme_dto.h ${CMAKE_SOURCE_DIR}/src/DAO/MySQLMedicationsDAO.cpp
src/DAO/IUserTreatmentSchemesDAO.h ${CMAKE_SOURCE_DIR}/src/dtos/user_treatment_scheme_dto.h
src/DAO/MySQLUserTreatmentSchemesDAO.cpp ${CMAKE_SOURCE_DIR}/src/DAO/IUserTreatmentSchemesDAO.h
src/DAO/MySQLUserTreatmentSchemesDAO.h ${CMAKE_SOURCE_DIR}/src/DAO/MySQLUserTreatmentSchemesDAO.cpp
src/endpoints_handlers/GetUserTreatmentSchemeExecutor.h ${CMAKE_SOURCE_DIR}/src/DAO/MySQLUserTreatmentSchemesDAO.h
src/endpoints_handlers/GetDiariesExecutor.h ${CMAKE_SOURCE_DIR}/src/endpoints_handlers/GetUserTreatmentSchemeExecutor.h
src/endpoints_handlers/PostDiaryExecutor.h ${CMAKE_SOURCE_DIR}/src/endpoints_handlers/GetDiariesExecutor.h
src/DAO/IDiariesDAO.h ${CMAKE_SOURCE_DIR}/src/endpoints_handlers/PostDiaryExecutor.h
src/dtos/diary_dto.h ${CMAKE_SOURCE_DIR}/src/endpoints_handlers/PutDiaryExecutor.h
src/DAO/MySQLDiariesDao.cpp ${CMAKE_SOURCE_DIR}/src/endpoints_handlers/DeleteDiaryExecutor.h
src/DAO/MySQLDiariesDao.h ${CMAKE_SOURCE_DIR}/src/DAO/IDiariesDAO.h
${CMAKE_SOURCE_DIR}/src/dtos/diary_dto.h
${CMAKE_SOURCE_DIR}/src/DAO/MySQLDiariesDAO.cpp
${CMAKE_SOURCE_DIR}/src/DAO/MySQLDiariesDAO.h
) )
target_link_libraries(App PRIVATE Boost::boost target_link_libraries(App PRIVATE Boost::boost
@@ -78,6 +83,7 @@ target_link_libraries(App PRIVATE Boost::boost
Boost::system Boost::system
Boost::filesystem Boost::filesystem
Boost::url Boost::url
Boost::log_setup
Threads::Threads Threads::Threads
mysql::concpp) mysql::concpp)
@@ -85,89 +91,97 @@ if (MSVC)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /bigobj")
endif () endif ()
add_executable(HelpersTests ./tests/helpers/helpers_TEST.cpp add_executable(HelpersTests
./src/helpers/helpers.h ${CMAKE_SOURCE_DIR}/tests/helpers/helpers_TEST.cpp
./src/helpers/helpers.cpp) ${CMAKE_SOURCE_DIR}/src/helpers/helpers.h
${CMAKE_SOURCE_DIR}/src/helpers/helpers.cpp)
target_link_libraries(HelpersTests PRIVATE Boost::boost Boost::json Boost::log) target_link_libraries(HelpersTests PRIVATE Boost::boost Boost::json Boost::log)
add_test(HelpersTests HelpersTests) add_test(HelpersTests HelpersTests)
add_executable(ControllerTests ./tests/endpoint_handlers/Controller_TEST.cpp add_executable(ControllerTests
./src/endpoints_handlers/IController.h ${CMAKE_SOURCE_DIR}/tests/endpoint_handlers/Controller_TEST.cpp
./src/endpoints_handlers/Controller.h) ${CMAKE_SOURCE_DIR}/src/endpoints_handlers/IController.h
${CMAKE_SOURCE_DIR}/src/endpoints_handlers/Controller.h)
target_link_libraries(ControllerTests PRIVATE Boost::boost) target_link_libraries(ControllerTests PRIVATE Boost::boost)
add_test(ControllerTests ControllerTests) add_test(ControllerTests ControllerTests)
add_executable(AuthRegistrationExecutorTests ./tests/endpoint_handlers/AuthRegistrationExecutor_TEST.cpp add_executable(AuthRegistrationExecutorTests
./src/endpoints_handlers/AuthRegistrationExecutor.h ${CMAKE_SOURCE_DIR}/tests/endpoint_handlers/AuthRegistrationExecutor_TEST.cpp
./src/exceptions/session_exception.cpp ${CMAKE_SOURCE_DIR}/src/endpoints_handlers/AuthRegistrationExecutor.h
./src/exceptions/session_exception.h ${CMAKE_SOURCE_DIR}/src/exceptions/session_exception.cpp
./src/helpers/helpers.h ${CMAKE_SOURCE_DIR}/src/exceptions/session_exception.h
./src/helpers/helpers.cpp ${CMAKE_SOURCE_DIR}/src/helpers/helpers.h
./src/DAO/MemoryAuthDAO.h ${CMAKE_SOURCE_DIR}/src/helpers/helpers.cpp
./src/DAO/MemoryAuthDAO.cpp ${CMAKE_SOURCE_DIR}/src/DAO/MemoryAuthDAO.h
./src/DAO/MySQLUserDAO.h ${CMAKE_SOURCE_DIR}/src/DAO/MemoryAuthDAO.cpp
./src/DAO/MySQLUserDAO.cpp ${CMAKE_SOURCE_DIR}/src/DAO/MySQLUserDAO.h
./src/db/mysql_connector.h ${CMAKE_SOURCE_DIR}/src/DAO/MySQLUserDAO.cpp
./src/db/mysql_connector.cpp ${CMAKE_SOURCE_DIR}/src/db/mysql_connector.h
tests/fixtures/AuthFixture.h ${CMAKE_SOURCE_DIR}/src/db/mysql_connector.cpp
tests/fixtures/AuthFixture.cpp ${CMAKE_SOURCE_DIR}/tests/fixtures/AuthFixture.h
./tests/fixtures/fixture_session_initialization_helper.h ${CMAKE_SOURCE_DIR}/tests/fixtures/AuthFixture.cpp
./tests/fixtures/fixture_session_initialization_helper.cpp) ${CMAKE_SOURCE_DIR}/tests/fixtures/fixture_session_initialization_helper.h
${CMAKE_SOURCE_DIR}/tests/fixtures/fixture_session_initialization_helper.cpp)
target_link_libraries(AuthRegistrationExecutorTests PRIVATE Boost::boost target_link_libraries(AuthRegistrationExecutorTests PRIVATE Boost::boost
Boost::json Boost::json
Boost::log Boost::log
Boost::system Boost::system
Boost::filesystem Boost::filesystem
Boost::log_setup
Threads::Threads Threads::Threads
mysql::concpp) mysql::concpp)
add_test(AuthRegistrationExecutorTests AuthRegistrationExecutorTests) add_test(AuthRegistrationExecutorTests AuthRegistrationExecutorTests)
add_executable(AuthLoginExecutorTests ./tests/endpoint_handlers/AuthLoginExecutor_TEST.cpp add_executable(AuthLoginExecutorTests
./src/endpoints_handlers/AuthRegistrationExecutor.h ${CMAKE_SOURCE_DIR}/tests/endpoint_handlers/AuthLoginExecutor_TEST.cpp
./src/exceptions/session_exception.cpp ${CMAKE_SOURCE_DIR}/src/endpoints_handlers/AuthRegistrationExecutor.h
./src/exceptions/session_exception.h ${CMAKE_SOURCE_DIR}/src/exceptions/session_exception.cpp
./src/helpers/helpers.h ${CMAKE_SOURCE_DIR}/src/exceptions/session_exception.h
./src/helpers/helpers.cpp ${CMAKE_SOURCE_DIR}/src/helpers/helpers.h
./src/DAO/MySQLUserDAO.h ${CMAKE_SOURCE_DIR}/src/helpers/helpers.cpp
./src/DAO/MySQLUserDAO.cpp ${CMAKE_SOURCE_DIR}/src/DAO/MySQLUserDAO.h
./src/DAO/MemoryAuthDAO.h ${CMAKE_SOURCE_DIR}/src/DAO/MySQLUserDAO.cpp
./src/DAO/MemoryAuthDAO.cpp ${CMAKE_SOURCE_DIR}/src/DAO/MemoryAuthDAO.h
./src/db/mysql_connector.h ${CMAKE_SOURCE_DIR}/src/DAO/MemoryAuthDAO.cpp
./src/db/mysql_connector.cpp ${CMAKE_SOURCE_DIR}/src/db/mysql_connector.h
tests/fixtures/AuthFixture.h ${CMAKE_SOURCE_DIR}/src/db/mysql_connector.cpp
tests/fixtures/AuthFixture.cpp ${CMAKE_SOURCE_DIR}/tests/fixtures/AuthFixture.h
./tests/fixtures/fixture_session_initialization_helper.h ${CMAKE_SOURCE_DIR}/tests/fixtures/AuthFixture.cpp
./tests/fixtures/fixture_session_initialization_helper.cpp) ${CMAKE_SOURCE_DIR}/tests/fixtures/fixture_session_initialization_helper.h
${CMAKE_SOURCE_DIR}/tests/fixtures/fixture_session_initialization_helper.cpp)
target_link_libraries(AuthLoginExecutorTests PRIVATE Boost::boost target_link_libraries(AuthLoginExecutorTests PRIVATE Boost::boost
Boost::json Boost::json
Boost::log Boost::log
Boost::system Boost::system
Boost::filesystem Boost::filesystem
Boost::log_setup
Threads::Threads Threads::Threads
mysql::concpp) mysql::concpp)
add_test(AuthLoginExecutorTests AuthLoginExecutorTests) add_test(AuthLoginExecutorTests AuthLoginExecutorTests)
add_executable(AuthLogoutExecutorTests ./tests/endpoint_handlers/AuthLogoutExecutor_TEST.cpp add_executable(AuthLogoutExecutorTests
./src/endpoints_handlers/AuthRegistrationExecutor.h ${CMAKE_SOURCE_DIR}/tests/endpoint_handlers/AuthLogoutExecutor_TEST.cpp
./src/exceptions/session_exception.cpp ${CMAKE_SOURCE_DIR}/src/endpoints_handlers/AuthRegistrationExecutor.h
./src/exceptions/session_exception.h ${CMAKE_SOURCE_DIR}/src/exceptions/session_exception.cpp
./src/helpers/helpers.h ${CMAKE_SOURCE_DIR}/src/exceptions/session_exception.h
./src/helpers/helpers.cpp ${CMAKE_SOURCE_DIR}/src/helpers/helpers.h
./src/DAO/MySQLUserDAO.h ${CMAKE_SOURCE_DIR}/src/helpers/helpers.cpp
./src/DAO/MySQLUserDAO.cpp ${CMAKE_SOURCE_DIR}/src/DAO/MySQLUserDAO.h
./src/DAO/MemoryAuthDAO.h ${CMAKE_SOURCE_DIR}/src/DAO/MySQLUserDAO.cpp
./src/DAO/MemoryAuthDAO.cpp ${CMAKE_SOURCE_DIR}/src/DAO/MemoryAuthDAO.h
./src/db/mysql_connector.h ${CMAKE_SOURCE_DIR}/src/DAO/MemoryAuthDAO.cpp
./src/db/mysql_connector.cpp ${CMAKE_SOURCE_DIR}/src/db/mysql_connector.h
./tests/fixtures/AuthFixture.h ${CMAKE_SOURCE_DIR}/src/db/mysql_connector.cpp
./tests/fixtures/AuthFixture.cpp ${CMAKE_SOURCE_DIR}/tests/fixtures/AuthFixture.h
./tests/fixtures/fixture_session_initialization_helper.h ${CMAKE_SOURCE_DIR}/tests/fixtures/AuthFixture.cpp
./tests/fixtures/fixture_session_initialization_helper.cpp) ${CMAKE_SOURCE_DIR}/tests/fixtures/fixture_session_initialization_helper.h
${CMAKE_SOURCE_DIR}/tests/fixtures/fixture_session_initialization_helper.cpp)
target_link_libraries(AuthLogoutExecutorTests PRIVATE Boost::boost target_link_libraries(AuthLogoutExecutorTests PRIVATE Boost::boost
Boost::json Boost::json
Boost::log Boost::log
Boost::system Boost::system
Boost::filesystem Boost::filesystem
Boost::log_setup
Threads::Threads Threads::Threads
mysql::concpp) mysql::concpp)
add_test(AuthLogoutExecutorTests AuthLogoutExecutorTests) add_test(AuthLogoutExecutorTests AuthLogoutExecutorTests)
+52
View File
@@ -0,0 +1,52 @@
FROM ubuntu:24.04
ARG CONCPP_VER=9.4.0
ARG CONCPP_TGZ=mysql-connector-c++-${CONCPP_VER}-linux-glibc2.28-x86-64bit.tar.gz
RUN apt-get update && apt-get install -y --no-install-recommends \
ca-certificates curl xz-utils \
&& rm -rf /var/lib/apt/lists/*
# MySQL xDevAPI install
RUN curl -fsSL -o concpp.tgz \
"https://dev.mysql.com/get/Downloads/Connector-C++/${CONCPP_TGZ}" \
&& mkdir -p /opt \
&& tar -xzf concpp.tgz -C /opt \
&& rm concpp.tgz \
&& found_dir="$(ls -1 /opt | grep -E '^mysql-connector-c\+\+-'"${CONCPP_VER}"'-')" \
&& mv "/opt/${found_dir}" /opt/mysql-concpp
# CMake install
RUN apt-get update && apt-get install -y --no-install-recommends \
cmake build-essential \
&& rm -rf /var/lib/apt/lists/*
# Boost install
RUN curl -L --retry 5 --retry-all-errors -o /tmp/boost.tar.gz "https://archives.boost.io/release/1.88.0/source/boost_1_88_0.tar.gz" \
&& ls -lh /tmp/boost.tar.gz \
&& tar -tzf /tmp/boost.tar.gz >/dev/null
RUN mkdir -p /tmp/boost-src \
&& tar -xzf /tmp/boost.tar.gz -C /tmp/boost-src --strip-components=1 \
&& cd /tmp/boost-src \
&& ./bootstrap.sh --prefix=/usr/local
RUN cd /tmp/boost-src \
&& ./b2 -j"$(nproc)" install
ENV LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH
# Project copy
WORKDIR /project
# COPY . /project
EXPOSE 8080
# Build & Run project
CMD ["bash", "-lc", "\
set -euo pipefail; \
test -f /project/CMakeLists.txt; \
mkdir -p /project/dist; \
cmake -S /project -B /project/dist -Dmysql-concpp_DIR=/opt/mysql-concpp; \
cmake --build /project/dist -j\"$(nproc)\"; \
exec /project/dist/App 0.0.0.0 8080 . 12 mysqlx://root:root@host.docker.internal:33060 \
"]
+21 -8
View File
@@ -1,3 +1,11 @@
# Запуск(Без Docker):
- cmake .. -DBOOST_ROOT=C:\Libs\boost_1_88_0 -Dmysql-concpp_DIR=C:\Libs\mysql_connector
- cmake --build .
# Запуск(С Docker):
- $env:DOCKER_BUILDKIT=1; docker build --progress=plain -t up_and_down .
- docker run --rm -v //c/CLionProjects/UpAndDown:/project -p 8080:8080 up_and_down
# TODO: # TODO:
- ~~Сделать реальные исполнители(executors) для регистрации, авторизации, логаута~~ - ~~Сделать реальные исполнители(executors) для регистрации, авторизации, логаута~~
@@ -21,17 +29,22 @@
- Посмотреть пулл соединений(Object pool) при использовании базы данных(посмотреть api MySQL-Connector) - Посмотреть пулл соединений(Object pool) при использовании базы данных(посмотреть api MySQL-Connector)
- Посмотреть и подумать, что лучше - корутины или многопоточность? - Посмотреть и подумать, что лучше - корутины или многопоточность?
- UseCase'ы по работе с личным кабинетом - UseCase'ы по работе с личным кабинетом
- Научиться поднимать базы данных под каждый тест - научиться Docker - docker-compose - а если тест что-то должен заполнить, то он заполняет в самом начале()
- Возможно, сделать тесты на CI/CD - приоритет - низкий
- Найти слабые места в C++ -- std::forward, universal reference, просмотреть про decltype(почитать статьи) - Найти слабые места в C++ -- std::forward, universal reference, просмотреть про decltype(почитать статьи)
- Написать фронтенд для MVP - ~~Разобрать decltype и auto по статье~~
- Разобрать decltype и auto по статье - Подготовить резюме для тестовых собесов
- DockerHosting.ru - купить аренду после того, как будет готов фронт и бэк
До 27.01.2026 До 27.01.2026
- Подобрать сервер по параметрам. Использовать linux. - ~~Подобрать сервер по параметрам. Использовать linux.~~
- Перевести string на string_view - ~~Перевести string на string_view~~
- ~~Попробовать nodiscard к executoru~~ - ~~Попробовать nodiscard к executoru~~
- Добить 2 ручки - ~~Добить 2 ручки~~
- Сделать тесты для ручек До 10.02.2026
- Сделать 2-3 теста
- Продвинуться по фронтенду(форма авторизации и логина)
- Сделать Dockerfile & Docker-compose(очищать и заполнять базу после каждого тест-кейса)
- Возможно, сделать тесты на CI/CD - приоритет - низкий
- Научиться поднимать базы данных под каждый тест - научиться Docker - docker-compose - а если тест что-то должен заполнить, то он заполняет в самом начале
- Проставить const на немутабельные объекты
# План # План
1)Добить бэкенд(2 ручки) (до февраля) 1)Добить бэкенд(2 ручки) (до февраля)
+5 -5
View File
@@ -11,14 +11,14 @@ class IAuthDAO
{ {
public: public:
virtual std::string Login( virtual std::string Login(
const std::string& registrated_user_uuid, std::string_view registrated_user_uuid,
const std::string& auth_token) = 0; std::string_view auth_token) = 0;
virtual bool HasAuthorized(const std::string& auth_token) = 0; virtual bool HasAuthorized(std::string_view auth_token) = 0;
virtual std::string_view GetUUID(const std::string& auth_token) = 0; virtual std::string_view GetUUID(std::string_view auth_token) = 0;
virtual bool Logout(const std::string& user_token) = 0; virtual bool Logout(std::string_view user_token) = 0;
virtual ~IAuthDAO() = default; virtual ~IAuthDAO() = default;
}; };
+13 -2
View File
@@ -10,13 +10,24 @@ namespace uad
class IDiariesDAO class IDiariesDAO
{ {
public: public:
virtual std::vector<diary_dto> GetDiariesByUserUUID(const std::string& login) = 0; virtual std::vector<diary_dto> GetDiariesByUserUUID(std::string_view login) = 0;
virtual void СreateDiary( virtual void СreateDiary(
const std::string& user_uuid, std::string_view user_uuid,
const diary_dto& dto const diary_dto& dto
) const = 0; ) const = 0;
virtual void UpdateDiary(
std::string_view user_uuid,
std::string_view diary_uuid,
const diary_dto& dto
) const = 0;
virtual void DeleteDiary(
std::string_view user_uuid,
std::string_view diary_uuid
) const = 0;
virtual ~IDiariesDAO() = default; virtual ~IDiariesDAO() = default;
}; };
} }
+3 -3
View File
@@ -13,15 +13,15 @@ class IUserDAO
public: public:
virtual std::string Create(const user_dto& created_user) = 0; virtual std::string Create(const user_dto& created_user) = 0;
virtual std::optional<user_dto> GetByUUID(const std::string& uuid) = 0; virtual std::optional<user_dto> GetByUUID(std::string_view uuid) = 0;
virtual std::optional<user_dto> GetByLogin(const std::string& login) = 0; virtual std::optional<user_dto> GetByLogin(std::string_view login) = 0;
virtual std::pair<bool, std::vector<user_dto>> GetAll(size_t limit, size_t offset) = 0; virtual std::pair<bool, std::vector<user_dto>> GetAll(size_t limit, size_t offset) = 0;
virtual bool Update(const user_dto& u) = 0; virtual bool Update(const user_dto& u) = 0;
virtual bool Delete(const std::string& uuid) = 0; virtual bool Delete(std::string_view uuid) = 0;
virtual ~IUserDAO() = default; virtual ~IUserDAO() = default;
}; };
+2 -2
View File
@@ -8,10 +8,10 @@ namespace uad
{ {
class IUserTreatmentSchemeDAO { class IUserTreatmentSchemeDAO {
public: public:
virtual std::vector<user_treatment_scheme_dto> FindByUserUUID(const std::string& login) = 0; virtual std::vector<user_treatment_scheme_dto> FindByUserUUID(std::string_view login) = 0;
virtual void CreateUserTreatmentScheme( virtual void CreateUserTreatmentScheme(
const std::string& user_login, std::string_view user_login,
const user_treatment_scheme_dto& dto const user_treatment_scheme_dto& dto
) = 0; ) = 0;
+12 -12
View File
@@ -11,33 +11,33 @@ MemoryAuthDAO::MemoryAuthDAO(mysqlx::Session& session): session_(session)
} }
std::string MemoryAuthDAO::Login( std::string MemoryAuthDAO::Login(
const std::string& registrated_user_uuid, std::string_view registrated_user_uuid,
const std::string& auth_token) std::string_view auth_token)
{ {
users_uuids_to_auth_tokens_[registrated_user_uuid] = auth_token; users_uuids_to_auth_tokens_[registrated_user_uuid.data()] = auth_token;
auth_tokens_to_users_uuids_[auth_token] = registrated_user_uuid; auth_tokens_to_users_uuids_[auth_token.data()] = registrated_user_uuid;
return auth_token; return auth_token.data();
} }
bool MemoryAuthDAO::HasAuthorized(const std::string& auth_token) bool MemoryAuthDAO::HasAuthorized(std::string_view auth_token)
{ {
return auth_tokens_to_users_uuids_.count(auth_token) > 0; return auth_tokens_to_users_uuids_.count(auth_token.data()) > 0;
} }
std::string_view MemoryAuthDAO::GetUUID(const std::string& auth_token) std::string_view MemoryAuthDAO::GetUUID(std::string_view auth_token)
{ {
return auth_tokens_to_users_uuids_.at(auth_token); return auth_tokens_to_users_uuids_.at(auth_token.data());
} }
bool MemoryAuthDAO::Logout(const std::string& auth_token) bool MemoryAuthDAO::Logout(std::string_view auth_token)
{ {
if (!HasAuthorized(auth_token)) return false; if (!HasAuthorized(auth_token)) return false;
string user_uuid = auth_tokens_to_users_uuids_[auth_token]; string user_uuid = auth_tokens_to_users_uuids_[auth_token.data()];
users_uuids_to_auth_tokens_.erase(user_uuid); users_uuids_to_auth_tokens_.erase(user_uuid);
auth_tokens_to_users_uuids_.erase(auth_token); auth_tokens_to_users_uuids_.erase(auth_token.data());
return true; return true;
} }
+5 -5
View File
@@ -20,13 +20,13 @@ public:
explicit MemoryAuthDAO(mysqlx::Session& session); explicit MemoryAuthDAO(mysqlx::Session& session);
std::string Login( std::string Login(
const std::string& registrated_user_uuid, std::string_view registrated_user_uuid,
const std::string& auth_token) override; std::string_view auth_token) override;
bool HasAuthorized(const std::string& auth_token) override; bool HasAuthorized(std::string_view auth_token) override;
std::string_view GetUUID(const std::string& auth_token) override; std::string_view GetUUID(std::string_view auth_token) override;
bool Logout(const std::string& auth_token) override; bool Logout(std::string_view auth_token) override;
}; };
} }
+64 -4
View File
@@ -1,12 +1,14 @@
#include "MySQLDiariesDAO.h" #include "MySQLDiariesDAO.h"
#include "../exceptions/session_exception.h"
namespace uad namespace uad
{ {
MySqlDiariesDAO::MySqlDiariesDAO(mysqlx::Session& session) : session_(session) MySqlDiariesDAO::MySqlDiariesDAO(mysqlx::Session& session) : session_(session)
{ {
} }
std::vector<diary_dto> MySqlDiariesDAO::GetDiariesByUserUUID(const std::string& user_uuid) std::vector<diary_dto> MySqlDiariesDAO::GetDiariesByUserUUID(std::string_view user_uuid)
{ {
static const std::string query = R"( static const std::string query = R"(
SELECT SELECT
@@ -28,7 +30,7 @@ std::vector<diary_dto> MySqlDiariesDAO::GetDiariesByUserUUID(const std::string&
mysqlx::SqlResult result = session_ mysqlx::SqlResult result = session_
.sql(query) .sql(query)
.bind(user_uuid) .bind(user_uuid.data())
.execute(); .execute();
std::vector<diary_dto> diaries; std::vector<diary_dto> diaries;
@@ -58,7 +60,7 @@ std::vector<diary_dto> MySqlDiariesDAO::GetDiariesByUserUUID(const std::string&
return diaries; return diaries;
} }
void MySqlDiariesDAO::СreateDiary(const std::string& user_uuid, const diary_dto& dto) const void MySqlDiariesDAO::СreateDiary(std::string_view user_uuid, const diary_dto& dto) const
{ {
auto stmt = session_.sql(R"( auto stmt = session_.sql(R"(
INSERT INTO `up_and_down`.`diaries` ( INSERT INTO `up_and_down`.`diaries` (
@@ -92,7 +94,7 @@ void MySqlDiariesDAO::СreateDiary(const std::string& user_uuid, const diary_dto
stmt.bind( stmt.bind(
dto.uuid, dto.uuid,
user_uuid, user_uuid.data(),
dto.time_ms, dto.time_ms,
dto.mania_level, dto.mania_level,
dto.depression_level, dto.depression_level,
@@ -107,4 +109,62 @@ void MySqlDiariesDAO::СreateDiary(const std::string& user_uuid, const diary_dto
stmt.execute(); stmt.execute();
} }
void MySqlDiariesDAO::UpdateDiary(
std::string_view user_uuid,
std::string_view diary_uuid,
const diary_dto& dto) const
{
auto stmt = session_.sql(R"(
UPDATE `up_and_down`.`diaries`
SET
mania_level = ?,
depression_level = ?,
mood_level = ?,
activity_level = ?,
appetite_level = ?,
dream_level = ?,
anxiety_level = ?,
comment = ?,
user_treatment_schemes_uuid = ?
WHERE uuid = ?
)");
stmt.bind(
dto.mania_level,
dto.depression_level,
dto.mood_level,
dto.activity_level,
dto.appetite_level,
dto.dream_level,
dto.anxiety_level,
dto.comment,
dto.user_treatment_scheme_uuid,
diary_uuid.data()
);
const auto res = stmt.execute();
if (res.getAffectedItemsCount() == 0) {
throw session_exception(boost::beast::http::status::not_found, "Diary not found");
}
}
void MySqlDiariesDAO::DeleteDiary(
std::string_view user_uuid,
std::string_view diary_uuid) const
{
auto stmt = session_.sql(R"(
DELETE FROM `up_and_down`.`diaries`
WHERE uuid = ? AND user_uuid = ?
)");
stmt.bind(diary_uuid.data(), user_uuid.data());
auto res = stmt.execute();
if (res.getAffectedItemsCount() == 0) {
throw session_exception(boost::beast::http::status::not_found, "Diary not found");
}
}
} }
+14 -3
View File
@@ -3,7 +3,7 @@
#include <vector> #include <vector>
#include <string> #include <string>
#include "./../DAO/IDiariesDao.h" #include "./../DAO/IDiariesDAO.h"
#include "./../db/mysql_connector.h" #include "./../db/mysql_connector.h"
namespace uad namespace uad
@@ -15,11 +15,22 @@ class MySqlDiariesDAO final : public IDiariesDAO
public: public:
explicit MySqlDiariesDAO(mysqlx::Session& session); explicit MySqlDiariesDAO(mysqlx::Session& session);
std::vector<diary_dto> GetDiariesByUserUUID(const std::string& user_uuid) override; std::vector<diary_dto> GetDiariesByUserUUID(std::string_view user_uuid) override;
void СreateDiary( void СreateDiary(
const std::string& user_uuid, std::string_view user_uuid,
const diary_dto& dto const diary_dto& dto
) const override; ) const override;
void UpdateDiary(
std::string_view user_uuid,
std::string_view diary_uuid,
const diary_dto& dto
) const override;
void DeleteDiary(
std::string_view user_uuid,
std::string_view diary_uuid
) const override;
}; };
} }
+8 -8
View File
@@ -31,23 +31,23 @@ string MySQLUserDAO::Create(const user_dto& created_user)
return uuid_str; return uuid_str;
} }
optional<user_dto> MySQLUserDAO::GetByUUID(const string& uuid) optional<user_dto> MySQLUserDAO::GetByUUID(std::string_view uuid)
{ {
static const string sql_script = "SELECT * FROM `up_and_down`.`users` WHERE (uuid = ?) LIMIT 1;"s; static const string sql_script = "SELECT * FROM `up_and_down`.`users` WHERE (uuid = ?) LIMIT 1;"s;
mysqlx::SqlResult sql_result = session_. mysqlx::SqlResult sql_result = session_.
sql(sql_script) sql(sql_script)
.bind(uuid) .bind(uuid.data())
.execute(); .execute();
return GetSingleUserBySQLResult(std::move(sql_result)); return GetSingleUserBySQLResult(std::move(sql_result));
} }
optional<user_dto> MySQLUserDAO::GetByLogin(const string& login) optional<user_dto> MySQLUserDAO::GetByLogin(std::string_view login)
{ {
static const std::string sql_script = "SELECT * FROM `up_and_down`.`users` WHERE (login = ?) LIMIT 1;"s; static const std::string sql_script = "SELECT * FROM `up_and_down`.`users` WHERE (login = ?) LIMIT 1;"s;
mysqlx::SqlResult sql_result = session_. mysqlx::SqlResult sql_result = session_
sql(sql_script) .sql(sql_script)
.bind(login) .bind(login.data())
.execute(); .execute();
return GetSingleUserBySQLResult(std::move(sql_result)); return GetSingleUserBySQLResult(std::move(sql_result));
@@ -107,12 +107,12 @@ bool MySQLUserDAO::Update(const user_dto& u)
return !!schema.getAffectedItemsCount(); return !!schema.getAffectedItemsCount();
} }
bool MySQLUserDAO::Delete(const string& uuid) bool MySQLUserDAO::Delete(std::string_view uuid)
{ {
static const string sql_script = "DELETE FROM `up_and_down`.`users` WHERE `uuid` = ?;"; static const string sql_script = "DELETE FROM `up_and_down`.`users` WHERE `uuid` = ?;";
auto schema = session_.sql(sql_script) auto schema = session_.sql(sql_script)
.bind(uuid) .bind(uuid.data())
.execute(); .execute();
return !!schema.getAffectedItemsCount(); return !!schema.getAffectedItemsCount();
+3 -3
View File
@@ -13,15 +13,15 @@ public:
std::string Create(const user_dto& created_user) override; std::string Create(const user_dto& created_user) override;
std::optional<user_dto> GetByUUID(const std::string& uuid) override; std::optional<user_dto> GetByUUID(std::string_view uuid) override;
std::optional<user_dto> GetByLogin(const std::string& login) override; std::optional<user_dto> GetByLogin(std::string_view login) override;
std::pair<bool, std::vector<user_dto>> GetAll(size_t limit, size_t offset) override; std::pair<bool, std::vector<user_dto>> GetAll(size_t limit, size_t offset) override;
bool Update(const user_dto& u) override; bool Update(const user_dto& u) override;
bool Delete(const std::string& uuid) override; bool Delete(std::string_view uuid) override;
private: private:
std::optional<user_dto> GetSingleUserBySQLResult(mysqlx::SqlResult&& sql_result); std::optional<user_dto> GetSingleUserBySQLResult(mysqlx::SqlResult&& sql_result);
+4 -4
View File
@@ -11,7 +11,7 @@ MySQLUserTreatmentSchemesDAO::MySQLUserTreatmentSchemesDAO(mysqlx::Session& sess
} }
std::vector<user_treatment_scheme_dto> MySQLUserTreatmentSchemesDAO::FindByUserUUID( std::vector<user_treatment_scheme_dto> MySQLUserTreatmentSchemesDAO::FindByUserUUID(
const std::string& user_uuid) std::string_view user_uuid)
{ {
static const std::string query = R"( static const std::string query = R"(
SELECT SELECT
@@ -30,7 +30,7 @@ std::vector<user_treatment_scheme_dto> MySQLUserTreatmentSchemesDAO::FindByUserU
mysqlx::SqlResult result = session_ mysqlx::SqlResult result = session_
.sql(query) .sql(query)
.bind(user_uuid) .bind(user_uuid.data())
.execute(); .execute();
std::unordered_map<std::string, user_treatment_scheme_dto> scheme_map; std::unordered_map<std::string, user_treatment_scheme_dto> scheme_map;
@@ -69,7 +69,7 @@ std::vector<user_treatment_scheme_dto> MySQLUserTreatmentSchemesDAO::FindByUserU
} }
void MySQLUserTreatmentSchemesDAO::CreateUserTreatmentScheme( void MySQLUserTreatmentSchemesDAO::CreateUserTreatmentScheme(
const std::string& user_uuid, std::string_view user_uuid,
const user_treatment_scheme_dto& dto) const user_treatment_scheme_dto& dto)
{ {
session_.startTransaction(); session_.startTransaction();
@@ -85,7 +85,7 @@ void MySQLUserTreatmentSchemesDAO::CreateUserTreatmentScheme(
)") )")
.bind( .bind(
dto.uuid, dto.uuid,
user_uuid, user_uuid.data(),
dto.treatment_name, dto.treatment_name,
dto.instructions dto.instructions
) )
+2 -2
View File
@@ -11,10 +11,10 @@ class MySQLUserTreatmentSchemesDAO : public IUserTreatmentSchemeDAO
public: public:
explicit MySQLUserTreatmentSchemesDAO(mysqlx::Session& session); explicit MySQLUserTreatmentSchemesDAO(mysqlx::Session& session);
std::vector<user_treatment_scheme_dto> FindByUserUUID(const std::string& uuid) override; std::vector<user_treatment_scheme_dto> FindByUserUUID(std::string_view uuid) override;
void CreateUserTreatmentScheme( void CreateUserTreatmentScheme(
const std::string& user_login, std::string_view user_login,
const user_treatment_scheme_dto& dto const user_treatment_scheme_dto& dto
) override; ) override;
}; };
@@ -97,16 +97,16 @@ public:
} }
private: private:
bool ValidateLogin(const std::string& login) bool ValidateLogin(std::string_view login)
{ {
if (login.size() < 3 || login.size() > 50) return false; if (login.size() < 3 || login.size() > 50) return false;
std::regex pattern(std::string("^[A-Za-z0-9_]+$")); std::regex pattern(std::string("^[A-Za-z0-9_]+$"));
return std::regex_match(login, pattern); return std::regex_match(login.data(), pattern);
} }
bool ValidatePassword(const std::string& password) bool ValidatePassword(std::string_view password)
{ {
return password.size() >= 5; return password.size() >= 5;
} }
@@ -0,0 +1,79 @@
#pragma once
#include <boost/log/trivial.hpp>
#include <regex>
#include <boost/json.hpp>
#include <boost/mpl/vector/vector0.hpp>
#include <mysqlx/xdevapi.h>
#include "IExecutor.h"
#include "../DAO/IAuthDAO.h"
#include "../DAO/IDiariesDAO.h"
#include "../exceptions/session_exception.h"
namespace uad
{
template <class Body, class Allocator, class ResponseType>
class DeleteDiaryExecutor
{
mysqlx::Session& session_;
const std::shared_ptr<IAuthDAO>& auth_dao_;
const std::shared_ptr<IDiariesDAO>& diaries_dao_;
public:
DeleteDiaryExecutor(
mysqlx::Session& session,
const std::shared_ptr<IAuthDAO>& auth_dao,
const std::shared_ptr<IDiariesDAO>& diaries_dao
) : session_(session), auth_dao_(auth_dao), diaries_dao_(diaries_dao)
{
}
[[nodiscard]] boost::beast::http::response<ResponseType> operator ()(
boost::beast::http::request<Body, boost::beast::http::basic_fields<Allocator>>&& req,
std::string diary_uuid
)
{
using namespace boost;
using namespace boost::json;
using namespace boost::beast;
using namespace std::string_literals;
using namespace std::string_view_literals;
constexpr std::string_view auth_prefix = "Bearer "sv;
static const std::string invalid_token_message =
"DELETE /api/v1/Diary - Response 401: Unauthorized"s;
BOOST_LOG_TRIVIAL(info) << "DELETE /api/v1/Diary - Request";
if (req[http::field::authorization].size() <= auth_prefix.size())
{
BOOST_LOG_TRIVIAL(error) << invalid_token_message;
throw session_exception(http::status::unauthorized, "Unauthorized");
}
const std::string auth_token = {
req[http::field::authorization].begin() + auth_prefix.size(),
req[http::field::authorization].end()
};
if (!auth_dao_->HasAuthorized(auth_token))
{
BOOST_LOG_TRIVIAL(error) << invalid_token_message;
throw session_exception(http::status::unauthorized, "Unauthorized");
}
std::string_view user_uuid_ref = auth_dao_->GetUUID(auth_token);
const std::string user_uuid{user_uuid_ref.begin(), user_uuid_ref.end()};
diaries_dao_->DeleteDiary(user_uuid, diary_uuid);
http::response<ResponseType> res{http::status::no_content, req.version()};
res.keep_alive(req.keep_alive());
BOOST_LOG_TRIVIAL(info) << "DELETE /api/v1/Diary - Response 204: Diary deleted";
return res;
}
};
}
+4 -8
View File
@@ -71,7 +71,7 @@ public:
diary_dto dto; diary_dto dto;
dto.uuid = obj["uuid"].as_string().c_str(); dto.uuid = GenerateUUID();
dto.time_ms = obj["time_ms"].as_int64(); dto.time_ms = obj["time_ms"].as_int64();
dto.mania_level = obj["mania_level"].as_int64(); dto.mania_level = obj["mania_level"].as_int64();
dto.depression_level = obj["depression_level"].as_int64(); dto.depression_level = obj["depression_level"].as_int64();
@@ -80,13 +80,9 @@ public:
dto.appetite_level = obj["appetite_level"].as_int64(); dto.appetite_level = obj["appetite_level"].as_int64();
dto.dream_level = obj["dream_level"].as_int64(); dto.dream_level = obj["dream_level"].as_int64();
dto.anxiety_level = obj["anxiety_level"].as_int64(); dto.anxiety_level = obj["anxiety_level"].as_int64();
dto.comment = obj["comment"].as_string().c_str();
if (obj.contains("comment")) dto.user_treatment_scheme_uuid =
dto.comment = obj["comment"].as_string().c_str(); obj["user_treatment_scheme_uuid"].as_string().c_str();
if (obj.contains("user_treatment_scheme_uuid"))
dto.user_treatment_scheme_uuid =
obj["user_treatment_scheme_uuid"].as_string().c_str();
try try
{ {
+119
View File
@@ -0,0 +1,119 @@
#pragma once
#include <boost/log/trivial.hpp>
#include <regex>
#include <boost/json.hpp>
#include <boost/mpl/vector/vector0.hpp>
#include <mysqlx/xdevapi.h>
#include "IExecutor.h"
#include "../DAO/IAuthDAO.h"
#include "../DAO/IDiariesDAO.h"
#include "../DAO/IUserTreatmentSchemesDAO.h"
#include "../exceptions/session_exception.h"
namespace uad
{
template <class Body, class Allocator, class ResponseType>
class PutDiaryExecutor
{
mysqlx::Session& session_;
const std::shared_ptr<IAuthDAO>& auth_dao_;
const std::shared_ptr<IDiariesDAO>& diaries_dao_;
public:
PutDiaryExecutor(
mysqlx::Session& session,
const std::shared_ptr<IAuthDAO>& auth_dao,
const std::shared_ptr<IDiariesDAO>& diaries_dao
) : session_(session), auth_dao_(auth_dao), diaries_dao_(diaries_dao)
{
}
[[nodiscard]] boost::beast::http::response<ResponseType> operator ()(
boost::beast::http::request<Body, boost::beast::http::basic_fields<Allocator>>&& req,
std::string diary_uuid
)
{
using namespace boost;
using namespace boost::json;
using namespace boost::beast;
using namespace std::string_literals;
using namespace std::string_view_literals;
constexpr std::string_view auth_prefix = "Bearer "sv;
static const std::string invalid_token_message =
"PUT /api/v1/Diary - Response 401: Unauthorized"s;
BOOST_LOG_TRIVIAL(info) << "PUT /api/v1/Diary - Request";
if (req[http::field::authorization].size() <= auth_prefix.size())
{
BOOST_LOG_TRIVIAL(error) << invalid_token_message;
throw session_exception(http::status::unauthorized, "Unauthorized");
}
const std::string auth_token = {
req[http::field::authorization].begin() + auth_prefix.size(),
req[http::field::authorization].end()
};
if (!auth_dao_->HasAuthorized(auth_token))
{
BOOST_LOG_TRIVIAL(error) << invalid_token_message;
throw session_exception(http::status::unauthorized, "Unauthorized");
}
std::string_view user_uuid_ref = auth_dao_->GetUUID(auth_token);
const std::string user_uuid{user_uuid_ref.begin(), user_uuid_ref.end()};
value val = json::parse(req.body());
object& obj = val.as_object();
diary_dto dto;
dto.uuid = diary_uuid;
dto.mania_level = obj["mania_level"].as_int64();
dto.depression_level = obj["depression_level"].as_int64();
dto.mood_level = obj["mood_level"].as_int64();
dto.activity_level = obj["activity_level"].as_int64();
dto.appetite_level = obj["appetite_level"].as_int64();
dto.dream_level = obj["dream_level"].as_int64();
dto.anxiety_level = obj["anxiety_level"].as_int64();
dto.comment = obj["comment"].as_string().c_str();
dto.user_treatment_scheme_uuid = obj["user_treatment_scheme_uuid"].as_string().c_str();
diaries_dao_->UpdateDiary(user_uuid, diary_uuid, dto);
http::response<ResponseType> res{http::status::ok, req.version()};
value response_body = ToJSON(dto);
res.body() = serialize(response_body);
res.set(http::field::content_type, "application/json");
res.content_length(res.body().size());
return res;
}
private:
boost::json::object ToJSON(const diary_dto& diary)
{
boost::json::object diary_json;
diary_json["uuid"] = diary.uuid;
diary_json["time"] = diary.time_ms;
diary_json["mania_level"] = diary.mania_level;
diary_json["depression_level"] = diary.depression_level;
diary_json["mood_level"] = diary.mood_level;
diary_json["activity_level"] = diary.activity_level;
diary_json["appetite_level"] = diary.appetite_level;
diary_json["dream_level"] = diary.dream_level;
diary_json["anxiety_level"] = diary.anxiety_level;
diary_json["comment"] = diary.comment;
diary_json["user_treatment_scheme_uuid"] =
diary.user_treatment_scheme_uuid;
return diary_json;
}
};
}
+33 -7
View File
@@ -16,6 +16,8 @@
#include "PostUserMedicationsExecutor.h" #include "PostUserMedicationsExecutor.h"
#include "GetDiariesExecutor.h" #include "GetDiariesExecutor.h"
#include "PostDiaryExecutor.h" #include "PostDiaryExecutor.h"
#include "PutDiaryExecutor.h"
#include "DeleteDiaryExecutor.h"
#include "../DAO/IUserDAO.h" #include "../DAO/IUserDAO.h"
#include "../DAO/IAuthDAO.h" #include "../DAO/IAuthDAO.h"
#include "../DAO/IDiariesDAO.h" #include "../DAO/IDiariesDAO.h"
@@ -48,6 +50,11 @@ class RootExecutor
Body, Allocator, boost::beast::http::string_body>; Body, Allocator, boost::beast::http::string_body>;
using RoutePostDiaryExecutor = PostDiaryExecutor< using RoutePostDiaryExecutor = PostDiaryExecutor<
Body, Allocator, boost::beast::http::string_body>; Body, Allocator, boost::beast::http::string_body>;
using RoutePutDiaryExecutor = PutDiaryExecutor<
Body, Allocator, boost::beast::http::string_body>;
using RouteDeleteDiaryExecutor = DeleteDiaryExecutor<
Body, Allocator, boost::beast::http::string_body>;
using IRouteController = IController<Body, Allocator, boost::beast::http::string_body>; using IRouteController = IController<Body, Allocator, boost::beast::http::string_body>;
using RouteController = Controller<Body, Allocator, boost::beast::http::string_body>; using RouteController = Controller<Body, Allocator, boost::beast::http::string_body>;
using RoutesPathes = std::unordered_map<std::string, std::unique_ptr<IRouteController>>; using RoutesPathes = std::unordered_map<std::string, std::unique_ptr<IRouteController>>;
@@ -162,13 +169,12 @@ public:
{ {
namespace urls = boost::urls; namespace urls = boost::urls;
const std::string& route = req.target(); const bool is_match_route = routes_pathes_.count(req.target());
const bool is_match_route = routes_pathes_.count(route);
if (is_match_route) if (is_match_route)
{ {
std::optional<std::shared_ptr<IRouteExecutor>> maybe_executor_ptr = routes_pathes_ std::optional<std::shared_ptr<IRouteExecutor>> maybe_executor_ptr = routes_pathes_
.at(route) .at(req.target())
->FindExecutor(req.method()); ->FindExecutor(req.method());
if (maybe_executor_ptr.has_value()) if (maybe_executor_ptr.has_value())
@@ -188,7 +194,7 @@ public:
} }
} }
urls::url_view parsed_view = urls::parse_uri_reference(route).value(); urls::url_view parsed_view = urls::parse_uri_reference(req.target()).value();
auto segs = parsed_view.segments(); auto segs = parsed_view.segments();
std::vector<std::string> parts; std::vector<std::string> parts;
@@ -199,11 +205,31 @@ public:
parts[0] == "api" && parts[0] == "api" &&
parts[2] == "Diaries") parts[2] == "Diaries")
{ {
std::string uuid = std::string(parts[3]); try
if (req.method() == boost::beast::http::verb::put)
{ {
std::string uuid = std::string(parts[3]);
if (req.method() == boost::beast::http::verb::put)
{
return send(RoutePutDiaryExecutor(
session_,
auth_dao_,
diaries_dao_
)(std::move(req), uuid));
}
if (req.method() == boost::beast::http::verb::delete_)
{
return send(RouteDeleteDiaryExecutor(
session_,
auth_dao_,
diaries_dao_
)(std::move(req), uuid));
}
}
catch (const session_exception& e)
{
return send(SendSessionExceptionError(std::move(req), e));
} }
} }
+1 -1
View File
@@ -4,7 +4,7 @@ using namespace std;
namespace uad namespace uad
{ {
char const* session_exception::what() const char const* session_exception::what() const noexcept
{ {
return message.c_str(); return message.c_str();
} }
+1 -1
View File
@@ -15,6 +15,6 @@ struct session_exception : std::exception
session_exception(const boost::beast::http::status ec, const std::string info) session_exception(const boost::beast::http::status ec, const std::string info)
: code(ec), comment(info), message(std::to_string(static_cast<uint64_t>(ec)) + " - " + comment) : code(ec), comment(info), message(std::to_string(static_cast<uint64_t>(ec)) + " - " + comment)
{} {}
char const* what() const override; [[nodiscard]] char const* what() const noexcept override;
}; };
} }
+2 -2
View File
@@ -117,9 +117,9 @@ std::string ToHex(std::byte* src, size_t len)
return ret; return ret;
} }
std::string HashPassword(const std::string& password) std::string HashPassword(std::string_view password)
{ {
size_t calculated_hash = std::hash<string>{}(password); size_t calculated_hash = std::hash<std::string_view>{}(password);
return ToHex((byte*)&calculated_hash, sizeof(calculated_hash)); return ToHex((byte*)&calculated_hash, sizeof(calculated_hash));
} }
+1 -1
View File
@@ -12,7 +12,7 @@ void Fail(boost::beast::error_code ec, char const* what);
std::string ToHex(std::byte* src, size_t len); std::string ToHex(std::byte* src, size_t len);
std::string HashPassword(const std::string& password); std::string HashPassword(std::string_view password);
std::string GenerateUUID(); std::string GenerateUUID();
-2
View File
@@ -1,5 +1,3 @@
#pragma once
#include <boost/log/trivial.hpp> #include <boost/log/trivial.hpp>
#include <boost/log/utility/setup/file.hpp> #include <boost/log/utility/setup/file.hpp>
#include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/utility/setup/common_attributes.hpp>
+6 -6
View File
@@ -51,12 +51,12 @@ BOOST_AUTO_TEST_CASE(Should_Be_Initiated_With_Unordered_Map_HTTP_Methods_To_Exec
{ {
IControllerMock::HTTPMethodsToExecutors executors; IControllerMock::HTTPMethodsToExecutors executors;
executors[beast::http::verb::get] = make_shared<MockExecutor>(); executors[beast::http::verb::get] = std::make_shared<MockExecutor>();
executors[beast::http::verb::post] = make_shared<MockExecutor>(); executors[beast::http::verb::post] = std::make_shared<MockExecutor>();
executors[beast::http::verb::put] = make_shared<MockExecutor>(); executors[beast::http::verb::put] = std::make_shared<MockExecutor>();
executors[beast::http::verb::delete_] = make_shared<MockExecutor>(); executors[beast::http::verb::delete_] = std::make_shared<MockExecutor>();
executors[beast::http::verb::head] = make_shared<MockExecutor>(); executors[beast::http::verb::head] = std::make_shared<MockExecutor>();
executors[beast::http::verb::options] = make_shared<MockExecutor>(); executors[beast::http::verb::options] = std::make_shared<MockExecutor>();
IControllerMock my_controller(std::move(executors)); IControllerMock my_controller(std::move(executors));