From cb9a10e36c4fa02439666cd008a16757bd52f39e Mon Sep 17 00:00:00 2001 From: MoonTestUse1 Date: Sat, 4 Jan 2025 05:20:56 +0600 Subject: [PATCH] =?UTF-8?q?=D0=BF=D0=BE=D1=87=D0=B8=D0=BD=D0=BA=D0=B0=20?= =?UTF-8?q?=D1=83=D0=B2=D0=B5=D0=B4=D0=BE=D0=BC=D0=BB=D0=B5=D0=BD=D0=B8=20?= =?UTF-8?q?=D0=B2=20=D1=82=D0=B322?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/routers/requests.py | 5 +- backend/app/utils/telegram.py | 3 +- docker-compose.yml | 18 ++++++- docker/nginx/Dockerfile | 20 +++---- docker/nginx/default.conf | 75 ++++++++++++++++++++++++++ docker/nginx/entrypoint.sh | 53 ++++++++++++++++++ docker/nginx/nginx.conf | 32 ++++++++--- init-letsencrypt.sh | 95 +++++++++++++++++++++++++-------- nginx/default.conf | 32 ++++++++++- 9 files changed, 285 insertions(+), 48 deletions(-) create mode 100644 docker/nginx/default.conf create mode 100644 docker/nginx/entrypoint.sh diff --git a/backend/app/routers/requests.py b/backend/app/routers/requests.py index a6404db..3c5e142 100644 --- a/backend/app/routers/requests.py +++ b/backend/app/routers/requests.py @@ -8,12 +8,11 @@ from ..schemas.request import Request, RequestCreate, RequestUpdate from ..models.request import RequestStatus from ..utils.auth import get_current_employee, get_current_admin from ..utils.telegram import notify_new_request -import asyncio router = APIRouter() @router.post("/", response_model=Request) -def create_request( +async def create_request( request: RequestCreate, db: Session = Depends(get_db), current_employee: dict = Depends(get_current_employee) @@ -21,7 +20,7 @@ def create_request( """Create new request""" db_request = requests.create_request(db, request, current_employee["id"]) # Отправляем уведомление в Telegram - asyncio.create_task(notify_new_request(db_request.id)) + await notify_new_request(db_request.id) return db_request @router.get("/my", response_model=List[Request]) diff --git a/backend/app/utils/telegram.py b/backend/app/utils/telegram.py index 858eeb2..20962d7 100644 --- a/backend/app/utils/telegram.py +++ b/backend/app/utils/telegram.py @@ -49,8 +49,9 @@ async def send_request_notification(request_id: int): message = ( f"📋 Новая заявка #{request_data['id']}\n\n" - f"📝 Заголовок: {request_data['title']}\n" f"👤 Сотрудник: {request_data['employee_first_name']} {request_data['employee_last_name']}\n" + f"🏢 Отдел: {request_data['department']}\n" + f"📝 Тип заявки: {request_data['request_type']}\n" f"❗ Приоритет: {format_priority(request_data['priority'])}\n" f"📊 Статус: {format_status(request_data['status'])}\n\n" f"📄 Описание:\n{request_data['description']}\n\n" diff --git a/docker-compose.yml b/docker-compose.yml index f6b2168..e9feb6e 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,13 +1,27 @@ version: '3.8' services: + nginx: + build: + context: . + dockerfile: docker/nginx/Dockerfile + ports: + - "80:80" + - "443:443" + volumes: + - ./docker/nginx:/etc/nginx/conf.d + - ./letsencrypt:/etc/letsencrypt + - ./certbot-www:/var/www/certbot + depends_on: + - frontend + - backend + restart: always + frontend: container_name: support-frontend build: context: . dockerfile: docker/frontend/Dockerfile - ports: - - "80:80" volumes: - ./frontend:/app depends_on: diff --git a/docker/nginx/Dockerfile b/docker/nginx/Dockerfile index 53005fe..9c40f61 100644 --- a/docker/nginx/Dockerfile +++ b/docker/nginx/Dockerfile @@ -1,14 +1,16 @@ FROM nginx:alpine -# Копируем конфигурацию nginx -COPY docker/nginx/conf.d/default.conf /etc/nginx/conf.d/default.conf +# Установка certbot и зависимостей +RUN apk add --no-cache certbot certbot-nginx openssl -# Копируем собранные файлы фронтенда -COPY frontend/dist /usr/share/nginx/html/ +# Копирование скриптов и конфигурации +COPY ./docker/nginx/nginx.conf /etc/nginx/nginx.conf +COPY ./docker/nginx/default.conf /etc/nginx/conf.d/default.conf +COPY ./docker/nginx/entrypoint.sh /entrypoint.sh -# Удаляем дефолтную страницу nginx -RUN rm -rf /usr/share/nginx/html/50x.html +# Создание директорий для certbot +RUN mkdir -p /var/www/certbot && \ + mkdir -p /etc/letsencrypt && \ + chmod +x /entrypoint.sh -EXPOSE 80 - -CMD ["nginx", "-g", "daemon off;"] \ No newline at end of file +ENTRYPOINT ["/entrypoint.sh"] \ No newline at end of file diff --git a/docker/nginx/default.conf b/docker/nginx/default.conf new file mode 100644 index 0000000..349139b --- /dev/null +++ b/docker/nginx/default.conf @@ -0,0 +1,75 @@ +upstream backend_upstream { + server backend:8000; +} + +upstream frontend_upstream { + server frontend:5173; +} + +# Редирект с HTTP на HTTPS +server { + listen 80; + server_name itformhelp.ru www.itformhelp.ru; + + location /.well-known/acme-challenge/ { + root /var/www/certbot; + } + + location / { + return 301 https://$host$request_uri; + } +} + +# Основной HTTPS сервер +server { + listen 443 ssl http2; + server_name itformhelp.ru www.itformhelp.ru; + + ssl_certificate /etc/letsencrypt/live/itformhelp.ru/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/itformhelp.ru/privkey.pem; + + # Дополнительные настройки SSL + ssl_trusted_certificate /etc/letsencrypt/live/itformhelp.ru/chain.pem; + ssl_stapling on; + ssl_stapling_verify on; + resolver 8.8.8.8 8.8.4.4 valid=300s; + resolver_timeout 5s; + + add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; + add_header X-Frame-Options SAMEORIGIN; + add_header X-Content-Type-Options nosniff; + add_header X-XSS-Protection "1; mode=block"; + + # Frontend proxy + location / { + proxy_pass http://frontend_upstream; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection 'upgrade'; + proxy_set_header Host $host; + proxy_cache_bypass $http_upgrade; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } + + # API proxy + location /api/ { + proxy_pass http://backend_upstream; + proxy_http_version 1.1; + proxy_set_header Upgrade $http_upgrade; + proxy_set_header Connection 'upgrade'; + proxy_set_header Host $host; + proxy_cache_bypass $http_upgrade; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } +} + +# Редирект с IP на домен +server { + listen 80; + server_name 185.139.70.62; + return 301 https://itformhelp.ru$request_uri; +} \ No newline at end of file diff --git a/docker/nginx/entrypoint.sh b/docker/nginx/entrypoint.sh new file mode 100644 index 0000000..5f3971f --- /dev/null +++ b/docker/nginx/entrypoint.sh @@ -0,0 +1,53 @@ +#!/bin/sh + +# Домены для SSL-сертификата +domains="itformhelp.ru www.itformhelp.ru" +email="admin@itformhelp.ru" + +# Функция для получения сертификата +get_certificate() { + echo "Requesting Let's Encrypt certificate for $domains ..." + + # Создаем временный конфиг nginx для валидации certbot + cat > /etc/nginx/conf.d/temp.conf << EOF +server { + listen 80; + server_name $domains; + location /.well-known/acme-challenge/ { + root /var/www/certbot; + } + location / { + return 301 https://\$host\$request_uri; + } +} +EOF + + # Перезапускаем nginx с временным конфигом + nginx -t && nginx -s reload + + # Запрашиваем сертификат + certbot certonly --webroot \ + --webroot-path=/var/www/certbot \ + --email $email \ + --agree-tos \ + --no-eff-email \ + --force-renewal \ + -d $(echo $domains | sed 's/ / -d /g') + + # Удаляем временный конфиг + rm /etc/nginx/conf.d/temp.conf +} + +# Проверяем наличие сертификата +if [ ! -d "/etc/letsencrypt/live/itformhelp.ru" ]; then + get_certificate +fi + +# Запускаем фоновый процесс для автоматического обновления сертификатов +while :; do + certbot renew --deploy-hook "nginx -s reload" + sleep 12h +done & + +# Запускаем nginx +nginx -g "daemon off;" \ No newline at end of file diff --git a/docker/nginx/nginx.conf b/docker/nginx/nginx.conf index 2dc3089..3e2573e 100644 --- a/docker/nginx/nginx.conf +++ b/docker/nginx/nginx.conf @@ -1,25 +1,41 @@ user nginx; worker_processes auto; - -error_log /var/log/nginx/error.log notice; pid /var/run/nginx.pid; events { worker_connections 1024; + multi_accept on; } http { + sendfile on; + tcp_nopush on; + tcp_nodelay on; + keepalive_timeout 65; + types_hash_max_size 2048; + server_tokens off; + include /etc/nginx/mime.types; default_type application/octet-stream; - log_format main '$remote_addr - $remote_user [$time_local] "$request" ' - '$status $body_bytes_sent "$http_referer" ' - '"$http_user_agent" "$http_x_forwarded_for"'; + ssl_protocols TLSv1.2 TLSv1.3; + ssl_prefer_server_ciphers off; + ssl_session_timeout 1d; + ssl_session_cache shared:SSL:50m; + ssl_session_tickets off; + ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384; - access_log /var/log/nginx/access.log main; + access_log /var/log/nginx/access.log; + error_log /var/log/nginx/error.log; - sendfile on; - keepalive_timeout 65; + gzip on; + gzip_disable "msie6"; + gzip_vary on; + gzip_proxied any; + gzip_comp_level 6; + gzip_buffers 16 8k; + gzip_http_version 1.1; + gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; include /etc/nginx/conf.d/*.conf; } diff --git a/init-letsencrypt.sh b/init-letsencrypt.sh index 7dcd132..936127a 100644 --- a/init-letsencrypt.sh +++ b/init-letsencrypt.sh @@ -1,27 +1,76 @@ #!/bin/bash -# Остановить все контейнеры -docker compose down - -# Создать временную директорию для webroot -mkdir -p ./docker/certbot/www - -# Запустить nginx -docker compose up -d frontend - -# Подождать, пока nginx запустится -echo "Waiting for nginx to start..." -sleep 5 - -# Получить тестовый сертификат -docker compose run --rm certbot - -# Если тестовый сертификат получен успешно, получить боевой сертификат -if [ $? -eq 0 ]; then - echo "Test certificate obtained successfully. Getting production certificate..." - docker compose run --rm certbot certonly --webroot --webroot-path=/var/www/html --email admin@itformhelp.ru --agree-tos --no-eff-email --force-renewal -d itformhelp.ru -d www.itformhelp.ru +if ! [ -x "$(command -v docker-compose)" ]; then + echo 'Error: docker-compose is not installed.' >&2 + exit 1 fi -# Перезапустить все сервисы -docker compose down -docker compose up -d +domains=(itformhelp.ru www.itformhelp.ru) +rsa_key_size=4096 +data_path="./certbot" +email="admin@itformhelp.ru" # Измените на свой email + +if [ -d "$data_path" ]; then + read -p "Existing data found for $domains. Continue and replace existing certificate? (y/N) " decision + if [ "$decision" != "Y" ] && [ "$decision" != "y" ]; then + exit + fi +fi + +if [ ! -e "$data_path/conf/options-ssl-nginx.conf" ] || [ ! -e "$data_path/conf/ssl-dhparams.pem" ]; then + echo "### Downloading recommended TLS parameters ..." + mkdir -p "$data_path/conf" + curl -s https://raw.githubusercontent.com/certbot/certbot/master/certbot-nginx/certbot_nginx/_internal/tls_configs/options-ssl-nginx.conf > "$data_path/conf/options-ssl-nginx.conf" + curl -s https://raw.githubusercontent.com/certbot/certbot/master/certbot/certbot/ssl-dhparams.pem > "$data_path/conf/ssl-dhparams.pem" + echo +fi + +echo "### Creating dummy certificate for $domains ..." +path="/etc/letsencrypt/live/$domains" +mkdir -p "$data_path/conf/live/$domains" +docker-compose run --rm --entrypoint "\ + openssl req -x509 -nodes -newkey rsa:$rsa_key_size -days 1\ + -keyout '$path/privkey.pem' \ + -out '$path/fullchain.pem' \ + -subj '/CN=localhost'" certbot +echo + +echo "### Starting nginx ..." +docker-compose up --force-recreate -d nginx +echo + +echo "### Deleting dummy certificate for $domains ..." +docker-compose run --rm --entrypoint "\ + rm -Rf /etc/letsencrypt/live/$domains && \ + rm -Rf /etc/letsencrypt/archive/$domains && \ + rm -Rf /etc/letsencrypt/renewal/$domains.conf" certbot +echo + +echo "### Requesting Let's Encrypt certificate for $domains ..." +#Join $domains to -d args +domain_args="" +for domain in "${domains[@]}"; do + domain_args="$domain_args -d $domain" +done + +# Select appropriate email arg +case "$email" in + "") email_arg="--register-unsafely-without-email" ;; + *) email_arg="--email $email" ;; +esac + +# Enable staging mode if needed +if [ $staging != "0" ]; then staging_arg="--staging"; fi + +docker-compose run --rm --entrypoint "\ + certbot certonly --webroot -w /var/www/certbot \ + $staging_arg \ + $email_arg \ + $domain_args \ + --rsa-key-size $rsa_key_size \ + --agree-tos \ + --force-renewal" certbot +echo + +echo "### Reloading nginx ..." +docker-compose exec nginx nginx -s reload diff --git a/nginx/default.conf b/nginx/default.conf index b5cb991..d033479 100644 --- a/nginx/default.conf +++ b/nginx/default.conf @@ -6,9 +6,37 @@ upstream frontend_upstream { server administrationitdepartmens-frontend-1:5173; } +# Редирект с HTTP на HTTPS server { - listen 80 default_server; + listen 80; server_name itformhelp.ru www.itformhelp.ru; + + location /.well-known/acme-challenge/ { + root /var/www/certbot; + } + + location / { + return 301 https://$host$request_uri; + } +} + +# Основной HTTPS сервер +server { + listen 443 ssl; + server_name itformhelp.ru www.itformhelp.ru; + + ssl_certificate /etc/letsencrypt/live/itformhelp.ru/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/itformhelp.ru/privkey.pem; + + # Рекомендуемые настройки SSL + ssl_protocols TLSv1.2 TLSv1.3; + ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384; + ssl_prefer_server_ciphers off; + ssl_session_timeout 1d; + ssl_session_cache shared:SSL:50m; + ssl_stapling on; + ssl_stapling_verify on; + add_header Strict-Transport-Security "max-age=31536000" always; root /usr/share/nginx/html; index index.html; @@ -48,5 +76,5 @@ server { server { listen 80; server_name 185.139.70.62; - return 301 http://itformhelp.ru$request_uri; + return 301 https://itformhelp.ru$request_uri; } \ No newline at end of file