Production

This commit is contained in:
Shubhankar45
2026-09-22 06:23:46 +00:00
commit 8fdd20b29f
217 changed files with 31212 additions and 0 deletions
View File
+111
View File
@@ -0,0 +1,111 @@
"""The permission core — two layers.
Layer 1 (`require_role`) answers "WHAT may this role do?".
Layer 2 (`assert_can_*`) answers "WHOSE data may this specific user touch?".
Most RBAC bugs live in the gap between those two questions: "AM" is a role, but
"AM *of this headquarters*" is a scope. Both checks are mandatory on scoped
endpoints, and every one has a negative test asserting 403 (X1-X3).
"""
import uuid
from fastapi import Depends, Request
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.auth.security import decode_access_token
from app.common.enums import Role
from app.common.exceptions import ForbiddenError, UnauthorizedError
from app.database.session import get_db
from app.organization.models import AMHeadquarters
from app.users.models import User
bearer_scheme = HTTPBearer(auto_error=False)
async def get_current_user(
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_scheme),
db: AsyncSession = Depends(get_db),
) -> User:
if credentials is None:
raise UnauthorizedError("Missing bearer token")
payload = decode_access_token(credentials.credentials)
try:
user_id = uuid.UUID(payload["sub"])
except (KeyError, ValueError) as exc:
raise UnauthorizedError("Malformed token subject") from exc
user = await db.get(User, user_id)
if user is None:
raise UnauthorizedError("User no longer exists")
# SEC-5: checked on EVERY request, not only at login.
if not user.is_active:
raise UnauthorizedError("User account is deactivated")
return user
def require_role(*allowed: Role):
"""Layer 1. Usage: `user: User = Depends(require_role(Role.MR))`."""
async def _check(user: User = Depends(get_current_user)) -> User:
if user.role not in allowed:
raise ForbiddenError(
"Role not permitted for this action",
{"your_role": user.role.value, "required": [r.value for r in allowed]},
)
return user
return _check
async def active_hq_ids_for_am(db: AsyncSession, am_user_id: uuid.UUID) -> set[uuid.UUID]:
"""Headquarters this Area Manager currently manages (`effective_to IS NULL`)."""
stmt = select(AMHeadquarters.headquarters_id).where(
AMHeadquarters.area_manager_user_id == am_user_id,
AMHeadquarters.effective_to.is_(None),
)
return set((await db.execute(stmt)).scalars().all())
async def visible_hq_ids(db: AsyncSession, user: User) -> set[uuid.UUID] | None:
"""Headquarters the user may see. `None` means "all" (GM and ADMIN)."""
if user.role in (Role.GM, Role.ADMIN):
return None
if user.role == Role.AM:
return await active_hq_ids_for_am(db, user.id)
if user.role == Role.MR:
return {user.headquarters_id} if user.headquarters_id else set()
return set()
async def assert_can_view_hq(db: AsyncSession, user: User, headquarters_id: uuid.UUID) -> None:
allowed = await visible_hq_ids(db, user)
if allowed is None or headquarters_id in allowed:
return
raise ForbiddenError("Headquarters outside your data scope")
async def assert_can_view_dcr(db: AsyncSession, user: User, dcr) -> None:
"""Layer 2 for reports.
ADMIN may inspect report content for support and administration, but cannot act on
reports because every transition endpoint still requires the AM role.
"""
if user.role in (Role.GM, Role.ADMIN):
return
if user.role == Role.MR and dcr.mr_user_id == user.id:
return
if user.role == Role.AM:
if dcr.headquarters_id in await active_hq_ids_for_am(db, user.id):
return
raise ForbiddenError("Report outside your data scope")
def client_ip(request: Request) -> str | None:
forwarded = request.headers.get("x-forwarded-for")
if forwarded:
return forwarded.split(",")[0].strip()
return request.client.host if request.client else None
+26
View File
@@ -0,0 +1,26 @@
"""Server-side refresh tokens.
Stored server-side (not stateless) precisely so they can be REVOKED — a departing MR
must lose access immediately (SEC-5).
"""
import uuid
from datetime import datetime
from sqlalchemy import Boolean, DateTime, ForeignKey, String
from sqlalchemy.dialects.postgresql import UUID as PGUUID
from sqlalchemy.orm import Mapped, mapped_column
from app.database.base import Base, TimestampMixin, UUIDMixin
class RefreshToken(Base, UUIDMixin, TimestampMixin):
__tablename__ = "refresh_token"
user_id: Mapped[uuid.UUID] = mapped_column(
PGUUID(as_uuid=True), ForeignKey("user.id", ondelete="CASCADE"), nullable=False, index=True
)
#: SHA-256 of the token — a database leak must not yield usable tokens.
token_hash: Mapped[str] = mapped_column(String(64), nullable=False, unique=True, index=True)
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
revoked: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
+34
View File
@@ -0,0 +1,34 @@
from fastapi import APIRouter, Depends, Request, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.auth.dependencies import client_ip, get_current_user
from app.auth.schemas import CurrentUser, LoginRequest, RefreshRequest, TokenPair
from app.auth.service import AuthService
from app.database.session import get_db
from app.users.models import User
router = APIRouter(prefix="/auth", tags=["auth"])
@router.post("/login", response_model=TokenPair)
async def login(
payload: LoginRequest, request: Request, db: AsyncSession = Depends(get_db)
) -> TokenPair:
return await AuthService(db).login(payload.email, payload.password, client_ip(request))
@router.post("/refresh", response_model=TokenPair)
async def refresh(payload: RefreshRequest, db: AsyncSession = Depends(get_db)) -> TokenPair:
return await AuthService(db).refresh(payload.refresh_token)
@router.post("/logout", status_code=status.HTTP_204_NO_CONTENT)
async def logout(
current_user: User = Depends(get_current_user), db: AsyncSession = Depends(get_db)
) -> None:
await AuthService(db).logout(current_user.id)
@router.get("/me", response_model=CurrentUser)
async def me(current_user: User = Depends(get_current_user)) -> User:
return current_user
+33
View File
@@ -0,0 +1,33 @@
import uuid
from pydantic import BaseModel, ConfigDict, EmailStr, Field
from app.common.enums import Role
class LoginRequest(BaseModel):
email: EmailStr
password: str = Field(min_length=1)
class TokenPair(BaseModel):
access_token: str
refresh_token: str
token_type: str = "bearer"
expires_in: int
class RefreshRequest(BaseModel):
refresh_token: str
class CurrentUser(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: uuid.UUID
email: str
full_name: str
employee_code: str
role: Role
headquarters_id: uuid.UUID | None
is_active: bool
+65
View File
@@ -0,0 +1,65 @@
"""Password hashing and JWT encoding/decoding."""
import hashlib
import secrets
import uuid
from datetime import UTC, datetime, timedelta
from typing import Any
from argon2 import PasswordHasher
from argon2.exceptions import VerificationError, VerifyMismatchError
from jose import JWTError, jwt
from app.common.exceptions import UnauthorizedError
from app.config.settings import settings
_hasher = PasswordHasher()
def utcnow() -> datetime:
return datetime.now(UTC)
def hash_password(plain: str) -> str:
return _hasher.hash(plain)
def verify_password(plain: str, hashed: str) -> bool:
try:
_hasher.verify(hashed, plain)
return True
except (VerifyMismatchError, VerificationError):
return False
def create_access_token(user_id: uuid.UUID, role: str) -> str:
now = utcnow()
payload: dict[str, Any] = {
"sub": str(user_id),
"role": role,
"type": "access",
"iat": now,
"exp": now + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES),
"jti": secrets.token_urlsafe(16),
}
return jwt.encode(payload, settings.SECRET_KEY, algorithm=settings.JWT_ALGORITHM)
def decode_access_token(token: str) -> dict[str, Any]:
try:
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.JWT_ALGORITHM])
except JWTError as exc:
raise UnauthorizedError("Invalid or expired token") from exc
if payload.get("type") != "access":
raise UnauthorizedError("Wrong token type")
return payload
def generate_refresh_token() -> tuple[str, str]:
"""Return (plaintext_token, sha256_hash). Only the hash is stored."""
raw = secrets.token_urlsafe(48)
return raw, hash_refresh_token(raw)
def hash_refresh_token(raw: str) -> str:
return hashlib.sha256(raw.encode()).hexdigest()
+100
View File
@@ -0,0 +1,100 @@
import uuid
from datetime import timedelta
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.audit.service import AuditService
from app.auth.models import RefreshToken
from app.auth.schemas import TokenPair
from app.auth.security import (
create_access_token,
generate_refresh_token,
hash_refresh_token,
utcnow,
verify_password,
)
from app.common.enums import AuditAction, EntityType
from app.common.exceptions import UnauthorizedError
from app.config.settings import settings
from app.users.models import User
class AuthService:
def __init__(self, db: AsyncSession) -> None:
self.db = db
self.audit = AuditService(db)
async def login(self, email: str, password: str, ip: str | None = None) -> TokenPair:
stmt = select(User).where(User.email == email)
user = (await self.db.execute(stmt)).scalar_one_or_none()
# Same message for unknown user and wrong password — do not leak which.
if user is None or not verify_password(password, user.password_hash):
if user is not None:
user.failed_login_attempts += 1
await self.db.commit()
raise UnauthorizedError("Invalid email or password")
if not user.is_active:
raise UnauthorizedError("User account is deactivated")
# SEC-10 — lock out after repeated failures.
if user.failed_login_attempts >= settings.LOGIN_MAX_FAILED_ATTEMPTS:
raise UnauthorizedError("Account locked after too many failed attempts")
user.failed_login_attempts = 0
await self.audit.log(
actor_user_id=user.id,
entity_type=EntityType.USER,
entity_id=user.id,
action=AuditAction.LOGIN,
ip_address=ip,
)
pair = await self._issue_tokens(user)
await self.db.commit()
return pair
async def refresh(self, raw_token: str) -> TokenPair:
token_hash = hash_refresh_token(raw_token)
stmt = select(RefreshToken).where(RefreshToken.token_hash == token_hash)
stored = (await self.db.execute(stmt)).scalar_one_or_none()
if stored is None or stored.revoked or stored.expires_at < utcnow():
raise UnauthorizedError("Invalid or expired refresh token")
user = await self.db.get(User, stored.user_id)
if user is None or not user.is_active:
raise UnauthorizedError("User no longer active")
# Rotate: the presented token is burned as the new one is issued.
stored.revoked = True
pair = await self._issue_tokens(user)
await self.db.commit()
return pair
async def logout(self, user_id: uuid.UUID) -> None:
"""Revoke every refresh token for this user."""
stmt = select(RefreshToken).where(
RefreshToken.user_id == user_id, RefreshToken.revoked.is_(False)
)
for token in (await self.db.execute(stmt)).scalars().all():
token.revoked = True
await self.db.commit()
async def _issue_tokens(self, user: User) -> TokenPair:
access = create_access_token(user.id, user.role.value)
raw_refresh, refresh_hash = generate_refresh_token()
self.db.add(
RefreshToken(
user_id=user.id,
token_hash=refresh_hash,
expires_at=utcnow() + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS),
)
)
await self.db.flush()
return TokenPair(
access_token=access,
refresh_token=raw_refresh,
expires_in=settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60,
)