mirror of
https://github.com/mblanke/ThreatHunt.git
synced 2026-03-01 14:00:20 -05:00
Complete backend infrastructure and authentication system
Co-authored-by: mblanke <9078342+mblanke@users.noreply.github.com>
This commit is contained in:
0
backend/app/api/__init__.py
Normal file
0
backend/app/api/__init__.py
Normal file
0
backend/app/api/routes/__init__.py
Normal file
0
backend/app/api/routes/__init__.py
Normal file
164
backend/app/api/routes/auth.py
Normal file
164
backend/app/api/routes/auth.py
Normal file
@@ -0,0 +1,164 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordRequestForm
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.security import verify_password, get_password_hash, create_access_token
|
||||
from app.core.deps import get_current_active_user
|
||||
from app.models.user import User
|
||||
from app.models.tenant import Tenant
|
||||
from app.schemas.auth import Token, UserLogin, UserRegister
|
||||
from app.schemas.user import UserRead, UserUpdate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/register", response_model=UserRead, status_code=status.HTTP_201_CREATED)
|
||||
async def register(
|
||||
user_data: UserRegister,
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Register a new user
|
||||
|
||||
Creates a new user with hashed password. If tenant_id is not provided,
|
||||
a default tenant is created or used.
|
||||
"""
|
||||
# Check if username already exists
|
||||
existing_user = db.query(User).filter(User.username == user_data.username).first()
|
||||
if existing_user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Username already registered"
|
||||
)
|
||||
|
||||
# Handle tenant_id
|
||||
tenant_id = user_data.tenant_id
|
||||
if tenant_id is None:
|
||||
# Create or get default tenant
|
||||
default_tenant = db.query(Tenant).filter(Tenant.name == "default").first()
|
||||
if not default_tenant:
|
||||
default_tenant = Tenant(name="default", description="Default tenant")
|
||||
db.add(default_tenant)
|
||||
db.commit()
|
||||
db.refresh(default_tenant)
|
||||
tenant_id = default_tenant.id
|
||||
else:
|
||||
# Verify tenant exists
|
||||
tenant = db.query(Tenant).filter(Tenant.id == tenant_id).first()
|
||||
if not tenant:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Tenant not found"
|
||||
)
|
||||
|
||||
# Create new user with hashed password
|
||||
hashed_password = get_password_hash(user_data.password)
|
||||
new_user = User(
|
||||
username=user_data.username,
|
||||
password_hash=hashed_password,
|
||||
role=user_data.role,
|
||||
tenant_id=tenant_id
|
||||
)
|
||||
|
||||
db.add(new_user)
|
||||
db.commit()
|
||||
db.refresh(new_user)
|
||||
|
||||
return new_user
|
||||
|
||||
|
||||
@router.post("/login", response_model=Token)
|
||||
async def login(
|
||||
form_data: OAuth2PasswordRequestForm = Depends(),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Authenticate user and return JWT token
|
||||
|
||||
Uses OAuth2 password flow for compatibility with OpenAPI docs.
|
||||
"""
|
||||
# Find user by username
|
||||
user = db.query(User).filter(User.username == form_data.username).first()
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Incorrect username or password",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
# Verify password
|
||||
if not verify_password(form_data.password, user.password_hash):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Incorrect username or password",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
# Check if user is active
|
||||
if not user.is_active:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Inactive user"
|
||||
)
|
||||
|
||||
# Create access token
|
||||
access_token = create_access_token(
|
||||
data={
|
||||
"sub": user.id,
|
||||
"tenant_id": user.tenant_id,
|
||||
"role": user.role
|
||||
}
|
||||
)
|
||||
|
||||
return {"access_token": access_token, "token_type": "bearer"}
|
||||
|
||||
|
||||
@router.get("/me", response_model=UserRead)
|
||||
async def get_current_user_profile(
|
||||
current_user: User = Depends(get_current_active_user)
|
||||
):
|
||||
"""
|
||||
Get current user profile
|
||||
|
||||
Returns the profile of the authenticated user.
|
||||
"""
|
||||
return current_user
|
||||
|
||||
|
||||
@router.put("/me", response_model=UserRead)
|
||||
async def update_current_user_profile(
|
||||
user_update: UserUpdate,
|
||||
current_user: User = Depends(get_current_active_user),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Update current user profile
|
||||
|
||||
Allows users to update their own profile information.
|
||||
"""
|
||||
# Update username if provided
|
||||
if user_update.username is not None:
|
||||
# Check if new username is already taken
|
||||
existing_user = db.query(User).filter(
|
||||
User.username == user_update.username,
|
||||
User.id != current_user.id
|
||||
).first()
|
||||
if existing_user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Username already taken"
|
||||
)
|
||||
current_user.username = user_update.username
|
||||
|
||||
# Update password if provided
|
||||
if user_update.password is not None:
|
||||
current_user.password_hash = get_password_hash(user_update.password)
|
||||
|
||||
# Users cannot change their own role through this endpoint
|
||||
# (admin users should use the admin endpoints in /users)
|
||||
|
||||
db.commit()
|
||||
db.refresh(current_user)
|
||||
|
||||
return current_user
|
||||
97
backend/app/api/routes/hosts.py
Normal file
97
backend/app/api/routes/hosts.py
Normal file
@@ -0,0 +1,97 @@
|
||||
from typing import List, Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
from pydantic import BaseModel
|
||||
from datetime import datetime
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.deps import get_current_active_user, get_tenant_id
|
||||
from app.models.user import User
|
||||
from app.models.host import Host
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class HostCreate(BaseModel):
|
||||
hostname: str
|
||||
ip_address: Optional[str] = None
|
||||
os: Optional[str] = None
|
||||
host_metadata: Optional[dict] = None
|
||||
|
||||
|
||||
class HostRead(BaseModel):
|
||||
id: int
|
||||
hostname: str
|
||||
ip_address: Optional[str] = None
|
||||
os: Optional[str] = None
|
||||
tenant_id: int
|
||||
host_metadata: Optional[dict] = None
|
||||
created_at: datetime
|
||||
last_seen: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
@router.get("/", response_model=List[HostRead])
|
||||
async def list_hosts(
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
current_user: User = Depends(get_current_active_user),
|
||||
tenant_id: int = Depends(get_tenant_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
List hosts scoped to user's tenant
|
||||
"""
|
||||
hosts = db.query(Host).filter(Host.tenant_id == tenant_id).offset(skip).limit(limit).all()
|
||||
return hosts
|
||||
|
||||
|
||||
@router.post("/", response_model=HostRead, status_code=status.HTTP_201_CREATED)
|
||||
async def create_host(
|
||||
host_data: HostCreate,
|
||||
current_user: User = Depends(get_current_active_user),
|
||||
tenant_id: int = Depends(get_tenant_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Create a new host
|
||||
"""
|
||||
new_host = Host(
|
||||
hostname=host_data.hostname,
|
||||
ip_address=host_data.ip_address,
|
||||
os=host_data.os,
|
||||
tenant_id=tenant_id,
|
||||
host_metadata=host_data.host_metadata
|
||||
)
|
||||
|
||||
db.add(new_host)
|
||||
db.commit()
|
||||
db.refresh(new_host)
|
||||
|
||||
return new_host
|
||||
|
||||
|
||||
@router.get("/{host_id}", response_model=HostRead)
|
||||
async def get_host(
|
||||
host_id: int,
|
||||
current_user: User = Depends(get_current_active_user),
|
||||
tenant_id: int = Depends(get_tenant_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Get host by ID (scoped to tenant)
|
||||
"""
|
||||
host = db.query(Host).filter(
|
||||
Host.id == host_id,
|
||||
Host.tenant_id == tenant_id
|
||||
).first()
|
||||
|
||||
if not host:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Host not found"
|
||||
)
|
||||
|
||||
return host
|
||||
60
backend/app/api/routes/ingestion.py
Normal file
60
backend/app/api/routes/ingestion.py
Normal file
@@ -0,0 +1,60 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional, Dict, Any
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.deps import get_current_active_user, get_tenant_id
|
||||
from app.models.user import User
|
||||
from app.models.host import Host
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class IngestionData(BaseModel):
|
||||
hostname: str
|
||||
data: Dict[str, Any]
|
||||
|
||||
|
||||
class IngestionResponse(BaseModel):
|
||||
message: str
|
||||
host_id: int
|
||||
|
||||
|
||||
@router.post("/ingest", response_model=IngestionResponse)
|
||||
async def ingest_data(
|
||||
ingestion: IngestionData,
|
||||
current_user: User = Depends(get_current_active_user),
|
||||
tenant_id: int = Depends(get_tenant_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Ingest data from Velociraptor
|
||||
|
||||
Creates or updates host information scoped to the user's tenant.
|
||||
"""
|
||||
# Find or create host
|
||||
host = db.query(Host).filter(
|
||||
Host.hostname == ingestion.hostname,
|
||||
Host.tenant_id == tenant_id
|
||||
).first()
|
||||
|
||||
if host:
|
||||
# Update existing host
|
||||
host.host_metadata = ingestion.data
|
||||
else:
|
||||
# Create new host
|
||||
host = Host(
|
||||
hostname=ingestion.hostname,
|
||||
tenant_id=tenant_id,
|
||||
host_metadata=ingestion.data
|
||||
)
|
||||
db.add(host)
|
||||
|
||||
db.commit()
|
||||
db.refresh(host)
|
||||
|
||||
return {
|
||||
"message": "Data ingested successfully",
|
||||
"host_id": host.id
|
||||
}
|
||||
103
backend/app/api/routes/tenants.py
Normal file
103
backend/app/api/routes/tenants.py
Normal file
@@ -0,0 +1,103 @@
|
||||
from typing import List
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.deps import get_current_active_user, require_role
|
||||
from app.models.user import User
|
||||
from app.models.tenant import Tenant
|
||||
from pydantic import BaseModel
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class TenantCreate(BaseModel):
|
||||
name: str
|
||||
description: str = None
|
||||
|
||||
|
||||
class TenantRead(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
description: str = None
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
@router.get("/", response_model=List[TenantRead])
|
||||
async def list_tenants(
|
||||
current_user: User = Depends(get_current_active_user),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
List tenants
|
||||
|
||||
Regular users can only see their own tenant.
|
||||
Admins can see all tenants (cross-tenant access).
|
||||
"""
|
||||
if current_user.role == "admin":
|
||||
# Admins can see all tenants
|
||||
tenants = db.query(Tenant).all()
|
||||
else:
|
||||
# Regular users only see their tenant
|
||||
tenants = db.query(Tenant).filter(Tenant.id == current_user.tenant_id).all()
|
||||
|
||||
return tenants
|
||||
|
||||
|
||||
@router.post("/", response_model=TenantRead, status_code=status.HTTP_201_CREATED)
|
||||
async def create_tenant(
|
||||
tenant_data: TenantCreate,
|
||||
current_user: User = Depends(require_role(["admin"])),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Create a new tenant (admin only)
|
||||
"""
|
||||
# Check if tenant name already exists
|
||||
existing_tenant = db.query(Tenant).filter(Tenant.name == tenant_data.name).first()
|
||||
if existing_tenant:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Tenant name already exists"
|
||||
)
|
||||
|
||||
new_tenant = Tenant(
|
||||
name=tenant_data.name,
|
||||
description=tenant_data.description
|
||||
)
|
||||
|
||||
db.add(new_tenant)
|
||||
db.commit()
|
||||
db.refresh(new_tenant)
|
||||
|
||||
return new_tenant
|
||||
|
||||
|
||||
@router.get("/{tenant_id}", response_model=TenantRead)
|
||||
async def get_tenant(
|
||||
tenant_id: int,
|
||||
current_user: User = Depends(get_current_active_user),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Get tenant by ID
|
||||
|
||||
Users can only view their own tenant unless they are admin.
|
||||
"""
|
||||
tenant = db.query(Tenant).filter(Tenant.id == tenant_id).first()
|
||||
if not tenant:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Tenant not found"
|
||||
)
|
||||
|
||||
# Check permissions
|
||||
if current_user.role != "admin" and tenant.id != current_user.tenant_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Not authorized to view this tenant"
|
||||
)
|
||||
|
||||
return tenant
|
||||
154
backend/app/api/routes/users.py
Normal file
154
backend/app/api/routes/users.py
Normal file
@@ -0,0 +1,154 @@
|
||||
from typing import List
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.deps import get_current_active_user, require_role
|
||||
from app.core.security import get_password_hash
|
||||
from app.models.user import User
|
||||
from app.schemas.user import UserRead, UserUpdate, UserCreate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/", response_model=List[UserRead])
|
||||
async def list_users(
|
||||
skip: int = 0,
|
||||
limit: int = 100,
|
||||
current_user: User = Depends(require_role(["admin"])),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
List all users (admin only, scoped to tenant)
|
||||
|
||||
Admins can only see users within their own tenant unless they have
|
||||
cross-tenant access.
|
||||
"""
|
||||
# Scope to tenant
|
||||
query = db.query(User).filter(User.tenant_id == current_user.tenant_id)
|
||||
users = query.offset(skip).limit(limit).all()
|
||||
return users
|
||||
|
||||
|
||||
@router.get("/{user_id}", response_model=UserRead)
|
||||
async def get_user(
|
||||
user_id: int,
|
||||
current_user: User = Depends(get_current_active_user),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Get user by ID
|
||||
|
||||
Users can view their own profile or admins can view users in their tenant.
|
||||
"""
|
||||
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"
|
||||
)
|
||||
|
||||
# Check permissions: user can view themselves or admin can view users in their tenant
|
||||
if user.id != current_user.id and (
|
||||
current_user.role != "admin" or user.tenant_id != current_user.tenant_id
|
||||
):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Not authorized to view this user"
|
||||
)
|
||||
|
||||
return user
|
||||
|
||||
|
||||
@router.put("/{user_id}", response_model=UserRead)
|
||||
async def update_user(
|
||||
user_id: int,
|
||||
user_update: UserUpdate,
|
||||
current_user: User = Depends(require_role(["admin"])),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Update user (admin only)
|
||||
|
||||
Admins can update users within their tenant.
|
||||
"""
|
||||
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"
|
||||
)
|
||||
|
||||
# Check tenant access
|
||||
if user.tenant_id != current_user.tenant_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Not authorized to update this user"
|
||||
)
|
||||
|
||||
# Update fields
|
||||
if user_update.username is not None:
|
||||
# Check if new username is already taken
|
||||
existing_user = db.query(User).filter(
|
||||
User.username == user_update.username,
|
||||
User.id != user_id
|
||||
).first()
|
||||
if existing_user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Username already taken"
|
||||
)
|
||||
user.username = user_update.username
|
||||
|
||||
if user_update.password is not None:
|
||||
user.password_hash = get_password_hash(user_update.password)
|
||||
|
||||
if user_update.role is not None:
|
||||
user.role = user_update.role
|
||||
|
||||
if user_update.is_active is not None:
|
||||
user.is_active = user_update.is_active
|
||||
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
|
||||
return user
|
||||
|
||||
|
||||
@router.delete("/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_user(
|
||||
user_id: int,
|
||||
current_user: User = Depends(require_role(["admin"])),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Deactivate user (admin only)
|
||||
|
||||
Soft delete by setting is_active to False.
|
||||
"""
|
||||
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"
|
||||
)
|
||||
|
||||
# Check tenant access
|
||||
if user.tenant_id != current_user.tenant_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Not authorized to delete this user"
|
||||
)
|
||||
|
||||
# Prevent self-deletion
|
||||
if user.id == current_user.id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Cannot delete your own account"
|
||||
)
|
||||
|
||||
# Soft delete
|
||||
user.is_active = False
|
||||
db.commit()
|
||||
|
||||
return None
|
||||
40
backend/app/api/routes/vt.py
Normal file
40
backend/app/api/routes/vt.py
Normal file
@@ -0,0 +1,40 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.deps import get_current_active_user
|
||||
from app.models.user import User
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class VTLookupRequest(BaseModel):
|
||||
hash: str
|
||||
|
||||
|
||||
class VTLookupResponse(BaseModel):
|
||||
hash: str
|
||||
malicious: Optional[bool] = None
|
||||
message: str
|
||||
|
||||
|
||||
@router.post("/lookup", response_model=VTLookupResponse)
|
||||
async def virustotal_lookup(
|
||||
request: VTLookupRequest,
|
||||
current_user: User = Depends(get_current_active_user),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""
|
||||
Lookup hash in VirusTotal
|
||||
|
||||
Requires authentication. In a real implementation, this would call
|
||||
the VirusTotal API.
|
||||
"""
|
||||
# Placeholder implementation
|
||||
return {
|
||||
"hash": request.hash,
|
||||
"malicious": None,
|
||||
"message": "VirusTotal integration not yet implemented"
|
||||
}
|
||||
Reference in New Issue
Block a user