30 Commits

Author SHA1 Message Date
Sithas 12ca243c21 Настроенный запуск 2026-02-10 11:33:16 +03:00
Sithas 6cd277c754 Настроенный запуск(невидимый снаружи) 2026-02-10 10:53:47 +03:00
Sithas 69b97275a6 Настроенный запуск(невидимый снаружи) 2026-02-10 09:41:43 +03:00
Sithas 75a9e4cc14 Настроенный запуск(невидимый снаружи) 2026-02-08 11:02:38 +03:00
Sithas 40f8d48296 Настроенная сборка 2026-02-08 10:05:51 +03:00
Sithas d198317d4f Почти настроенная сборка 2026-02-08 09:25:10 +03:00
Sithas 9bd4187e9b База для сборки образа(MySQL+Boost+cmake) 2026-02-07 13:13:06 +03:00
Sithas bff937f9a7 Перепись с const std::string& на std::string_view 2026-02-07 09:44:03 +03:00
Sithas 0ee1beacfa Перепись с const std::string& на std::string_view 2026-01-30 09:21:13 +03:00
Sithas 513210a304 Перепись с const std::string& на std::string_view 2026-01-29 18:50:21 +03:00
Sithas 3f77cdc2bd Перепись с const std::string& на std::string_view 2026-01-29 18:45:16 +03:00
Sithas 9a7c9b7e7c Перепись с const std::string& на std::string_view 2026-01-29 09:33:38 +03:00
Sithas 91d20fcf01 Delete Diary 2026-01-29 07:45:40 +03:00
Sithas e4104e9707 Put Diary 2026-01-25 15:08:30 +03:00
Sithas b3007c1471 Post Diary 2026-01-25 11:18:07 +03:00
Sithas 66632855c2 Post Diary 2026-01-25 11:03:41 +03:00
Sithas 199659266f Post Diary 2026-01-25 10:02:15 +03:00
Sithas 7ff1bf10f8 Post Diary 2026-01-24 11:07:56 +03:00
Sithas 10f86a5a99 Post Diary 2026-01-24 11:02:17 +03:00
Sithas 3547ce3cb5 Добавление nodiscard 2026-01-23 08:11:16 +03:00
Sithas 14561b303e Добавление nodiscard 2026-01-22 08:38:55 +03:00
Sithas 05a135afc6 Ручка PostUserTreatmentScheme.h 2026-01-18 11:47:37 +03:00
Sithas c5c6058fb2 База для ручки GetUserDiariesExecutor.h 2026-01-17 22:02:39 +03:00
Sithas 80e171532f База для ручки GetUserDiariesExecutor.h 2026-01-17 11:33:39 +03:00
Sithas 22be5842be База для ручки GetUserDiariesExecutor.h 2026-01-17 11:24:12 +03:00
Sithas 8a61656343 База для ручки GetUserDiariesExecutor.h 2026-01-17 09:55:03 +03:00
Sithas 2027bbb513 База для ручки GetUserDiariesExecutor.h 2026-01-17 09:24:04 +03:00
Sithas 08943b5938 База для ручки GetUserDiariesExecutor.h 2026-01-16 08:08:11 +03:00
Sithas f56c14b3da База для ручки PostUserMedicationsExecutor.h 2026-01-16 07:40:00 +03:00
Sithas 11641e3fa1 База для ручки PostUserMedicationsExecutor.h 2026-01-13 08:33:54 +03:00
37 changed files with 1358 additions and 275 deletions
+119 -98
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)
if (WIN32)
set(Boost_INCLUDE_DIR ${BOOST_ROOT}) set(Boost_INCLUDE_DIR ${BOOST_ROOT})
set(Boost_LIBRARY_DIR "${BOOST_ROOT}/stage/lib") set(Boost_LIBRARY_DIR "${BOOST_ROOT}/stage/lib")
endif ()
find_package(Boost 1.88.0 REQUIRED COMPONENTS filesystem json log system filesystem) 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,47 +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
${CMAKE_SOURCE_DIR}/src/endpoints_handlers/GetUserTreatmentSchemeExecutor.h
${CMAKE_SOURCE_DIR}/src/endpoints_handlers/GetDiariesExecutor.h
${CMAKE_SOURCE_DIR}/src/endpoints_handlers/PostDiaryExecutor.h
${CMAKE_SOURCE_DIR}/src/endpoints_handlers/PutDiaryExecutor.h
${CMAKE_SOURCE_DIR}/src/endpoints_handlers/DeleteDiaryExecutor.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
@@ -71,6 +82,8 @@ target_link_libraries(App PRIVATE Boost::boost
Boost::log Boost::log
Boost::system Boost::system
Boost::filesystem Boost::filesystem
Boost::url
Boost::log_setup
Threads::Threads Threads::Threads
mysql::concpp) mysql::concpp)
@@ -78,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 \
"]
+38 -23
View File
@@ -1,10 +1,14 @@
# Запуск(Без 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) для регистрации, авторизации, логаута~~
- Посмотреть по поводу блокировок или тред пулла при использовании базы
- Посмотреть пулл соединений(Object pool) при использовании базы данных(посмотреть api MySQL-Connector)
- Посмотреть, что дает MySQL, какие там есть возможность
- Посмотреть и подумать, что лучше - корутины или многопоточность?
- ~~Покрыть тестами класс User и AuthRegistrationExecutor~~ - ~~Покрыть тестами класс User и AuthRegistrationExecutor~~
- ~~Добавить clang-format(через CLion)~~ - ~~Добавить clang-format(через CLion)~~
- ~~Перевести GetByUUID GetByLogin на const ref/string_view в IUserDAO - также не vector, а span(погуглить)~~ - span не применим - ~~Перевести GetByUUID GetByLogin на const ref/string_view в IUserDAO - также не vector, а span(погуглить)~~ - span не применим
@@ -18,12 +22,36 @@
- ~~Покрыть логами~~ - ~~Покрыть логами~~
- ~~Сделать один класс исключений, имеющих метод HTTP code - код и сообщение записывать уже в ловушке~~ - ~~Сделать один класс исключений, имеющих метод HTTP code - код и сообщение записывать уже в ловушке~~
- ~~Сделать интеграционный тест по ручкам~~ - ~~Сделать интеграционный тест по ручкам~~
- UseCase'ы по работе с личным кабинетом
- Научиться поднимать базы данных под каждый тест - научиться Docker - docker-compose - а если тест что-то должен заполнить, то он заполняет в самом начале()
- Возможно, сделать тесты на CI/CD - приоритет - низкий
- ~~Заменить internal_server_error на bad_request и перепроверить коды ошибок~~ - ~~Заменить internal_server_error на bad_request и перепроверить коды ошибок~~
- ~~Создание и удаление вспомогательных классов должно быть вынесено в фикстуру~~ - ~~Создание и удаление вспомогательных классов должно быть вынесено в фикстуру~~
- ~~К следующему занятию сделать ручку из кейса 3 + восстановить фикстуры из тестов~~ - ~~К следующему занятию сделать ручку из кейса 3 + восстановить фикстуры из тестов~~
- Посмотреть по поводу блокировок или тред пулла при использовании базы
- Посмотреть пулл соединений(Object pool) при использовании базы данных(посмотреть api MySQL-Connector)
- Посмотреть и подумать, что лучше - корутины или многопоточность?
- UseCase'ы по работе с личным кабинетом
- Найти слабые места в C++ -- std::forward, universal reference, просмотреть про decltype(почитать статьи)
- ~~Разобрать decltype и auto по статье~~
- Подготовить резюме для тестовых собесов
- DockerHosting.ru - купить аренду после того, как будет готов фронт и бэк
До 27.01.2026
- ~~Подобрать сервер по параметрам. Использовать linux.~~
- ~~Перевести string на string_view~~
- ~~Попробовать nodiscard к executoru~~
- ~~Добить 2 ручки~~
До 10.02.2026
- Сделать 2-3 теста
- Продвинуться по фронтенду(форма авторизации и логина)
- Сделать Dockerfile & Docker-compose(очищать и заполнять базу после каждого тест-кейса)
- Возможно, сделать тесты на CI/CD - приоритет - низкий
- Научиться поднимать базы данных под каждый тест - научиться Docker - docker-compose - а если тест что-то должен заполнить, то он заполняет в самом начале
- Проставить const на немутабельные объекты
# План
1)Добить бэкенд(2 ручки) (до февраля)
2)Сделать деплой(до марта)
3)Сделать фронтенд для MVP
4)Делаем веб-чат и роль доктора
5)Читать книгу Мейерса "Эффективный и современный C++" до ???
# UseCase'ы приложения: # UseCase'ы приложения:
@@ -193,7 +221,7 @@ null
"dream_level": 6, "dream_level": 6,
"anxiety_level": 7, "anxiety_level": 7,
"comment": "Накрыл психоз. Выпил одну таблетку аминазина" "comment": "Накрыл психоз. Выпил одну таблетку аминазина"
"treatment_scheme_uuid": bf6d1555-39e9-4d73-8928-4763627f4dd5 "user_treatment_scheme_uuid": bf6d1555-39e9-4d73-8928-4763627f4dd5
} }
] ]
} }
@@ -211,13 +239,7 @@ null
"treatment_name": "Bipolar I Scheme Urgent", "treatment_name": "Bipolar I Scheme Urgent",
"instructions": "Схема для быстрого и жесткого купирования психозов. Аминазин пить каждый день.", "instructions": "Схема для быстрого и жесткого купирования психозов. Аминазин пить каждый день.",
"medications": [ "medications": [
{ "eda5a5f7-167a-44b9-900d-c5c6acfc249b"
"uuid": "eda5a5f7-167a-44b9-900d-c5c6acfc249b",
"name": "Aminazin",
"dose": 100,
"unit": "mg",
"is_urgent": true
}
] ]
} }
] ]
@@ -296,14 +318,7 @@ null
`dream_level`: "5", `dream_level`: "5",
`anxiety_level`: "9", `anxiety_level`: "9",
`comment`: "Сильная тревога. Пришлось выпить аминазин", `comment`: "Сильная тревога. Пришлось выпить аминазин",
`user_treatment_scheme`: { `user_treatment_scheme`: "51351bb1-7563-479d-a8e9-201d0ff934c2"
"uuid": "248313cb-a75e-4331-8379-d3f2fc36b68d"
"treatment_name": "Bipolar I Scheme Urgent",
"instructions": "Схема для быстрого и жесткого купирования психозов. Аминазин пить каждый день.",
"medications": [
"eda5a5f7-167a-44b9-900d-c5c6acfc249b"
]
},
} }
``` ```
##### Errors ##### Errors
+7
View File
@@ -0,0 +1,7 @@
init
seed_states
seed_medications
seed_users
seed_user_treatment_schemes
seed_treatment_schemes
seed_diaries
+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 GetLogin(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;
}; };
+33
View File
@@ -0,0 +1,33 @@
#pragma once
#include <vector>
#include <string>
#include "./../dtos/diary_dto.h"
namespace uad
{
class IDiariesDAO
{
public:
virtual std::vector<diary_dto> GetDiariesByUserUUID(std::string_view login) = 0;
virtual void СreateDiary(
std::string_view user_uuid,
const diary_dto& dto
) 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;
};
}
+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;
}; };
+6 -1
View File
@@ -8,7 +8,12 @@ namespace uad
{ {
class IUserTreatmentSchemeDAO { class IUserTreatmentSchemeDAO {
public: public:
virtual std::vector<user_treatment_scheme_dto> FindByUserLogin(const std::string& login) = 0; virtual std::vector<user_treatment_scheme_dto> FindByUserUUID(std::string_view login) = 0;
virtual void CreateUserTreatmentScheme(
std::string_view user_login,
const user_treatment_scheme_dto& dto
) = 0;
virtual ~IUserTreatmentSchemeDAO() = default; virtual ~IUserTreatmentSchemeDAO() = default;
}; };
+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::GetLogin(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 GetLogin(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;
}; };
} }
+170
View File
@@ -0,0 +1,170 @@
#include "MySQLDiariesDAO.h"
#include "../exceptions/session_exception.h"
namespace uad
{
MySqlDiariesDAO::MySqlDiariesDAO(mysqlx::Session& session) : session_(session)
{
}
std::vector<diary_dto> MySqlDiariesDAO::GetDiariesByUserUUID(std::string_view user_uuid)
{
static const std::string query = R"(
SELECT
d.uuid,
UNIX_TIMESTAMP(d.time) * 1000,
d.mania_level,
d.depression_level,
d.mood_level,
d.activity_level,
d.appetite_level,
d.dream_level,
d.anxiety_level,
d.comment,
d.user_treatment_schemes_uuid
FROM up_and_down.diaries d
WHERE d.user_uuid = ?
ORDER BY d.time;
)";
mysqlx::SqlResult result = session_
.sql(query)
.bind(user_uuid.data())
.execute();
std::vector<diary_dto> diaries;
diaries.reserve(result.count());
for (const mysqlx::Row& row : result)
{
diary_dto dto;
dto.uuid = row[0].get<std::string>();
dto.time_ms = row[1].get<std::int64_t>();
dto.mania_level = row[2].get<int>();
dto.depression_level = row[3].get<int>();
dto.mood_level = row[4].get<int>();
dto.activity_level = row[5].get<int>();
dto.appetite_level = row[6].get<int>();
dto.dream_level = row[7].get<int>();
dto.anxiety_level = row[8].get<int>();
dto.comment = row[9].get<std::string>();
dto.user_treatment_scheme_uuid = row[10].get<std::string>();
diaries.push_back(std::move(dto));
}
return diaries;
}
void MySqlDiariesDAO::СreateDiary(std::string_view user_uuid, const diary_dto& dto) const
{
auto stmt = session_.sql(R"(
INSERT INTO `up_and_down`.`diaries` (
uuid,
user_uuid,
time,
mania_level,
depression_level,
mood_level,
activity_level,
appetite_level,
dream_level,
anxiety_level,
comment,
user_treatment_schemes_uuid
) VALUES (
?,
?,
FROM_UNIXTIME(? / 1000),
?,
?,
?,
?,
?,
?,
?,
?,
?
)
)");
stmt.bind(
dto.uuid,
user_uuid.data(),
dto.time_ms,
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
);
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");
}
}
}
+36
View File
@@ -0,0 +1,36 @@
#pragma once
#include <vector>
#include <string>
#include "./../DAO/IDiariesDAO.h"
#include "./../db/mysql_connector.h"
namespace uad
{
class MySqlDiariesDAO final : public IDiariesDAO
{
mysqlx::Session& session_;
public:
explicit MySqlDiariesDAO(mysqlx::Session& session);
std::vector<diary_dto> GetDiariesByUserUUID(std::string_view user_uuid) override;
void СreateDiary(
std::string_view user_uuid,
const diary_dto& dto
) 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);
+58 -9
View File
@@ -10,8 +10,8 @@ MySQLUserTreatmentSchemesDAO::MySQLUserTreatmentSchemesDAO(mysqlx::Session& sess
{ {
} }
std::vector<user_treatment_scheme_dto> MySQLUserTreatmentSchemesDAO::FindByUserLogin( std::vector<user_treatment_scheme_dto> MySQLUserTreatmentSchemesDAO::FindByUserUUID(
const std::string& login) std::string_view user_uuid)
{ {
static const std::string query = R"( static const std::string query = R"(
SELECT SELECT
@@ -24,18 +24,23 @@ std::vector<user_treatment_scheme_dto> MySQLUserTreatmentSchemesDAO::FindByUserL
ON uts.user_uuid = u.uuid ON uts.user_uuid = u.uuid
LEFT JOIN up_and_down.treatment_schemes ts LEFT JOIN up_and_down.treatment_schemes ts
ON ts.user_treatment_schemes_uuid = uts.uuid ON ts.user_treatment_schemes_uuid = uts.uuid
WHERE u.login = ? WHERE u.uuid = ?
ORDER BY uts.uuid ORDER BY uts.uuid
)"; )";
mysqlx::SqlResult result = session_.sql(query).bind(login).execute(); mysqlx::SqlResult result = session_
.sql(query)
.bind(user_uuid.data())
.execute();
std::unordered_map<std::string, user_treatment_scheme_dto> scheme_map; std::unordered_map<std::string, user_treatment_scheme_dto> scheme_map;
for (const mysqlx::Row& row : result) { for (const mysqlx::Row& row : result)
{
const std::string scheme_uuid = row[0].get<std::string>(); const std::string scheme_uuid = row[0].get<std::string>();
if (scheme_map.find(scheme_uuid) == scheme_map.end()) { if (scheme_map.find(scheme_uuid) == scheme_map.end())
{
user_treatment_scheme_dto dto; user_treatment_scheme_dto dto;
dto.uuid = scheme_uuid; dto.uuid = scheme_uuid;
dto.treatment_name = row[1].isNull() ? "" : row[1].get<std::string>(); dto.treatment_name = row[1].isNull() ? "" : row[1].get<std::string>();
@@ -44,7 +49,8 @@ std::vector<user_treatment_scheme_dto> MySQLUserTreatmentSchemesDAO::FindByUserL
scheme_map.emplace(scheme_uuid, std::move(dto)); scheme_map.emplace(scheme_uuid, std::move(dto));
} }
if (!row[3].isNull()) { if (!row[3].isNull())
{
scheme_map[scheme_uuid] scheme_map[scheme_uuid]
.medication_uuids .medication_uuids
.push_back(row[3].get<std::string>()); .push_back(row[3].get<std::string>());
@@ -54,10 +60,53 @@ std::vector<user_treatment_scheme_dto> MySQLUserTreatmentSchemesDAO::FindByUserL
std::vector<user_treatment_scheme_dto> schemes; std::vector<user_treatment_scheme_dto> schemes;
schemes.reserve(scheme_map.size()); schemes.reserve(scheme_map.size());
for (auto& [_, dto] : scheme_map) { for (auto& [_, dto] : scheme_map)
{
schemes.push_back(std::move(dto)); schemes.push_back(std::move(dto));
} }
return schemes; return std::move(schemes);
}
void MySQLUserTreatmentSchemesDAO::CreateUserTreatmentScheme(
std::string_view user_uuid,
const user_treatment_scheme_dto& dto)
{
session_.startTransaction();
try {
session_.sql(R"(
INSERT INTO up_and_down.user_treatment_schemes (
uuid,
user_uuid,
treatment_name,
instructions
) VALUES (?, ?, ?, ?)
)")
.bind(
dto.uuid,
user_uuid.data(),
dto.treatment_name,
dto.instructions
)
.execute();
for (const auto& medication_uuid : dto.medication_uuids) {
session_.sql(R"(
INSERT INTO up_and_down.treatment_schemes (
user_treatment_schemes_uuid,
medication_uuid
) VALUES (?, ?)
)")
.bind(dto.uuid, medication_uuid)
.execute();
}
session_.commit();
}
catch (...) {
session_.rollback();
throw;
}
} }
} // uad } // uad
+6 -1
View File
@@ -11,6 +11,11 @@ class MySQLUserTreatmentSchemesDAO : public IUserTreatmentSchemeDAO
public: public:
explicit MySQLUserTreatmentSchemesDAO(mysqlx::Session& session); explicit MySQLUserTreatmentSchemesDAO(mysqlx::Session& session);
std::vector<user_treatment_scheme_dto> FindByUserLogin(const std::string& login) override; std::vector<user_treatment_scheme_dto> FindByUserUUID(std::string_view uuid) override;
void CreateUserTreatmentScheme(
std::string_view user_login,
const user_treatment_scheme_dto& dto
) override;
}; };
} // uad } // uad
+22
View File
@@ -0,0 +1,22 @@
#pragma once
#include <string>
#include <cstdint>
namespace uad
{
struct diary_dto
{
std::string uuid;
int64_t time_ms;
int64_t mania_level;
int64_t depression_level;
int64_t mood_level;
int64_t activity_level;
int64_t appetite_level;
int64_t dream_level;
int64_t anxiety_level;
std::string comment;
std::string user_treatment_scheme_uuid;
};
}
+1 -1
View File
@@ -30,7 +30,7 @@ public:
{ {
} }
boost::beast::http::response<ResponseType> operator ()( [[nodiscard]] boost::beast::http::response<ResponseType> operator ()(
boost::beast::http::request<Body, boost::beast::http::basic_fields<Allocator>>&& req boost::beast::http::request<Body, boost::beast::http::basic_fields<Allocator>>&& req
) override ) override
{ {
+1 -1
View File
@@ -23,7 +23,7 @@ public:
{ {
} }
boost::beast::http::response<ResponseType> operator ()( [[nodiscard]] boost::beast::http::response<ResponseType> operator ()(
boost::beast::http::request<Body, boost::beast::http::basic_fields<Allocator>>&& req boost::beast::http::request<Body, boost::beast::http::basic_fields<Allocator>>&& req
) override ) override
{ {
@@ -24,7 +24,7 @@ public:
{ {
} }
boost::beast::http::response<ResponseType> operator ()( [[nodiscard]] boost::beast::http::response<ResponseType> operator ()(
boost::beast::http::request<Body, boost::beast::http::basic_fields<Allocator>>&& req boost::beast::http::request<Body, boost::beast::http::basic_fields<Allocator>>&& req
) 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;
}
};
}
+123
View File
@@ -0,0 +1,123 @@
#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 GetDiariesExecutor : public IExecutor<Body, Allocator, ResponseType>
{
mysqlx::Session& session_;
const std::shared_ptr<IAuthDAO>& auth_dao_;
const std::shared_ptr<IDiariesDAO>& diaries_dao_;
public:
GetDiariesExecutor(
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
) override
{
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 =
"GET /api/v1/User/Medications - Response 401: Unauthorized"s;
BOOST_LOG_TRIVIAL(info) << "GET /api/v1/User/Medications - 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()};
std::vector<diary_dto> diaries = diaries_dao_->GetDiariesByUserUUID(user_uuid);
http::response<ResponseType> res{http::status::ok, req.version()};
value response_body;
response_body.emplace_object();
response_body.as_object().emplace("diaries", toJSONArray(diaries));
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;
}
boost::json::array toJSONArray(const std::vector<diary_dto>& schemes)
{
using namespace boost;
using namespace boost::json;
using namespace boost::beast;
using namespace std::string_literals;
using namespace std::string_view_literals;
json::array arr;
for (const auto& m : schemes)
{
arr.emplace_back(ToJSON(m));
}
return std::move(arr);
}
};
}
@@ -29,7 +29,7 @@ public:
} }
boost::beast::http::response<ResponseType> operator ()( [[nodiscard]] boost::beast::http::response<ResponseType> operator ()(
boost::beast::http::request<Body, boost::beast::http::basic_fields<Allocator>>&& req boost::beast::http::request<Body, boost::beast::http::basic_fields<Allocator>>&& req
) override ) override
{ {
@@ -29,7 +29,7 @@ public:
{ {
} }
boost::beast::http::response<ResponseType> operator ()( [[nodiscard]] boost::beast::http::response<ResponseType> operator ()(
boost::beast::http::request<Body, boost::beast::http::basic_fields<Allocator>>&& req boost::beast::http::request<Body, boost::beast::http::basic_fields<Allocator>>&& req
) override ) override
{ {
@@ -41,9 +41,9 @@ public:
constexpr std::string_view auth_prefix = "Bearer "sv; constexpr std::string_view auth_prefix = "Bearer "sv;
static const std::string invalid_token_message = static const std::string invalid_token_message =
"GET /api/v1/User/Medications - Response 401: Unauthorized"s; "GET /api/v1/UserTreatmentSchemes - Response 401: Unauthorized"s;
BOOST_LOG_TRIVIAL(info) << "GET /api/v1/User/Medications - Request"; BOOST_LOG_TRIVIAL(info) << "GET /api/v1/UserTreatmentSchemes - Request";
if (req[http::field::authorization].size() <= auth_prefix.size()) if (req[http::field::authorization].size() <= auth_prefix.size())
{ {
@@ -62,66 +62,16 @@ public:
throw session_exception(http::status::unauthorized, "Unauthorized"); throw session_exception(http::status::unauthorized, "Unauthorized");
} }
std::string_view user_login_ref = auth_dao_->GetLogin(auth_token); std::string_view user_uuid_ref = auth_dao_->GetUUID(auth_token);
const std::string user_uuid{user_login_ref.begin(), user_login_ref.end()}; const std::string user_uuid{user_uuid_ref.begin(), user_uuid_ref.end()};
static const std::string query = R"( std::vector<user_treatment_scheme_dto> schemes = user_treatment_scheme_dao_->FindByUserUUID(user_uuid);
SELECT
uts.uuid,
uts.treatment_name,
uts.instructions,
ts.medication_uuid
FROM up_and_down.users u
JOIN up_and_down.user_treatment_schemes uts
ON uts.user_uuid = u.uuid
LEFT JOIN up_and_down.treatment_schemes ts
ON ts.user_treatment_schemes_uuid = uts.uuid
WHERE u.uuid = ?
ORDER BY uts.uuid
)";
mysqlx::SqlResult result = session_
.sql(query)
.bind(user_uuid)
.execute();
std::unordered_map<std::string, user_treatment_scheme_dto> scheme_map;
for (const mysqlx::Row& row : result)
{
const std::string scheme_uuid = row[0].get<std::string>();
if (scheme_map.find(scheme_uuid) == scheme_map.end())
{
user_treatment_scheme_dto dto;
dto.uuid = scheme_uuid;
dto.treatment_name = row[1].isNull() ? "" : row[1].get<std::string>();
dto.instructions = row[2].isNull() ? "" : row[2].get<std::string>();
scheme_map.emplace(scheme_uuid, std::move(dto));
}
if (!row[3].isNull())
{
scheme_map[scheme_uuid]
.medication_uuids
.push_back(row[3].get<std::string>());
}
}
std::vector<user_treatment_scheme_dto> schemes;
schemes.reserve(scheme_map.size());
for (auto& [_, dto] : scheme_map)
{
schemes.push_back(std::move(dto));
}
http::response<ResponseType> res{http::status::ok, req.version()}; http::response<ResponseType> res{http::status::ok, req.version()};
value response_body; value response_body;
response_body.emplace_object(); response_body.emplace_object();
response_body.as_object().emplace("user_treatment_schemes", toJSONArray(schemes)); response_body.as_object().emplace("user_treatment_schemes", ToJSONArray(schemes));
res.body() = serialize(response_body); res.body() = serialize(response_body);
res.set(http::field::content_type, "application/json"); res.set(http::field::content_type, "application/json");
@@ -149,7 +99,7 @@ private:
return scheme_json; return scheme_json;
} }
boost::json::array toJSONArray(const std::vector<user_treatment_scheme_dto>& schemes) boost::json::array ToJSONArray(const std::vector<user_treatment_scheme_dto>& schemes)
{ {
using namespace boost; using namespace boost;
using namespace boost::json; using namespace boost::json;
+4 -1
View File
@@ -11,6 +11,7 @@
#include "../DAO/MemoryAuthDAO.h" #include "../DAO/MemoryAuthDAO.h"
#include "../DAO/MySQLUserDAO.h" #include "../DAO/MySQLUserDAO.h"
#include "../DAO/MySQLMedicationsDAO.h" #include "../DAO/MySQLMedicationsDAO.h"
#include "../DAO/MySQLDiariesDAO.h"
namespace uad namespace uad
{ {
@@ -24,13 +25,15 @@ void HandleRequest(
static std::shared_ptr<IAuthDAO> auth_dao = std::make_shared<MemoryAuthDAO>(GetMySqlSession()); static std::shared_ptr<IAuthDAO> auth_dao = std::make_shared<MemoryAuthDAO>(GetMySqlSession());
static std::shared_ptr<IMedicationsDAO> medications_dao = std::make_shared<MySQLMedicationsDAO>(GetMySqlSession()); static std::shared_ptr<IMedicationsDAO> medications_dao = std::make_shared<MySQLMedicationsDAO>(GetMySqlSession());
static std::shared_ptr<IUserTreatmentSchemeDAO> user_treatment_schemes_dao = std::make_shared<MySQLUserTreatmentSchemesDAO>(GetMySqlSession()); static std::shared_ptr<IUserTreatmentSchemeDAO> user_treatment_schemes_dao = std::make_shared<MySQLUserTreatmentSchemesDAO>(GetMySqlSession());
static std::shared_ptr<IDiariesDAO> diaries_dao = std::make_shared<MySqlDiariesDAO>(GetMySqlSession());
static RootExecutor<Body, Allocator, boost::beast::http::string_body, Send> root_executor( static RootExecutor<Body, Allocator, boost::beast::http::string_body, Send> root_executor(
GetMySqlSession(), GetMySqlSession(),
user_dao, user_dao,
auth_dao, auth_dao,
medications_dao, medications_dao,
user_treatment_schemes_dao user_treatment_schemes_dao,
diaries_dao
); );
root_executor(doc_root, std::move(req), std::forward<Send>(send)); root_executor(doc_root, std::move(req), std::forward<Send>(send));
+22 -1
View File
@@ -8,9 +8,30 @@ template <class Body, class Allocator, class ResponseType>
class IExecutor class IExecutor
{ {
public: public:
virtual boost::beast::http::response<ResponseType> operator ()( [[nodiscard]] virtual boost::beast::http::response<ResponseType> operator ()(
boost::beast::http::request<Body, boost::beast::http::basic_fields<Allocator>>&& req boost::beast::http::request<Body, boost::beast::http::basic_fields<Allocator>>&& req
) = 0; ) = 0;
virtual ~IExecutor() = default; virtual ~IExecutor() = default;
}; };
// class IAuthorizable : public IExecutor
// {
// IExecutor& next_executor_;
// public:
// IAuthorizable(IExecutor& next_executor): next_executor_(next_executor)
// {
//
// }
//
// boost::beast::http::response<ResponseType> operator ()(
// boost::beast::http::request<Body, boost::beast::http::basic_fields<Allocator>>&& req
// ) override
// {
// // Логика проверки авторизации
// // передать управление следующему executorу - возврат req
// // посмотреть chain of responsibility, composite
// // выбрасывать исключение здесь
// return next_executor_(req);
// }
// };
} }
+140
View File
@@ -0,0 +1,140 @@
#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 PostDiaryExecutor : public IExecutor<Body, Allocator, ResponseType>
{
mysqlx::Session& session_;
const std::shared_ptr<IAuthDAO>& auth_dao_;
const std::shared_ptr<IDiariesDAO>& diaries_dao_;
public:
PostDiaryExecutor(
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
) override
{
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 =
"POST /api/v1/Diary - Response 401: Unauthorized"s;
BOOST_LOG_TRIVIAL(info) << "POST /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 = GenerateUUID();
dto.time_ms = obj["time_ms"].as_int64();
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();
try
{
session_.startTransaction();
diaries_dao_->СreateDiary(user_uuid, dto);
session_.commit();
}
catch (const mysqlx::Error& e)
{
session_.rollback();
BOOST_LOG_TRIVIAL(error) << "MySQL Error: " << e.what();
throw session_exception(http::status::internal_server_error, "Internal Server Error");
}
catch (const std::exception& e)
{
session_.rollback();
BOOST_LOG_TRIVIAL(error) << "Unexpected Error: " << e.what();
throw session_exception(http::status::internal_server_error, "Internal Server Error");
}
http::response<ResponseType> res{http::status::ok, req.version()};
value response_body;
response_body.emplace_object();
response_body.as_object().emplace("diary", 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;
}
};
}
@@ -29,7 +29,7 @@ public:
} }
boost::beast::http::response<ResponseType> operator ()( [[nodiscard]] boost::beast::http::response<ResponseType> operator ()(
boost::beast::http::request<Body, boost::beast::http::basic_fields<Allocator>>&& req boost::beast::http::request<Body, boost::beast::http::basic_fields<Allocator>>&& req
) override ) override
{ {
@@ -68,7 +68,7 @@ public:
} }
catch (const system::system_error& err) catch (const system::system_error& err)
{ {
BOOST_LOG_TRIVIAL(info) << "POST /api/v1/User/Medications - Response 400: Cannot deserialize json"; BOOST_LOG_TRIVIAL(error) << "POST /api/v1/User/Medications - Response 400: Cannot deserialize json";
throw session_exception(http::status::bad_request, "Cannot deserialize json"); throw session_exception(http::status::bad_request, "Cannot deserialize json");
} }
@@ -0,0 +1,144 @@
#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/IUserTreatmentSchemesDAO.h"
#include "../exceptions/session_exception.h"
namespace uad
{
template <class Body, class Allocator, class ResponseType>
class PostUserTreatmentSchemeExecutor : public IExecutor<Body, Allocator, ResponseType>
{
mysqlx::Session& session_;
const std::shared_ptr<IAuthDAO>& auth_dao_;
const std::shared_ptr<IUserTreatmentSchemeDAO>& user_treatment_scheme_dao_;
public:
PostUserTreatmentSchemeExecutor(
mysqlx::Session& session,
const std::shared_ptr<IAuthDAO>& auth_dao,
const std::shared_ptr<IUserTreatmentSchemeDAO>& user_treatment_scheme_dao
) : session_(session), auth_dao_(auth_dao), user_treatment_scheme_dao_(user_treatment_scheme_dao)
{
}
[[nodiscard]] 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;
using namespace std::string_view_literals;
constexpr std::string_view auth_prefix = "Bearer "sv;
static const std::string invalid_token_message =
"POST /api/v1/UserTreatmentSchemes - Response 401: Unauthorized"s;
BOOST_LOG_TRIVIAL(info) << "POST /api/v1/UserTreatmentSchemes - 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()};
const auto body = req.body();
value req_json;
try
{
req_json = json::parse(body);
}
catch (const system::system_error& err)
{
BOOST_LOG_TRIVIAL(error) <<
"POST /api/v1/UserTreatmentSchemes - Response 400: Cannot deserialize json";
throw session_exception(http::status::bad_request, "Cannot deserialize json");
}
user_treatment_scheme_dto utsd = FromJSON(req_json);
utsd.uuid = GenerateUUID();
try
{
user_treatment_scheme_dao_->CreateUserTreatmentScheme(user_uuid, utsd);
}
catch (...)
{
BOOST_LOG_TRIVIAL(error) <<
"POST /api/v1/UserTreatmentSchemes - Response 400: Cannot write entity";
throw session_exception(http::status::bad_request, "Cannot write entity");
}
http::response<ResponseType> res{http::status::ok, req.version()};
json::value res_json = ToJSON(utsd);
res.body() = serialize(res_json);
res.set(http::field::content_type, "application/json");
res.content_length(res.body().size());
return res;
}
private:
user_treatment_scheme_dto FromJSON(const boost::json::value& scheme)
{
user_treatment_scheme_dto dto;
dto.treatment_name =
scheme.at("treatment_name").as_string().c_str();
dto.instructions =
scheme.at("instructions").as_string().c_str();
for (const auto& med : scheme.at("medications").as_array())
{
dto.medication_uuids.push_back(
med.as_string().c_str()
);
}
return dto;
}
boost::json::object ToJSON(const user_treatment_scheme_dto& utsd)
{
boost::json::array medications_json;
medications_json.reserve(utsd.medication_uuids.size());
for (const auto& medication_uuid : utsd.medication_uuids) {
medications_json.emplace_back(medication_uuid);
}
boost::json::object scheme_json;
scheme_json["uuid"] = utsd.uuid;
scheme_json["treatment_name"] = utsd.treatment_name;
scheme_json["instructions"] = utsd.instructions;
scheme_json["medications"] = std::move(medications_json);
return scheme_json;
}
};
}
+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;
}
};
}
+110 -19
View File
@@ -1,3 +1,6 @@
#pragma once
#include <boost/url.hpp>
#include <mysqlx/xdevapi.h> #include <mysqlx/xdevapi.h>
#include <mysqlx/common/api.h> #include <mysqlx/common/api.h>
@@ -9,9 +12,15 @@
#include "AuthLogoutExecutor.h" #include "AuthLogoutExecutor.h"
#include "GetUserMedicationsExecutor.h" #include "GetUserMedicationsExecutor.h"
#include "GetUserTreatmentSchemeExecutor.h" #include "GetUserTreatmentSchemeExecutor.h"
#include "PostUserTreatmentSchemeExecutor.h"
#include "PostUserMedicationsExecutor.h" #include "PostUserMedicationsExecutor.h"
#include "GetDiariesExecutor.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/IMedicationsDAO.h" #include "../DAO/IMedicationsDAO.h"
#include "../DAO/IUserTreatmentSchemesDAO.h" #include "../DAO/IUserTreatmentSchemesDAO.h"
#include "./../helpers/helpers.h" #include "./../helpers/helpers.h"
@@ -35,6 +44,17 @@ class RootExecutor
Body, Allocator, boost::beast::http::string_body>; Body, Allocator, boost::beast::http::string_body>;
using RouteGetUserTreatmentSchemeExecutor = GetUserTreatmentSchemeExecutor< using RouteGetUserTreatmentSchemeExecutor = GetUserTreatmentSchemeExecutor<
Body, Allocator, boost::beast::http::string_body>; Body, Allocator, boost::beast::http::string_body>;
using RoutePostUserTreatmentSchemeExecutor = PostUserTreatmentSchemeExecutor<
Body, Allocator, boost::beast::http::string_body>;
using RouteGetDiariesExecutor = GetDiariesExecutor<
Body, Allocator, boost::beast::http::string_body>;
using RoutePostDiaryExecutor = PostDiaryExecutor<
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>>;
@@ -50,6 +70,7 @@ private:
const std::shared_ptr<IAuthDAO>& auth_dao_; const std::shared_ptr<IAuthDAO>& auth_dao_;
const std::shared_ptr<IMedicationsDAO>& medications_dao_; const std::shared_ptr<IMedicationsDAO>& medications_dao_;
const std::shared_ptr<IUserTreatmentSchemeDAO>& user_treatment_scheme_dao_; const std::shared_ptr<IUserTreatmentSchemeDAO>& user_treatment_scheme_dao_;
const std::shared_ptr<IDiariesDAO>& diaries_dao_;
public: public:
RootExecutor( RootExecutor(
@@ -57,11 +78,15 @@ public:
const std::shared_ptr<IUserDAO>& user_dao, const std::shared_ptr<IUserDAO>& user_dao,
const std::shared_ptr<IAuthDAO>& auth_dao, const std::shared_ptr<IAuthDAO>& auth_dao,
const std::shared_ptr<IMedicationsDAO>& medications_dao, const std::shared_ptr<IMedicationsDAO>& medications_dao,
const std::shared_ptr<IUserTreatmentSchemeDAO>& user_treatment_scheme_dao const std::shared_ptr<IUserTreatmentSchemeDAO>& user_treatment_scheme_dao,
const std::shared_ptr<IDiariesDAO>& diaries_dao
) : ) :
session_(session), user_dao_(user_dao), session_(session),
auth_dao_(auth_dao), medications_dao_(medications_dao), user_dao_(user_dao),
user_treatment_scheme_dao_(user_treatment_scheme_dao) auth_dao_(auth_dao),
medications_dao_(medications_dao),
user_treatment_scheme_dao_(user_treatment_scheme_dao),
diaries_dao_(diaries_dao)
{ {
routes_pathes_["/api/v1/Auth/Register"] = std::make_unique<RouteController>( routes_pathes_["/api/v1/Auth/Register"] = std::make_unique<RouteController>(
typename RouteController::HTTPMethodsToExecutors{ typename RouteController::HTTPMethodsToExecutors{
@@ -109,7 +134,28 @@ public:
typename RouteController::HTTPMethodsToExecutors{ typename RouteController::HTTPMethodsToExecutors{
{ {
boost::beast::http::verb::get, boost::beast::http::verb::get,
std::make_shared<RouteGetUserTreatmentSchemeExecutor>(session_, auth_dao_, user_treatment_scheme_dao_) std::make_shared<RouteGetUserTreatmentSchemeExecutor>(session_, auth_dao_,
user_treatment_scheme_dao_)
},
{
boost::beast::http::verb::post,
std::make_shared<RoutePostUserTreatmentSchemeExecutor>(session_, auth_dao_,
user_treatment_scheme_dao_)
}
}
);
routes_pathes_["/api/v1/Diaries"] = std::make_unique<RouteController>(
typename RouteController::HTTPMethodsToExecutors{
{
boost::beast::http::verb::get,
std::make_shared<RouteGetDiariesExecutor>(session_, auth_dao_,
diaries_dao_)
},
{
boost::beast::http::verb::post,
std::make_shared<RoutePostDiaryExecutor>(session_, auth_dao_,
diaries_dao_)
}, },
} }
); );
@@ -121,13 +167,14 @@ public:
Send&& send Send&& send
) )
{ {
const std::string& route = req.target(); namespace urls = boost::urls;
const bool is_match_route = routes_pathes_.count(route);
const bool is_match_route = routes_pathes_.count(req.target());
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())
@@ -142,21 +189,50 @@ public:
} }
catch (const session_exception& e) catch (const session_exception& e)
{ {
boost::beast::http::response<ResponseType> res{e.code, req.version()}; return send(SendSessionExceptionError(std::move(req), e));
boost::json::value response_body;
response_body.emplace_object();
response_body.as_object().emplace("Result", e.what());
res.body() = serialize(response_body);
res.set(boost::beast::http::field::content_type, "application/json");
res.content_length(res.body().size());
return send(std::move(res));
} }
} }
} }
urls::url_view parsed_view = urls::parse_uri_reference(req.target()).value();
auto segs = parsed_view.segments();
std::vector<std::string> parts;
for (auto s : segs)
parts.push_back(s);
if (parts.size() == 4 &&
parts[0] == "api" &&
parts[2] == "Diaries")
{
try
{
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));
}
}
if (req.method() != boost::beast::http::verb::get && if (req.method() != boost::beast::http::verb::get &&
req.method() != boost::beast::http::verb::head) req.method() != boost::beast::http::verb::head)
return send(SendBadRequest(std::move(req), "Unknown boost::beast::HTTP-method")); return send(SendBadRequest(std::move(req), "Unknown boost::beast::HTTP-method"));
@@ -253,5 +329,20 @@ private:
res.prepare_payload(); res.prepare_payload();
return res; return res;
} }
StringResponse SendSessionExceptionError(Request&& req, const session_exception& e)
{
StringResponse res{e.code, req.version()};
boost::json::value response_body;
response_body.emplace_object();
response_body.as_object().emplace("Result", e.what());
res.body() = serialize(response_body);
res.set(boost::beast::http::field::content_type, "application/json");
res.content_length(res.body().size());
return res;
}
}; };
} }
+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));