Spaces:
Sleeping
Sleeping
File size: 5,779 Bytes
1220b7a bb6f17c 1220b7a bb6f17c 1220b7a bb6f17c 1220b7a bb6f17c 1220b7a bb6f17c 1220b7a bb6f17c 1220b7a bb6f17c 1220b7a bb6f17c 1220b7a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | """
admin.py β Admin authentication and protected admin routes.
Endpoints:
POST /api/v1/admin/login β Public: authenticate and receive JWT
GET /api/v1/admin/me β Protected: verify token, return admin info
GET /api/v1/admin/stats β Protected: dashboard overview stats
GET /api/v1/admin/ingredients β Protected: paginated ingredient list
"""
from fastapi import APIRouter, HTTPException, Depends, status, Request
from slowapi import Limiter
from slowapi.util import get_remote_address
from pydantic import BaseModel
from core.config import settings
from database.mongo import get_db
from datetime import datetime, timezone
from utils.auth import verify_password, get_password_hash, create_access_token, get_current_admin
router = APIRouter(prefix="/api/v1/admin", tags=["admin"])
limiter = Limiter(key_func=get_remote_address)
class LoginRequest(BaseModel):
username: str
password: str
class TokenResponse(BaseModel):
access_token: str
token_type: str = "bearer"
class ChangePasswordRequest(BaseModel):
old_password: str
new_password: str
class StatsResponse(BaseModel):
total_ingredients: int
toxic_count: int
safe_count: int
@router.post("/login", response_model=TokenResponse)
@limiter.limit("5/minute")
async def login(request: Request, credentials: LoginRequest, db = Depends(get_db)):
"""
Admin login. Rate limited to 5 attempts per minute.
Returns JWT on success, 401 on invalid credentials.
Checks admin_users collection with fallback to .env configuration.
"""
# 1. Check database for admin user first
user_doc = await db.admin_users.find_one({"username": credentials.username})
expected_hash = None
if user_doc:
expected_hash = user_doc.get("hashed_password")
elif credentials.username == settings.ADMIN_USERNAME:
expected_hash = settings.ADMIN_PASSWORD_HASH
else:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Username atau password salah",
)
if not expected_hash:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Admin auth not configured. Set ADMIN_PASSWORD_HASH in .env",
)
if not verify_password(credentials.password, expected_hash):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Username atau password salah",
)
token = create_access_token(subject=credentials.username)
return TokenResponse(access_token=token)
@router.post("/change-password")
async def change_password(
req: ChangePasswordRequest,
admin: str = Depends(get_current_admin),
db = Depends(get_db),
):
"""
Change password for authenticated admin.
Requires current password verification and at least 8 characters for new password.
"""
if len(req.new_password) < 8:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Password baru minimal 8 karakter",
)
user_doc = await db.admin_users.find_one({"username": admin})
current_hash = user_doc.get("hashed_password") if user_doc else settings.ADMIN_PASSWORD_HASH
if not current_hash or not verify_password(req.old_password, current_hash):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Password saat ini tidak sesuai",
)
new_hash = get_password_hash(req.new_password)
settings.ADMIN_PASSWORD_HASH = new_hash
await db.admin_users.update_one(
{"username": admin},
{
"$set": {
"username": admin,
"hashed_password": new_hash,
"updated_at": datetime.now(timezone.utc),
}
},
upsert=True,
)
return {"status": "success", "message": "Password berhasil diperbarui dengan enkripsi bcrypt"}
@router.get("/me")
async def get_me(admin: str = Depends(get_current_admin)):
"""Verify token is valid. Returns admin username."""
return {"username": admin, "role": "admin"}
@router.get("/stats", response_model=StatsResponse)
async def get_stats(admin: str = Depends(get_current_admin)):
"""Dashboard overview: ingredient and toxicity counts from MongoDB."""
db = get_db()
total = await db.tcm_ingredients.count_documents({})
toxic = await db.tcm_ingredients.count_documents({"is_toxic": True})
return StatsResponse(
total_ingredients=total,
toxic_count=toxic,
safe_count=total - toxic,
)
@router.get("/ingredients")
async def list_ingredients(
admin: str = Depends(get_current_admin),
page: int = 1,
limit: int = 20,
):
"""
Paginated ingredient list for the admin table.
Sorted by mandarin_name ascending.
"""
db = get_db()
skip = (page - 1) * limit
total = await db.tcm_ingredients.count_documents({})
cursor = db.tcm_ingredients.find(
{},
{
"mandarin_name": 1,
"indonesian_name": 1,
"latin_name": 1,
"english_name": 1,
"is_toxic": 1,
"toxicity_level": 1,
"_id": 1,
},
).skip(skip).limit(limit).sort("mandarin_name", 1)
ingredients = []
async for doc in cursor:
doc["_id"] = str(doc["_id"])
ingredients.append(doc)
return {
"ingredients": ingredients,
"total": total,
"page": page,
"limit": limit,
"pages": max(1, (total + limit - 1) // limit),
}
|