Initial monorepo structure
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Core package."""
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Auth dependencies."""
|
||||
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.security import decode_token
|
||||
from app.models.user import User
|
||||
|
||||
security = HTTPBearer()
|
||||
|
||||
|
||||
def get_current_user_id(credentials: HTTPAuthorizationCredentials = Depends(security)) -> int:
|
||||
token = credentials.credentials
|
||||
payload = decode_token(token)
|
||||
if not payload:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
||||
user_id = payload.get("sub")
|
||||
if not user_id:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
||||
return int(user_id)
|
||||
|
||||
|
||||
def get_current_user(
|
||||
user_id: int = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db),
|
||||
) -> User:
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
|
||||
if not user.is_active:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="User is deactivated")
|
||||
return user
|
||||
|
||||
|
||||
def require_platform_admin(user: User = Depends(get_current_user), db: Session = Depends(get_db)) -> User:
|
||||
if user.is_superadmin:
|
||||
return user
|
||||
from app.models.associations import UserRole
|
||||
from app.models.role import Role
|
||||
has_role = db.query(UserRole).join(Role).filter(
|
||||
UserRole.user_id == user.id, Role.name == "platform_admin"
|
||||
).first()
|
||||
if not has_role:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Platform admin required")
|
||||
return user
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Database utilities."""
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker, Session
|
||||
from typing import Generator
|
||||
from app.settings import get_settings
|
||||
from app.models.base import Base
|
||||
|
||||
settings = get_settings()
|
||||
engine = create_engine(settings.DATABASE_URL, pool_pre_ping=True, echo=False)
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
|
||||
def get_db() -> Generator[Session, None, None]:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def init_db():
|
||||
from app.models import user, role, module, associations
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
from app.models.role import Role
|
||||
system_roles = [
|
||||
("platform_admin", "Platform administrator", True),
|
||||
("user_manager", "Can manage users", True),
|
||||
]
|
||||
for name, desc, is_system in system_roles:
|
||||
if not db.query(Role).filter(Role.name == name).first():
|
||||
db.add(Role(name=name, description=desc, is_system=is_system))
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Security utilities."""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional, Dict, Any
|
||||
from jose import JWTError, jwt
|
||||
import bcrypt
|
||||
from app.settings import get_settings
|
||||
|
||||
|
||||
def get_password_hash(password: str) -> str:
|
||||
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
||||
|
||||
|
||||
def verify_password(plain: str, hashed: str) -> bool:
|
||||
try:
|
||||
return bcrypt.checkpw(plain.encode("utf-8"), hashed.encode("utf-8"))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def create_access_token(data: Dict[str, Any], expires_delta: Optional[timedelta] = None) -> str:
|
||||
to_encode = data.copy()
|
||||
expire = datetime.utcnow() + (expires_delta or timedelta(minutes=get_settings().JWT_ACCESS_TOKEN_EXPIRE_MINUTES))
|
||||
to_encode["exp"] = expire
|
||||
return jwt.encode(to_encode, get_settings().JWT_SECRET_KEY, algorithm=get_settings().JWT_ALGORITHM)
|
||||
|
||||
|
||||
def decode_token(token: str) -> Optional[Dict[str, Any]]:
|
||||
try:
|
||||
return jwt.decode(token, get_settings().JWT_SECRET_KEY, algorithms=[get_settings().JWT_ALGORITHM])
|
||||
except JWTError:
|
||||
return None
|
||||
Reference in New Issue
Block a user