File size: 2,463 Bytes
11757af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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

from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel
from datetime import timedelta
from ...core.admin_auth import (
    authenticate_admin,
    create_access_token,
    get_current_admin,
    ACCESS_TOKEN_EXPIRE_MINUTES
)
import logging

router = APIRouter(prefix="/admin/auth", tags=["admin-auth"])
logger = logging.getLogger("api.admin.auth")

class AdminLogin(BaseModel):
    username: str
    password: str
    connection_key: str

class TokenResponse(BaseModel):
    access_token: str
    token_type: str
    expires_in: int

@router.post("/login", response_model=TokenResponse)
async def admin_login(credentials: AdminLogin):
    """
    🔐 Admin Dashboard Login
    
    Requires 3-layer authentication:
    - Username: mina samir
    - Password: !9#@minasamir#@
    - Connection Key: en
    
    Returns a JWT token valid for 60 minutes.
    """
    # Validate credentials
    if not authenticate_admin(
        credentials.username,
        credentials.password,
        credentials.connection_key
    ):
        # Generic error message to prevent username enumeration
        raise HTTPException(
            status_code=401,
            detail="⛔ Authentication failed. Invalid credentials or connection key."
        )
    
    # Create access token
    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": credentials.username},
        expires_delta=access_token_expires
    )
    
    logger.info(f"✅ Token issued for admin: {credentials.username}")
    
    return {
        "access_token": access_token,
        "token_type": "bearer",
        "expires_in": ACCESS_TOKEN_EXPIRE_MINUTES * 60  # in seconds
    }

@router.get("/verify")
async def verify_admin_token(current_admin: str = Depends(get_current_admin)):
    """
    Verify if the current token is valid.
    Protected endpoint - requires valid JWT token.
    """
    return {
        "valid": True,
        "admin": current_admin,
        "message": "✅ Token is valid"
    }

@router.post("/logout")
async def admin_logout(current_admin: str = Depends(get_current_admin)):
    """
    Logout endpoint (client should discard the token).
    Protected endpoint - requires valid JWT token.
    """
    logger.info(f"Admin logged out: {current_admin}")
    return {
        "success": True,
        "message": "Logged out successfully. Please discard your token."
    }