mirror of
https://gitlab.com/MoonTestUse1/AdministrationItDepartmens.git
synced 2025-08-14 00:25:46 +02:00
Fix database
This commit is contained in:
@@ -3,11 +3,11 @@ from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||
from passlib.context import CryptContext
|
||||
from sqlalchemy.orm import Session
|
||||
import re
|
||||
|
||||
from .jwt import verify_token
|
||||
from ..database import get_db
|
||||
from ..crud import employees
|
||||
from ..models.employee import Employee
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
security = HTTPBearer(auto_error=False)
|
||||
@@ -23,7 +23,7 @@ def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
def get_current_admin(
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
db: Session = Depends(get_db)
|
||||
) -> dict:
|
||||
) -> Employee:
|
||||
"""Get current admin from token"""
|
||||
if not credentials:
|
||||
raise HTTPException(
|
||||
@@ -34,11 +34,16 @@ def get_current_admin(
|
||||
|
||||
try:
|
||||
token = credentials.credentials
|
||||
payload = verify_token(token, db)
|
||||
employee_id = int(payload.get("sub"))
|
||||
token_data = verify_token(token, db)
|
||||
if not token_data:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid authentication credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
# Проверяем, что это админ
|
||||
employee = employees.get_employee(db, employee_id)
|
||||
employee = employees.get_employee(db, token_data.employee_id)
|
||||
if not employee or not employee.is_admin:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
@@ -47,7 +52,7 @@ def get_current_admin(
|
||||
)
|
||||
|
||||
return employee
|
||||
except Exception as e:
|
||||
except Exception:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid authentication credentials",
|
||||
@@ -57,7 +62,7 @@ def get_current_admin(
|
||||
def get_current_employee(
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
db: Session = Depends(get_db)
|
||||
) -> dict:
|
||||
) -> Employee:
|
||||
"""Get current employee from token"""
|
||||
if not credentials:
|
||||
raise HTTPException(
|
||||
@@ -68,11 +73,16 @@ def get_current_employee(
|
||||
|
||||
try:
|
||||
token = credentials.credentials
|
||||
payload = verify_token(token, db)
|
||||
employee_id = int(payload.get("sub"))
|
||||
token_data = verify_token(token, db)
|
||||
if not token_data:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid authentication credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
# Проверяем существование сотрудника
|
||||
employee = employees.get_employee(db, employee_id)
|
||||
employee = employees.get_employee(db, token_data.employee_id)
|
||||
if not employee:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
|
@@ -2,9 +2,11 @@
|
||||
from datetime import datetime, timedelta
|
||||
from jose import JWTError, jwt
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import Optional
|
||||
|
||||
from ..core.config import settings
|
||||
from ..models.token import Token
|
||||
from ..schemas.auth import TokenData
|
||||
|
||||
def create_access_token(data: dict) -> str:
|
||||
"""Create access token"""
|
||||
@@ -14,13 +16,22 @@ def create_access_token(data: dict) -> str:
|
||||
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
||||
return encoded_jwt
|
||||
|
||||
def verify_token(token: str, db: Session) -> dict:
|
||||
def verify_token(token: str, db: Session) -> Optional[TokenData]:
|
||||
"""Verify token"""
|
||||
try:
|
||||
# Проверяем, что токен действителен
|
||||
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
|
||||
return payload
|
||||
except JWTError:
|
||||
employee_id = int(payload.get("sub"))
|
||||
if employee_id is None:
|
||||
return None
|
||||
|
||||
# Проверяем, что токен существует в базе
|
||||
db_token = db.query(Token).filter(Token.token == token).first()
|
||||
if not db_token:
|
||||
return None
|
||||
|
||||
return TokenData(employee_id=employee_id)
|
||||
except (JWTError, ValueError):
|
||||
return None
|
||||
|
||||
def create_and_save_token(employee_id: int, db: Session) -> str:
|
||||
|
@@ -3,20 +3,17 @@ from aiogram import Bot
|
||||
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
|
||||
import asyncio
|
||||
from datetime import datetime
|
||||
import os
|
||||
from logging import getLogger
|
||||
from ..models.request import RequestStatus, RequestPriority
|
||||
from ..crud import requests
|
||||
from ..database import get_db
|
||||
from ..core.config import settings
|
||||
|
||||
# Initialize logger
|
||||
logger = getLogger(__name__)
|
||||
|
||||
# Initialize bot with token
|
||||
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "7677506032:AAHduD5EePz3bE23DKlo35KoOp2_9lZuS34")
|
||||
TELEGRAM_CHAT_ID = os.getenv("TELEGRAM_CHAT_ID", "5057752127")
|
||||
|
||||
bot = Bot(token=TELEGRAM_BOT_TOKEN)
|
||||
# Initialize bot with token from settings
|
||||
bot = Bot(token=settings.TELEGRAM_BOT_TOKEN)
|
||||
|
||||
def format_priority(priority: str) -> str:
|
||||
"""Format priority with emoji"""
|
||||
@@ -59,7 +56,7 @@ async def send_request_notification(request_id: int):
|
||||
)
|
||||
|
||||
await bot.send_message(
|
||||
chat_id=TELEGRAM_CHAT_ID,
|
||||
chat_id=settings.TELEGRAM_CHAT_ID,
|
||||
text=message,
|
||||
parse_mode="HTML"
|
||||
)
|
||||
|
Reference in New Issue
Block a user