1
0
mirror of https://gitlab.com/MoonTestUse1/AdministrationItDepartmens.git synced 2025-08-14 00:25:46 +02:00

починка уведомлени в тг22

This commit is contained in:
MoonTestUse1
2025-01-04 05:20:56 +06:00
parent 4634262b91
commit cb9a10e36c
9 changed files with 285 additions and 48 deletions

View File

@@ -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])

View File

@@ -49,8 +49,9 @@ async def send_request_notification(request_id: int):
message = (
f"📋 <b>Новая заявка #{request_data['id']}</b>\n\n"
f"📝 <b>Заголовок:</b> {request_data['title']}\n"
f"👤 <b>Сотрудник:</b> {request_data['employee_first_name']} {request_data['employee_last_name']}\n"
f"🏢 <b>Отдел:</b> {request_data['department']}\n"
f"📝 <b>Тип заявки:</b> {request_data['request_type']}\n"
f"❗ <b>Приоритет:</b> {format_priority(request_data['priority'])}\n"
f"📊 <b>Статус:</b> {format_status(request_data['status'])}\n\n"
f"📄 <b>Описание:</b>\n{request_data['description']}\n\n"

View File

@@ -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:

View File

@@ -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;"]
ENTRYPOINT ["/entrypoint.sh"]

75
docker/nginx/default.conf Normal file
View File

@@ -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;
}

View File

@@ -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;"

View File

@@ -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;
}

View File

@@ -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

View File

@@ -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;
}