Compare commits
3 Commits
d5f9d3be49
...
295c1f68e0
| Author | SHA1 | Date | |
|---|---|---|---|
| 295c1f68e0 | |||
| cec3bcb500 | |||
| b296f786ec |
@ -1,7 +1,11 @@
|
||||
import pika
|
||||
from config import RABBITMQ_HOST, RABBITMQ_PORT, RABBITMQ_LOGIN, RABBITMQ_PASS, RABBITMQ_QUEUE
|
||||
import time
|
||||
|
||||
import pika
|
||||
from pika.exceptions import ChannelClosedByBroker, ConnectionClosed, AMQPConnectionError
|
||||
|
||||
from config import RABBITMQ_HOST, RABBITMQ_PORT, RABBITMQ_LOGIN, RABBITMQ_PASS, RABBITMQ_QUEUE
|
||||
|
||||
|
||||
class RabbitMQClient:
|
||||
def __init__(self):
|
||||
self._connect()
|
||||
@ -31,9 +35,9 @@ class RabbitMQClient:
|
||||
delivery_mode=2,
|
||||
)
|
||||
)
|
||||
except (pika.exceptions.ChannelClosedByBroker,
|
||||
pika.exceptions.ConnectionClosed,
|
||||
pika.exceptions.AMQPConnectionError) as e:
|
||||
except (ChannelClosedByBroker,
|
||||
ConnectionClosed,
|
||||
AMQPConnectionError) as e:
|
||||
if retry > 0:
|
||||
# Короткая пауза перед переподключением
|
||||
time.sleep(1)
|
||||
|
||||
@ -1,11 +1,10 @@
|
||||
from flask import Blueprint, render_template, request, redirect, url_for, flash, session, current_app
|
||||
from flask import Blueprint, render_template, request, redirect, url_for, flash, session
|
||||
from flask_login import login_user, login_required, logout_user
|
||||
|
||||
from app.extensions.db import db
|
||||
from app.extensions.audit_logger import AuditLogger
|
||||
from app.services.auth_service import authenticate_user, parse_ldap_user
|
||||
from app.extensions.db import db
|
||||
from app.models import User
|
||||
|
||||
from app.services.auth_service import authenticate_user, parse_ldap_user
|
||||
|
||||
auditlog = AuditLogger(db.session)
|
||||
|
||||
@ -25,7 +24,11 @@ def login():
|
||||
if not success:
|
||||
flash(error, 'danger')
|
||||
auditlog.auth(username_attempted=username, success=False, error=error)
|
||||
return render_template("login.html")
|
||||
session['login_username'] = username # сохраняем введённый логин
|
||||
return redirect(url_for('auth.login')) # редирект вместо render_template
|
||||
|
||||
# Очистка сохранённого логина при успешном входе
|
||||
session.pop('login_username', None)
|
||||
|
||||
data = parse_ldap_user(user_info)
|
||||
display_name = (f"{data['user_surname']} {data['user_name']} {data['user_middle_name']}").strip()
|
||||
@ -48,7 +51,10 @@ def login():
|
||||
flash("Logged in successfully!", "success")
|
||||
return redirect(url_for("dashboard.dashboard"))
|
||||
|
||||
return render_template("login.html")
|
||||
# GET-запрос — передаём в шаблон ранее введённый логин, если есть
|
||||
username_prefill = session.pop('login_username', '')
|
||||
return render_template("login.html", username=username_prefill)
|
||||
|
||||
|
||||
|
||||
@auth_bp.route('/logout')
|
||||
|
||||
@ -1,28 +0,0 @@
|
||||
# from utilities.notification_manager import NotificationManager
|
||||
# from utilities.telegram_utilities import extract_region_number, format_message
|
||||
# from flask import current_app
|
||||
#
|
||||
#
|
||||
#
|
||||
# class NotificationService:
|
||||
# def __init__(self):
|
||||
# self.logger = current_app.logger
|
||||
# self.manager = NotificationManager(self.logger)
|
||||
#
|
||||
# def process_notification(self, data):
|
||||
# self.logger.info(f"Получены данные уведомления: {data}")
|
||||
#
|
||||
# region_id = extract_region_number(data.get("host"))
|
||||
# if region_id is None:
|
||||
# self.logger.error(f"Не удалось извлечь номер региона из host: {data.get('host')}")
|
||||
# return {"status": "error", "message": "Invalid host format"}, 400
|
||||
#
|
||||
# self.logger.debug(f"Извлечён номер региона: {region_id}")
|
||||
#
|
||||
# subscribers = self.manager.get_subscribers(region_id, data['severity'])
|
||||
#
|
||||
# if self.manager.is_region_active(region_id):
|
||||
# message = format_message(data)
|
||||
# self.manager.send_notifications(subscribers, message)
|
||||
#
|
||||
# return {"status": "success"}, 200
|
||||
@ -1,86 +0,0 @@
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from app import app, Users
|
||||
import aio_pika
|
||||
import pika
|
||||
|
||||
from config import RABBITMQ_LOGIN, RABBITMQ_PASS, RABBITMQ_HOST, RABBITMQ_QUEUE, RABBITMQ_URL_FULL
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
rate_limit_semaphore = asyncio.Semaphore(25)
|
||||
|
||||
def rabbitmq_connection():
|
||||
credentials = pika.PlainCredentials(RABBITMQ_LOGIN, RABBITMQ_PASS)
|
||||
parameters = pika.ConnectionParameters(
|
||||
host=RABBITMQ_HOST,
|
||||
credentials=credentials,
|
||||
heartbeat=600,
|
||||
blocked_connection_timeout=300
|
||||
)
|
||||
connection = pika.BlockingConnection(parameters)
|
||||
channel = connection.channel()
|
||||
channel.queue_declare(queue=RABBITMQ_QUEUE, durable=True)
|
||||
return connection, channel
|
||||
|
||||
def send_to_queue(message):
|
||||
connection, channel = rabbitmq_connection()
|
||||
channel.basic_publish(
|
||||
exchange='',
|
||||
routing_key=RABBITMQ_QUEUE,
|
||||
body=json.dumps(message),
|
||||
properties=pika.BasicProperties(
|
||||
delivery_mode=2,
|
||||
))
|
||||
connection.close()
|
||||
|
||||
async def send_message(chat_id, message, backend_bot, is_notification=False):
|
||||
telegram_id = "unknown"
|
||||
try:
|
||||
if is_notification:
|
||||
await rate_limit_semaphore.acquire()
|
||||
|
||||
def get_user():
|
||||
with app.app_context():
|
||||
user = Users.query.get(chat_id)
|
||||
return user.telegram_id if user else "unknown"
|
||||
|
||||
telegram_id = await asyncio.to_thread(get_user)
|
||||
|
||||
await asyncio.to_thread(backend_bot.bot.send_message, chat_id, message, parse_mode='HTML')
|
||||
|
||||
formatted_message = message.replace('\n', ' ').replace('\r', '')
|
||||
logger.info(f'Send notification to {telegram_id} ({chat_id}) from RabbitMQ [{formatted_message}]')
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error sending message to {telegram_id} ({chat_id}): {e}")
|
||||
finally:
|
||||
if is_notification:
|
||||
rate_limit_semaphore.release()
|
||||
|
||||
async def consume_from_queue(backend_bot):
|
||||
while True:
|
||||
try:
|
||||
connection = await aio_pika.connect_robust(RABBITMQ_URL_FULL)
|
||||
async with connection:
|
||||
channel = await connection.channel()
|
||||
queue = await channel.declare_queue(RABBITMQ_QUEUE, durable=True)
|
||||
|
||||
async for message in queue:
|
||||
async with message.process():
|
||||
try:
|
||||
data = json.loads(message.body.decode('utf-8'))
|
||||
chat_id = data["chat_id"]
|
||||
message_text = data["message"]
|
||||
await send_message(chat_id, message_text, backend_bot, is_notification=True)
|
||||
except (json.JSONDecodeError, KeyError) as e:
|
||||
logger.error(f"Error processing message: {e}")
|
||||
except Exception as e:
|
||||
logger.error(f"Error sending message: {e}")
|
||||
except aio_pika.exceptions.AMQPError as e:
|
||||
logger.error(f"RabbitMQ error: {e}")
|
||||
except Exception as e:
|
||||
logger.error(f"Critical error: {e}")
|
||||
finally:
|
||||
await asyncio.sleep(5)
|
||||
@ -84,7 +84,7 @@
|
||||
<div id="formContent">
|
||||
<!-- Форма входа -->
|
||||
<form method="POST" action="{{ url_for('auth.login') }}">
|
||||
<input type="text" id="username" class="fadeIn second form-control text-center" name="username" placeholder="Имя пользователя" required>
|
||||
<input type="text" id="username" class="fadeIn second form-control text-center" name="username" value="{{ username|default('') }}" placeholder="Имя пользователя" required>
|
||||
<input type="password" id="password" class="fadeIn third form-control text-center" name="password" placeholder="Пароль" required>
|
||||
<input type="submit" class="fadeIn fourth btn btn-primary w-100 mt-3" value="Войти">
|
||||
</form>
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user