mirror of
https://gitlab.com/MoonTestUse1/AdministrationItDepartmens.git
synced 2025-08-14 00:25:46 +02:00
testing pipe
This commit is contained in:
55
backend/app/api/endpoints/auth.py
Normal file
55
backend/app/api/endpoints/auth.py
Normal file
@@ -0,0 +1,55 @@
|
||||
"""Authentication endpoints."""
|
||||
from datetime import timedelta
|
||||
from typing import Any
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordRequestForm
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.auth import (
|
||||
authenticate_user,
|
||||
create_access_token,
|
||||
get_current_user
|
||||
)
|
||||
from app.database import get_db
|
||||
from app.core.config import settings
|
||||
from app.models.user import User
|
||||
from app.schemas.token import Token
|
||||
from app.schemas.user import User as UserSchema
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.post("/login", response_model=Token)
|
||||
def login(
|
||||
db: Session = Depends(get_db),
|
||||
form_data: OAuth2PasswordRequestForm = Depends()
|
||||
) -> Any:
|
||||
"""OAuth2 compatible token login, get an access token for future requests."""
|
||||
user = authenticate_user(db, form_data.username, form_data.password)
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Incorrect email or password",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
elif not user.is_active:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Inactive user"
|
||||
)
|
||||
|
||||
access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
access_token = create_access_token(
|
||||
data={"sub": user.email, "is_admin": user.is_admin},
|
||||
expires_delta=access_token_expires
|
||||
)
|
||||
|
||||
return {
|
||||
"access_token": access_token,
|
||||
"token_type": "bearer"
|
||||
}
|
||||
|
||||
@router.get("/me", response_model=UserSchema)
|
||||
def read_users_me(current_user: User = Depends(get_current_user)):
|
||||
"""Get current user."""
|
||||
return current_user
|
||||
|
||||
@@ -13,19 +13,20 @@ def get_employee(db: Session, employee_id: int) -> Optional[Employee]:
|
||||
"""Get employee by ID"""
|
||||
return db.query(Employee).filter(Employee.id == employee_id).first()
|
||||
|
||||
def get_employee_by_last_name(db: Session, last_name: str) -> Optional[Employee]:
|
||||
"""Get employee by last name"""
|
||||
return db.query(Employee).filter(Employee.last_name == last_name).first()
|
||||
def get_employee_by_email(db: Session, email: str) -> Optional[Employee]:
|
||||
"""Get employee by email"""
|
||||
return db.query(Employee).filter(Employee.email == email).first()
|
||||
|
||||
def create_employee(db: Session, employee: EmployeeCreate, hashed_password: str) -> Employee:
|
||||
"""Create new employee"""
|
||||
try:
|
||||
db_employee = Employee(
|
||||
first_name=employee.first_name,
|
||||
last_name=employee.last_name,
|
||||
department=employee.department,
|
||||
office=employee.office,
|
||||
hashed_password=hashed_password
|
||||
email=employee.email,
|
||||
full_name=employee.full_name,
|
||||
hashed_password=hashed_password,
|
||||
is_active=employee.is_active,
|
||||
is_admin=employee.is_admin,
|
||||
department=employee.department
|
||||
)
|
||||
db.add(db_employee)
|
||||
db.commit()
|
||||
|
||||
@@ -48,8 +48,7 @@ def get_request_details(db: Session, request_id: int) -> Optional[Dict]:
|
||||
"status": request.status,
|
||||
"department": request.department,
|
||||
"created_at": request.created_at.isoformat(),
|
||||
"employee_first_name": employee.first_name,
|
||||
"employee_last_name": employee.last_name
|
||||
"employee_full_name": employee.full_name
|
||||
}
|
||||
|
||||
def get_employee_requests(db: Session, employee_id: int) -> list[Request]:
|
||||
@@ -81,6 +80,12 @@ def get_statistics(db: Session) -> Dict:
|
||||
func.count(Request.id)
|
||||
).group_by(Request.status).all()
|
||||
)
|
||||
|
||||
# Добавляем статусы с нулевым количеством
|
||||
for status in RequestStatus:
|
||||
if status not in by_status:
|
||||
by_status[status] = 0
|
||||
|
||||
return {
|
||||
"total": total,
|
||||
"by_status": by_status
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"""Employee model"""
|
||||
from sqlalchemy import Column, Integer, String, DateTime
|
||||
from sqlalchemy import Column, Integer, String, DateTime, Boolean
|
||||
from sqlalchemy.sql import func
|
||||
from sqlalchemy.orm import relationship
|
||||
from app.db.base_class import Base
|
||||
@@ -8,12 +8,13 @@ class Employee(Base):
|
||||
__tablename__ = "employees"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
first_name = Column(String, nullable=False)
|
||||
last_name = Column(String, nullable=False)
|
||||
department = Column(String, nullable=False)
|
||||
office = Column(String, nullable=False)
|
||||
email = Column(String, unique=True, index=True, nullable=False)
|
||||
full_name = Column(String, nullable=False)
|
||||
hashed_password = Column(String, nullable=False)
|
||||
is_active = Column(Boolean, default=True)
|
||||
is_admin = Column(Boolean, default=False)
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
department = Column(String, nullable=True)
|
||||
|
||||
# Определяем отношение к Request
|
||||
requests = relationship("Request", back_populates="employee", cascade="all, delete-orphan")
|
||||
@@ -8,5 +8,5 @@ class Token(Base):
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
token = Column(String, unique=True, index=True)
|
||||
user_id = Column(Integer, index=True) # -1 для админа, остальные для сотрудников
|
||||
user_id = Column(Integer, index=True) # ID сотрудника из таблицы employees
|
||||
created_at = Column(DateTime(timezone=True), server_default=func.now())
|
||||
@@ -18,8 +18,9 @@ async def login_for_access_token(
|
||||
form_data: OAuth2PasswordRequestForm = Depends(),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Авторизация сотрудника"""
|
||||
# Проверяем учетные данные сотрудника
|
||||
employee = employees.get_employee_by_last_name(db, form_data.username)
|
||||
employee = employees.get_employee_by_email(db, form_data.username)
|
||||
if not employee or not verify_password(form_data.password, employee.hashed_password):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
@@ -40,17 +41,18 @@ async def admin_login(
|
||||
form_data: OAuth2PasswordRequestForm = Depends(),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Авторизация администратора"""
|
||||
# Проверяем учетные данные администратора
|
||||
if form_data.username != "admin" or form_data.password != "admin123":
|
||||
employee = employees.get_employee_by_email(db, form_data.username)
|
||||
if not employee or not employee.is_admin or not verify_password(form_data.password, employee.hashed_password):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Incorrect username or password",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
# Для админа используем специальный ID
|
||||
admin_id = -1
|
||||
access_token = create_and_save_token(admin_id, db)
|
||||
# Создаем и сохраняем токен
|
||||
access_token = create_and_save_token(employee.id, db)
|
||||
|
||||
return {
|
||||
"access_token": access_token,
|
||||
|
||||
@@ -5,19 +5,21 @@ from typing import List
|
||||
import logging
|
||||
from ..database import get_db
|
||||
from ..crud import employees
|
||||
from ..schemas.employee import Employee, EmployeeCreate, EmployeeUpdate
|
||||
from ..utils.auth import get_current_admin, get_password_hash
|
||||
from ..schemas.employee import Employee as EmployeeSchema
|
||||
from ..schemas.employee import EmployeeCreate, EmployeeUpdate
|
||||
from ..models.employee import Employee
|
||||
from ..utils.auth import get_current_admin, get_current_employee, get_password_hash
|
||||
|
||||
# Настройка логирования
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter(tags=["employees"])
|
||||
|
||||
@router.post("", response_model=Employee, status_code=status.HTTP_201_CREATED)
|
||||
@router.post("", response_model=EmployeeSchema, status_code=status.HTTP_201_CREATED)
|
||||
async def create_employee(
|
||||
employee: EmployeeCreate,
|
||||
db: Session = Depends(get_db),
|
||||
_: dict = Depends(get_current_admin)
|
||||
current_admin: Employee = Depends(get_current_admin)
|
||||
):
|
||||
"""Create new employee"""
|
||||
try:
|
||||
@@ -31,12 +33,12 @@ async def create_employee(
|
||||
detail="Error creating employee"
|
||||
)
|
||||
|
||||
@router.get("", response_model=List[Employee])
|
||||
@router.get("", response_model=List[EmployeeSchema])
|
||||
async def get_employees(
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
db: Session = Depends(get_db),
|
||||
_: dict = Depends(get_current_admin)
|
||||
current_admin: Employee = Depends(get_current_admin)
|
||||
):
|
||||
"""Get all employees"""
|
||||
try:
|
||||
@@ -49,11 +51,40 @@ async def get_employees(
|
||||
detail="Error getting employees"
|
||||
)
|
||||
|
||||
@router.get("/{employee_id}", response_model=Employee)
|
||||
@router.get("/me", response_model=EmployeeSchema)
|
||||
async def get_me(
|
||||
current_employee: Employee = Depends(get_current_employee)
|
||||
):
|
||||
"""Get current employee"""
|
||||
return current_employee
|
||||
|
||||
@router.put("/me", response_model=EmployeeSchema)
|
||||
async def update_me(
|
||||
employee: EmployeeUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_employee: Employee = Depends(get_current_employee)
|
||||
):
|
||||
"""Update current employee data"""
|
||||
try:
|
||||
logger.info(f"Updating employee {current_employee.id}: {employee}")
|
||||
db_employee = employees.update_employee(db, current_employee.id, employee)
|
||||
if db_employee is None:
|
||||
raise HTTPException(status_code=404, detail="Employee not found")
|
||||
return db_employee
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error updating employee: {e}")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail="Error updating employee"
|
||||
)
|
||||
|
||||
@router.get("/{employee_id}", response_model=EmployeeSchema)
|
||||
async def get_employee(
|
||||
employee_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
_: dict = Depends(get_current_admin)
|
||||
current_admin: Employee = Depends(get_current_admin)
|
||||
):
|
||||
"""Get employee by ID"""
|
||||
try:
|
||||
@@ -71,12 +102,12 @@ async def get_employee(
|
||||
detail="Error getting employee"
|
||||
)
|
||||
|
||||
@router.put("/{employee_id}", response_model=Employee)
|
||||
@router.put("/{employee_id}", response_model=EmployeeSchema)
|
||||
async def update_employee(
|
||||
employee_id: int,
|
||||
employee: EmployeeUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
_: dict = Depends(get_current_admin)
|
||||
current_admin: Employee = Depends(get_current_admin)
|
||||
):
|
||||
"""Update employee data"""
|
||||
try:
|
||||
@@ -94,11 +125,11 @@ async def update_employee(
|
||||
detail="Error updating employee"
|
||||
)
|
||||
|
||||
@router.delete("/{employee_id}", response_model=Employee)
|
||||
@router.delete("/{employee_id}", response_model=EmployeeSchema)
|
||||
async def delete_employee(
|
||||
employee_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
_: dict = Depends(get_current_admin)
|
||||
current_admin: Employee = Depends(get_current_admin)
|
||||
):
|
||||
"""Delete employee"""
|
||||
try:
|
||||
|
||||
@@ -6,19 +6,20 @@ from ..database import get_db
|
||||
from ..crud import requests
|
||||
from ..schemas.request import Request, RequestCreate, RequestUpdate
|
||||
from ..models.request import RequestStatus
|
||||
from ..models.employee import Employee
|
||||
from ..utils.auth import get_current_employee, get_current_admin
|
||||
from ..utils.telegram import notify_new_request
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.post("/", response_model=Request)
|
||||
@router.post("/", response_model=Request, status_code=201)
|
||||
async def create_request(
|
||||
request: RequestCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_employee: dict = Depends(get_current_employee)
|
||||
current_employee: Employee = Depends(get_current_employee)
|
||||
):
|
||||
"""Create new request"""
|
||||
db_request = requests.create_request(db, request, current_employee["id"])
|
||||
db_request = requests.create_request(db, request, current_employee.id)
|
||||
# Отправляем уведомление в Telegram
|
||||
await notify_new_request(db_request.id)
|
||||
return db_request
|
||||
@@ -26,10 +27,10 @@ async def create_request(
|
||||
@router.get("/my", response_model=List[Request])
|
||||
def get_employee_requests(
|
||||
db: Session = Depends(get_db),
|
||||
current_employee: dict = Depends(get_current_employee)
|
||||
current_employee: Employee = Depends(get_current_employee)
|
||||
):
|
||||
"""Get current employee's requests"""
|
||||
return requests.get_employee_requests(db, current_employee["id"])
|
||||
return requests.get_employee_requests(db, current_employee.id)
|
||||
|
||||
@router.get("/admin", response_model=List[Request])
|
||||
def get_all_requests(
|
||||
@@ -37,7 +38,7 @@ def get_all_requests(
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
db: Session = Depends(get_db),
|
||||
_: dict = Depends(get_current_admin)
|
||||
current_admin: Employee = Depends(get_current_admin)
|
||||
):
|
||||
"""Get all requests (admin only)"""
|
||||
return requests.get_requests(db, status=status, skip=skip, limit=limit)
|
||||
@@ -47,9 +48,15 @@ def update_request_status(
|
||||
request_id: int,
|
||||
request_update: RequestUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
_: dict = Depends(get_current_admin)
|
||||
current_employee: Employee = Depends(get_current_employee)
|
||||
):
|
||||
"""Update request status (admin only)"""
|
||||
if not current_employee.is_admin:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Not enough permissions"
|
||||
)
|
||||
|
||||
db_request = requests.update_request_status(db, request_id, request_update.status)
|
||||
if db_request is None:
|
||||
raise HTTPException(status_code=404, detail="Request not found")
|
||||
@@ -58,14 +65,11 @@ def update_request_status(
|
||||
@router.get("/statistics")
|
||||
def get_request_statistics(
|
||||
db: Session = Depends(get_db),
|
||||
_: dict = Depends(get_current_admin)
|
||||
current_admin: Employee = Depends(get_current_admin)
|
||||
):
|
||||
"""Get request statistics (admin only)"""
|
||||
stats = requests.get_statistics(db)
|
||||
return {
|
||||
"total": stats["total"],
|
||||
"by_status": {
|
||||
status: count
|
||||
for status, count in stats["by_status"].items()
|
||||
}
|
||||
"by_status": stats["by_status"]
|
||||
}
|
||||
@@ -2,7 +2,8 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
from ..database import get_db
|
||||
from ..crud import statistics
|
||||
from ..crud import requests
|
||||
from ..models.employee import Employee
|
||||
from ..utils.auth import get_current_admin
|
||||
|
||||
router = APIRouter()
|
||||
@@ -10,7 +11,11 @@ router = APIRouter()
|
||||
@router.get("/")
|
||||
def get_statistics(
|
||||
db: Session = Depends(get_db),
|
||||
_: dict = Depends(get_current_admin)
|
||||
current_admin: Employee = Depends(get_current_admin)
|
||||
):
|
||||
"""Get system statistics"""
|
||||
return statistics.get_request_statistics(db)
|
||||
"""Get request statistics (admin only)"""
|
||||
stats = requests.get_statistics(db)
|
||||
return {
|
||||
"total": stats["total"],
|
||||
"by_status": stats["by_status"]
|
||||
}
|
||||
@@ -4,21 +4,26 @@ from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
class EmployeeBase(BaseModel):
|
||||
first_name: str
|
||||
last_name: str
|
||||
email: str
|
||||
full_name: str
|
||||
department: str
|
||||
office: str
|
||||
is_active: bool = True
|
||||
is_admin: bool = False
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
class EmployeeCreate(EmployeeBase):
|
||||
password: str
|
||||
|
||||
class EmployeeUpdate(EmployeeBase):
|
||||
first_name: Optional[str] = None
|
||||
last_name: Optional[str] = None
|
||||
class EmployeeUpdate(BaseModel):
|
||||
email: Optional[str] = None
|
||||
full_name: Optional[str] = None
|
||||
department: Optional[str] = None
|
||||
office: Optional[str] = None
|
||||
password: Optional[str] = None
|
||||
is_active: Optional[bool] = None
|
||||
is_admin: Optional[bool] = None
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
class Employee(EmployeeBase):
|
||||
id: int
|
||||
|
||||
@@ -23,7 +23,7 @@ class Request(RequestBase):
|
||||
id: int
|
||||
status: RequestStatus
|
||||
employee_id: int
|
||||
department: str
|
||||
department: Optional[str] = None
|
||||
created_at: datetime
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
@@ -7,6 +7,7 @@ import re
|
||||
|
||||
from .jwt import verify_token
|
||||
from ..database import get_db
|
||||
from ..models.employee import Employee
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
security = HTTPBearer(auto_error=False)
|
||||
@@ -22,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(
|
||||
@@ -36,26 +37,28 @@ def get_current_admin(
|
||||
payload = verify_token(token, db)
|
||||
employee_id = int(payload.get("sub"))
|
||||
|
||||
# Проверяем, что это админ (id = -1)
|
||||
if employee_id != -1:
|
||||
# Получаем сотрудника из БД
|
||||
from ..crud.employees import get_employee
|
||||
employee = get_employee(db, employee_id)
|
||||
if not employee or not employee.is_admin:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Not an admin",
|
||||
detail="Could not validate credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
return {"is_admin": True}
|
||||
except Exception as e:
|
||||
return employee
|
||||
except Exception:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid authentication credentials",
|
||||
detail="Could not validate credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
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(
|
||||
@@ -69,18 +72,20 @@ def get_current_employee(
|
||||
payload = verify_token(token, db)
|
||||
employee_id = int(payload.get("sub"))
|
||||
|
||||
# Проверяем, что это не админ
|
||||
if employee_id == -1:
|
||||
# Получаем сотрудника из БД
|
||||
from ..crud.employees import get_employee
|
||||
employee = get_employee(db, employee_id)
|
||||
if not employee:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Admin cannot access employee endpoints",
|
||||
detail="Could not validate credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
return {"id": employee_id}
|
||||
return employee
|
||||
except Exception:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid authentication credentials",
|
||||
detail="Could not validate credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
@@ -35,18 +35,9 @@ def verify_token(token: str, db: Session) -> dict:
|
||||
|
||||
# Проверяем токен в Redis
|
||||
if not redis.get(f"token:{token}"):
|
||||
# Если токена нет в Redis, проверяем в БД
|
||||
db_token = db.query(Token).filter(Token.token == token).first()
|
||||
if not db_token:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Token is invalid",
|
||||
)
|
||||
# Если токен валиден, кэшируем его в Redis
|
||||
redis.setex(
|
||||
f"token:{token}",
|
||||
timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES),
|
||||
"valid"
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Could not validate credentials",
|
||||
)
|
||||
|
||||
return payload
|
||||
|
||||
Reference in New Issue
Block a user