Compare commits
3 Commits
9ab99aa7e4
...
main
Author | SHA1 | Date | |
---|---|---|---|
b83bd87c68 | |||
eb7227bdc2 | |||
f7b3081893 |
9
auth.py
9
auth.py
@ -57,3 +57,12 @@ async def get_current_admin(token: str = Depends(oauth2_scheme), db: Session = D
|
|||||||
if admin is None:
|
if admin is None:
|
||||||
raise credentials_exception
|
raise credentials_exception
|
||||||
return admin
|
return admin
|
||||||
|
|
||||||
|
async def get_current_super_admin(current_admin: models.Admin = Depends(get_current_admin)):
|
||||||
|
"""Проверяет, является ли текущий админ суперадмином"""
|
||||||
|
if not current_admin.is_super_admin:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Недостаточно прав. Эта операция доступна только главному администратору."
|
||||||
|
)
|
||||||
|
return current_admin
|
||||||
|
@ -3,9 +3,9 @@ from models import Admin, Base
|
|||||||
from database import SessionLocal, engine
|
from database import SessionLocal, engine
|
||||||
import argparse
|
import argparse
|
||||||
|
|
||||||
def create_initial_admin(username: str, password: str):
|
def create_initial_admin(username: str, password: str, super_admin: bool = True):
|
||||||
"""
|
"""
|
||||||
Создает первого администратора в системе
|
Создает первого администратора в системе (по умолчанию как главного админа)
|
||||||
"""
|
"""
|
||||||
Base.metadata.create_all(bind=engine)
|
Base.metadata.create_all(bind=engine)
|
||||||
db = SessionLocal()
|
db = SessionLocal()
|
||||||
@ -18,18 +18,24 @@ def create_initial_admin(username: str, password: str):
|
|||||||
|
|
||||||
# Создаем нового админа
|
# Создаем нового админа
|
||||||
hashed_password = get_password_hash(password)
|
hashed_password = get_password_hash(password)
|
||||||
db_admin = Admin(username=username, hashed_password=hashed_password)
|
db_admin = Admin(
|
||||||
|
username=username,
|
||||||
|
hashed_password=hashed_password,
|
||||||
|
is_super_admin=super_admin
|
||||||
|
)
|
||||||
db.add(db_admin)
|
db.add(db_admin)
|
||||||
db.commit()
|
db.commit()
|
||||||
db.refresh(db_admin)
|
db.refresh(db_admin)
|
||||||
print(f"Администратор {username} успешно создан!")
|
admin_type = "главный администратор" if super_admin else "администратор"
|
||||||
|
print(f"{admin_type.capitalize()} {username} успешно создан!")
|
||||||
|
|
||||||
db.close()
|
db.close()
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
parser = argparse.ArgumentParser(description="Создание первого администратора")
|
parser = argparse.ArgumentParser(description="Создание администратора")
|
||||||
parser.add_argument("--username", required=True, help="Имя пользователя администратора")
|
parser.add_argument("--username", required=True, help="Имя пользователя администратора")
|
||||||
parser.add_argument("--password", required=True, help="Пароль администратора")
|
parser.add_argument("--password", required=True, help="Пароль администратора")
|
||||||
|
parser.add_argument("--super", action="store_true", help="Создать как главного администратора")
|
||||||
|
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
create_initial_admin(args.username, args.password)
|
create_initial_admin(args.username, args.password, args.super)
|
||||||
|
6
crud.py
6
crud.py
@ -9,7 +9,11 @@ def get_admin_by_username(db: Session, username: str) -> Optional[Admin]:
|
|||||||
|
|
||||||
def create_admin(db: Session, admin: schemas.AdminCreate) -> Admin:
|
def create_admin(db: Session, admin: schemas.AdminCreate) -> Admin:
|
||||||
hashed_password = get_password_hash(admin.password)
|
hashed_password = get_password_hash(admin.password)
|
||||||
db_admin = Admin(username=admin.username, hashed_password=hashed_password)
|
db_admin = Admin(
|
||||||
|
username=admin.username,
|
||||||
|
hashed_password=hashed_password,
|
||||||
|
is_super_admin=admin.is_super_admin
|
||||||
|
)
|
||||||
db.add(db_admin)
|
db.add(db_admin)
|
||||||
db.commit()
|
db.commit()
|
||||||
db.refresh(db_admin)
|
db.refresh(db_admin)
|
||||||
|
7
main.py
7
main.py
@ -47,8 +47,11 @@ async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(
|
|||||||
return {"access_token": access_token, "token_type": "bearer"}
|
return {"access_token": access_token, "token_type": "bearer"}
|
||||||
|
|
||||||
@app.post("/admins", response_model=schemas.Admin, status_code=status.HTTP_201_CREATED)
|
@app.post("/admins", response_model=schemas.Admin, status_code=status.HTTP_201_CREATED)
|
||||||
def create_admin(admin: schemas.AdminCreate, db: Session = Depends(get_db), current_admin: models.Admin = Depends(auth.get_current_admin)):
|
def create_admin(
|
||||||
# Проверка, что создать админа может только существующий админ
|
admin: schemas.AdminCreate,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_admin: models.Admin = Depends(auth.get_current_super_admin)
|
||||||
|
):
|
||||||
db_admin = crud.get_admin_by_username(db, username=admin.username)
|
db_admin = crud.get_admin_by_username(db, username=admin.username)
|
||||||
if db_admin:
|
if db_admin:
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
|
@ -24,6 +24,7 @@ class Admin(Base):
|
|||||||
username = Column(String, unique=True, index=True)
|
username = Column(String, unique=True, index=True)
|
||||||
hashed_password = Column(String)
|
hashed_password = Column(String)
|
||||||
is_active = Column(Boolean, default=True)
|
is_active = Column(Boolean, default=True)
|
||||||
|
is_super_admin = Column(Boolean, default=False) # Новое поле для главного админа
|
||||||
|
|
||||||
class Car(Base):
|
class Car(Base):
|
||||||
__tablename__ = "cars"
|
__tablename__ = "cars"
|
||||||
|
@ -32,10 +32,12 @@ class AdminBase(BaseModel):
|
|||||||
|
|
||||||
class AdminCreate(AdminBase):
|
class AdminCreate(AdminBase):
|
||||||
password: str
|
password: str
|
||||||
|
is_super_admin: Optional[bool] = False
|
||||||
|
|
||||||
class Admin(AdminBase):
|
class Admin(AdminBase):
|
||||||
id: int
|
id: int
|
||||||
is_active: bool
|
is_active: bool
|
||||||
|
is_super_admin: bool
|
||||||
|
|
||||||
class Config:
|
class Config:
|
||||||
from_attributes = True
|
from_attributes = True
|
||||||
|
Reference in New Issue
Block a user