revamped authentication system

This commit is contained in:
2025-11-02 18:40:03 +01:00
parent 9cc92e5fc4
commit e4bc438069
18 changed files with 674 additions and 636 deletions

View File

@@ -15,7 +15,7 @@ from datetime import datetime
from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session
from app.api.deps import get_current_admin_user
from app.api.deps import get_current_admin_api
from app.core.database import get_db
from app.services.admin_audit_service import admin_audit_service
from models.schema.admin import (
@@ -39,7 +39,7 @@ def get_audit_logs(
skip: int = Query(0, ge=0, description="Number of records to skip"),
limit: int = Query(100, ge=1, le=1000, description="Maximum records to return"),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""
Get filtered admin audit logs.
@@ -74,7 +74,7 @@ def get_audit_logs(
def get_recent_audit_logs(
limit: int = Query(20, ge=1, le=100),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""Get recent audit logs (last 20 by default)."""
filters = AdminAuditLogFilters(limit=limit)
@@ -85,7 +85,7 @@ def get_recent_audit_logs(
def get_my_actions(
limit: int = Query(50, ge=1, le=100),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""Get audit logs for current admin's actions."""
return admin_audit_service.get_recent_actions_by_admin(
@@ -101,7 +101,7 @@ def get_actions_by_target(
target_id: str,
limit: int = Query(50, ge=1, le=100),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""
Get all actions performed on a specific target.

View File

@@ -2,9 +2,11 @@
"""
Admin authentication endpoints.
Implements dual token storage:
- Sets HTTP-only cookie for browser page navigation
Implements dual token storage with path restriction:
- Sets HTTP-only cookie with path=/admin (restricted to admin routes only)
- Returns token in response for localStorage (API calls)
This prevents admin cookies from being sent to vendor routes.
"""
import logging
@@ -16,7 +18,7 @@ from app.services.auth_service import auth_service
from app.exceptions import InvalidCredentialsException
from models.schema.auth import LoginResponse, UserLogin, UserResponse
from models.database.user import User
from app.api.deps import get_current_admin_user
from app.api.deps import get_current_admin_api
from app.core.config import settings
router = APIRouter(prefix="/auth")
@@ -36,8 +38,11 @@ def admin_login(
Returns JWT token for authenticated admin users.
Sets token in two places:
1. HTTP-only cookie (for browser page navigation)
1. HTTP-only cookie with path=/admin (for browser page navigation)
2. Response body (for localStorage and API calls)
The cookie is restricted to /admin/* routes only to prevent
it from being sent to vendor or other routes.
"""
# Authenticate user
login_result = auth_service.login_user(db=db, user_credentials=user_credentials)
@@ -50,17 +55,21 @@ def admin_login(
logger.info(f"Admin login successful: {login_result['user'].username}")
# Set HTTP-only cookie for browser navigation
# CRITICAL: path=/admin restricts cookie to admin routes only
response.set_cookie(
key="admin_token",
value=login_result["token_data"]["access_token"],
httponly=True, # JavaScript cannot access (XSS protection)
secure=False, # Set to True in production (requires HTTPS)
secure=settings.environment == "production", # HTTPS only in production
samesite="lax", # CSRF protection
max_age=login_result["token_data"]["expires_in"], # Match JWT expiry
path="/", # Available for all routes
path="/admin", # RESTRICTED TO ADMIN ROUTES ONLY
)
logger.debug(f"Set admin_token cookie with {login_result['token_data']['expires_in']}s expiry")
logger.debug(
f"Set admin_token cookie with {login_result['token_data']['expires_in']}s expiry "
f"(path=/admin, httponly=True, secure={settings.environment == 'production'})"
)
# Also return token in response for localStorage (API calls)
return LoginResponse(
@@ -72,7 +81,7 @@ def admin_login(
@router.get("/me", response_model=UserResponse)
def get_current_admin(current_user: User = Depends(get_current_admin_user)):
def get_current_admin(current_user: User = Depends(get_current_admin_api)):
"""
Get current authenticated admin user.
@@ -81,11 +90,9 @@ def get_current_admin(current_user: User = Depends(get_current_admin_user)):
Token can come from:
- Authorization header (API calls)
- admin_token cookie (browser navigation)
- admin_token cookie (browser navigation, path=/admin only)
"""
logger.info(f"Admin user info requested: {current_user.username}")
# Pydantic will automatically serialize the User model to UserResponse
return current_user
@@ -99,10 +106,10 @@ def admin_logout(response: Response):
"""
logger.info("Admin logout")
# Clear the cookie
# Clear the cookie (must match path used when setting)
response.delete_cookie(
key="admin_token",
path="/",
path="/admin",
)
logger.debug("Deleted admin_token cookie")

View File

@@ -8,7 +8,7 @@ from typing import List
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from app.api.deps import get_current_admin_user
from app.api.deps import get_current_admin_api
from app.core.database import get_db
from app.services.admin_service import admin_service
from app.services.stats_service import stats_service
@@ -22,7 +22,7 @@ logger = logging.getLogger(__name__)
@router.get("")
def get_admin_dashboard(
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""Get admin dashboard with platform statistics (Admin only)."""
return {
@@ -40,7 +40,7 @@ def get_admin_dashboard(
@router.get("/stats", response_model=StatsResponse)
def get_comprehensive_stats(
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""Get comprehensive platform statistics (Admin only)."""
stats_data = stats_service.get_comprehensive_stats(db=db)
@@ -59,7 +59,7 @@ def get_comprehensive_stats(
@router.get("/stats/marketplace", response_model=List[MarketplaceStatsResponse])
def get_marketplace_stats(
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""Get statistics broken down by marketplace (Admin only)."""
marketplace_stats = stats_service.get_marketplace_breakdown_stats(db=db)
@@ -78,7 +78,7 @@ def get_marketplace_stats(
@router.get("/stats/platform")
def get_platform_statistics(
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""Get comprehensive platform statistics (Admin only)."""
return {

View File

@@ -9,7 +9,7 @@ from typing import List, Optional
from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session
from app.api.deps import get_current_admin_user
from app.api.deps import get_current_admin_api
from app.core.database import get_db
from app.services.admin_service import admin_service
from app.services.stats_service import stats_service
@@ -28,7 +28,7 @@ def get_all_marketplace_import_jobs(
skip: int = Query(0, ge=0),
limit: int = Query(100, ge=1, le=100),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""Get all marketplace import jobs (Admin only)."""
return admin_service.get_marketplace_import_jobs(
@@ -44,7 +44,7 @@ def get_all_marketplace_import_jobs(
@router.get("/stats")
def get_import_statistics(
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""Get marketplace import statistics (Admin only)."""
return stats_service.get_import_statistics(db)

View File

@@ -14,7 +14,7 @@ from typing import Optional
from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session
from app.api.deps import get_current_admin_user
from app.api.deps import get_current_admin_api
from app.core.database import get_db
from models.schema.admin import (
AdminNotificationCreate,
@@ -42,7 +42,7 @@ def get_notifications(
skip: int = Query(0, ge=0),
limit: int = Query(50, ge=1, le=100),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""Get admin notifications with filtering."""
# TODO: Implement notification service
@@ -58,7 +58,7 @@ def get_notifications(
@router.get("/unread-count")
def get_unread_count(
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""Get count of unread notifications."""
# TODO: Implement
@@ -69,7 +69,7 @@ def get_unread_count(
def mark_as_read(
notification_id: int,
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""Mark notification as read."""
# TODO: Implement
@@ -79,7 +79,7 @@ def mark_as_read(
@router.put("/mark-all-read")
def mark_all_as_read(
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""Mark all notifications as read."""
# TODO: Implement
@@ -97,7 +97,7 @@ def get_platform_alerts(
skip: int = Query(0, ge=0),
limit: int = Query(50, ge=1, le=100),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""Get platform alerts with filtering."""
# TODO: Implement alert service
@@ -115,7 +115,7 @@ def get_platform_alerts(
def create_platform_alert(
alert_data: PlatformAlertCreate,
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""Create new platform alert (manual)."""
# TODO: Implement
@@ -128,7 +128,7 @@ def resolve_platform_alert(
alert_id: int,
resolve_data: PlatformAlertResolve,
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""Resolve platform alert."""
# TODO: Implement
@@ -139,7 +139,7 @@ def resolve_platform_alert(
@router.get("/alerts/stats")
def get_alert_statistics(
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""Get alert statistics for dashboard."""
# TODO: Implement

View File

@@ -14,7 +14,7 @@ from typing import Optional
from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session
from app.api.deps import get_current_admin_user
from app.api.deps import get_current_admin_api
from app.core.database import get_db
from app.services.admin_settings_service import admin_settings_service
from app.services.admin_audit_service import admin_audit_service
@@ -35,7 +35,7 @@ def get_all_settings(
category: Optional[str] = Query(None, description="Filter by category"),
is_public: Optional[bool] = Query(None, description="Filter by public flag"),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""
Get all platform settings.
@@ -55,7 +55,7 @@ def get_all_settings(
@router.get("/categories")
def get_setting_categories(
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""Get list of all setting categories."""
# This could be enhanced to return counts per category
@@ -75,7 +75,7 @@ def get_setting_categories(
def get_setting(
key: str,
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""Get specific setting by key."""
setting = admin_settings_service.get_setting_by_key(db, key)
@@ -91,7 +91,7 @@ def get_setting(
def create_setting(
setting_data: AdminSettingCreate,
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""
Create new platform setting.
@@ -122,7 +122,7 @@ def update_setting(
key: str,
update_data: AdminSettingUpdate,
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""Update existing setting value."""
old_value = admin_settings_service.get_setting_value(db, key)
@@ -151,7 +151,7 @@ def update_setting(
def upsert_setting(
setting_data: AdminSettingCreate,
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""
Create or update setting (upsert).
@@ -182,7 +182,7 @@ def delete_setting(
key: str,
confirm: bool = Query(False, description="Must be true to confirm deletion"),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""
Delete platform setting.

View File

@@ -9,7 +9,7 @@ from typing import List
from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session
from app.api.deps import get_current_admin_user
from app.api.deps import get_current_admin_api
from app.core.database import get_db
from app.services.admin_service import admin_service
from app.services.stats_service import stats_service
@@ -25,7 +25,7 @@ def get_all_users(
skip: int = Query(0, ge=0),
limit: int = Query(100, ge=1, le=1000),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""Get all users (Admin only)."""
users = admin_service.get_all_users(db=db, skip=skip, limit=limit)
@@ -36,7 +36,7 @@ def get_all_users(
def toggle_user_status(
user_id: int,
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""Toggle user active status (Admin only)."""
user, message = admin_service.toggle_user_status(db, user_id, current_admin.id)
@@ -46,7 +46,7 @@ def toggle_user_status(
@router.get("/stats")
def get_user_statistics(
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""Get user statistics for admin dashboard (Admin only)."""
return stats_service.get_user_statistics(db)

View File

@@ -15,7 +15,7 @@ from typing import List
from fastapi import APIRouter, Depends, Path, Body, Query
from sqlalchemy.orm import Session
from app.api.deps import get_current_admin_user
from app.api.deps import get_current_admin_api
from app.core.database import get_db
from app.services.vendor_domain_service import vendor_domain_service
from app.exceptions import VendorNotFoundException
@@ -60,7 +60,7 @@ def add_vendor_domain(
vendor_id: int = Path(..., description="Vendor ID", gt=0),
domain_data: VendorDomainCreate = Body(...),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""
Add a custom domain to vendor (Admin only).
@@ -113,7 +113,7 @@ def add_vendor_domain(
def list_vendor_domains(
vendor_id: int = Path(..., description="Vendor ID", gt=0),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""
List all domains for a vendor (Admin only).
@@ -156,7 +156,7 @@ def list_vendor_domains(
def get_domain_details(
domain_id: int = Path(..., description="Domain ID", gt=0),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""
Get detailed information about a specific domain (Admin only).
@@ -187,7 +187,7 @@ def update_vendor_domain(
domain_id: int = Path(..., description="Domain ID", gt=0),
domain_update: VendorDomainUpdate = Body(...),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""
Update domain settings (Admin only).
@@ -231,7 +231,7 @@ def update_vendor_domain(
def delete_vendor_domain(
domain_id: int = Path(..., description="Domain ID", gt=0),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""
Delete a custom domain (Admin only).
@@ -260,7 +260,7 @@ def delete_vendor_domain(
def verify_domain_ownership(
domain_id: int = Path(..., description="Domain ID", gt=0),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""
Verify domain ownership via DNS TXT record (Admin only).
@@ -298,7 +298,7 @@ def verify_domain_ownership(
def get_domain_verification_instructions(
domain_id: int = Path(..., description="Domain ID", gt=0),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""
Get DNS verification instructions for domain (Admin only).

View File

@@ -17,7 +17,7 @@ import logging
from fastapi import APIRouter, Depends, Path
from sqlalchemy.orm import Session
from app.api.deps import get_current_admin_user, get_db
from app.api.deps import get_current_admin_api, get_db
from app.services.vendor_theme_service import vendor_theme_service
from models.database.user import User
from models.schema.vendor_theme import (
@@ -36,7 +36,7 @@ logger = logging.getLogger(__name__)
@router.get("/presets", response_model=ThemePresetListResponse)
async def get_theme_presets(
current_admin: User = Depends(get_current_admin_user)
current_admin: User = Depends(get_current_admin_api)
):
"""
Get all available theme presets with preview information.
@@ -63,7 +63,7 @@ async def get_theme_presets(
async def get_vendor_theme(
vendor_code: str = Path(..., description="Vendor code"),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user)
current_admin: User = Depends(get_current_admin_api)
):
"""
Get theme configuration for a vendor.
@@ -98,7 +98,7 @@ async def update_vendor_theme(
vendor_code: str = Path(..., description="Vendor code"),
theme_data: VendorThemeUpdate = None,
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user)
current_admin: User = Depends(get_current_admin_api)
):
"""
Update or create theme for a vendor.
@@ -145,7 +145,7 @@ async def apply_theme_preset(
vendor_code: str = Path(..., description="Vendor code"),
preset_name: str = Path(..., description="Preset name"),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user)
current_admin: User = Depends(get_current_admin_api)
):
"""
Apply a theme preset to a vendor.
@@ -196,7 +196,7 @@ async def apply_theme_preset(
async def delete_vendor_theme(
vendor_code: str = Path(..., description="Vendor code"),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user)
current_admin: User = Depends(get_current_admin_api)
):
"""
Delete custom theme for a vendor.

View File

@@ -9,7 +9,7 @@ from typing import Optional
from fastapi import APIRouter, Depends, Query, Path, Body
from sqlalchemy.orm import Session
from app.api.deps import get_current_admin_user
from app.api.deps import get_current_admin_api
from app.core.database import get_db
from app.services.admin_service import admin_service
from app.services.stats_service import stats_service
@@ -74,7 +74,7 @@ def _get_vendor_by_identifier(db: Session, identifier: str) -> Vendor:
def create_vendor_with_owner(
vendor_data: VendorCreate,
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""
Create a new vendor with owner user account (Admin only).
@@ -133,7 +133,7 @@ def get_all_vendors_admin(
is_active: Optional[bool] = Query(None),
is_verified: Optional[bool] = Query(None),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""Get all vendors with filtering (Admin only)."""
vendors, total = admin_service.get_all_vendors(
@@ -150,7 +150,7 @@ def get_all_vendors_admin(
@router.get("/stats", response_model=VendorStatsResponse)
def get_vendor_statistics_endpoint(
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""Get vendor statistics for admin dashboard (Admin only)."""
stats = stats_service.get_vendor_statistics(db)
@@ -167,7 +167,7 @@ def get_vendor_statistics_endpoint(
def get_vendor_details(
vendor_identifier: str = Path(..., description="Vendor ID or vendor_code"),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""
Get detailed vendor information including owner details (Admin only).
@@ -211,7 +211,7 @@ def update_vendor(
vendor_identifier: str = Path(..., description="Vendor ID or vendor_code"),
vendor_update: VendorUpdate = Body(...),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""
Update vendor information (Admin only).
@@ -262,7 +262,7 @@ def transfer_vendor_ownership(
vendor_identifier: str = Path(..., description="Vendor ID or vendor_code"),
transfer_data: VendorTransferOwnership = Body(...),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""
Transfer vendor ownership to another user (Admin only).
@@ -314,7 +314,7 @@ def toggle_vendor_verification(
vendor_identifier: str = Path(..., description="Vendor ID or vendor_code"),
verification_data: dict = Body(..., example={"is_verified": True}),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""
Toggle vendor verification status (Admin only).
@@ -365,7 +365,7 @@ def toggle_vendor_status(
vendor_identifier: str = Path(..., description="Vendor ID or vendor_code"),
status_data: dict = Body(..., example={"is_active": True}),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""
Toggle vendor active status (Admin only).
@@ -416,7 +416,7 @@ def delete_vendor(
vendor_identifier: str = Path(..., description="Vendor ID or vendor_code"),
confirm: bool = Query(False, description="Must be true to confirm deletion"),
db: Session = Depends(get_db),
current_admin: User = Depends(get_current_admin_user),
current_admin: User = Depends(get_current_admin_api),
):
"""
Delete vendor and all associated data (Admin only).