Spaces:
Paused
Paused
File size: 9,021 Bytes
f3bcb28 | 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 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 | """Authentication endpoints for admin dashboard."""
from datetime import datetime
from fastapi import APIRouter, Depends, HTTPException, Response, Request
from pydantic import BaseModel, EmailStr
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from backend.db.session import get_db
from backend.db.models import User
from backend.core.jwt_auth import (
verify_password,
hash_password,
create_access_token,
create_refresh_token,
decode_token,
set_auth_cookies,
clear_auth_cookies,
get_current_user,
get_role_permissions,
AuthenticatedUser,
)
from backend.core.config import settings
router = APIRouter(prefix="/auth", tags=["Authentication"])
# ============================================================================
# Schemas
# ============================================================================
class LoginRequest(BaseModel):
"""Login request body."""
email: EmailStr
password: str
class LoginResponse(BaseModel):
"""Login response."""
user: dict
message: str
class UserResponse(BaseModel):
"""User info response."""
id: int
email: str
name: str
role: str
permissions: list[str]
class PasswordChangeRequest(BaseModel):
"""Password change request."""
current_password: str
new_password: str
class SetPasswordRequest(BaseModel):
"""Set initial password (for users without password)."""
email: EmailStr
password: str
# ============================================================================
# Endpoints
# ============================================================================
@router.post("/login", response_model=LoginResponse)
async def login(
credentials: LoginRequest,
response: Response,
db: AsyncSession = Depends(get_db),
):
"""
Authenticate user with email/password.
Sets HttpOnly cookies for access and refresh tokens.
"""
# Find user by email
stmt = select(User).where(User.email == credentials.email)
result = await db.execute(stmt)
user = result.scalar_one_or_none()
if not user:
raise HTTPException(status_code=401, detail="Invalid credentials")
if not user.is_active:
raise HTTPException(status_code=401, detail="Account is deactivated")
if not user.password_hash:
raise HTTPException(
status_code=401, detail="Password not set. Please contact administrator."
)
if not verify_password(credentials.password, user.password_hash):
raise HTTPException(status_code=401, detail="Invalid credentials")
# Update last login
user.last_login_at = datetime.utcnow()
await db.commit()
# Generate tokens
access_token = create_access_token(user)
refresh_token = create_refresh_token(user)
# Set cookies
set_auth_cookies(response, access_token, refresh_token)
# Get permissions
permissions = get_role_permissions(user.role.value)
return LoginResponse(
user={
"id": user.id,
"email": user.email,
"name": user.name,
"role": user.role.value,
"permissions": permissions,
},
message="Login successful",
)
# Demo user for anonymous authentication
DEMO_USER = {
"id": 0,
"email": "demo@tensorwall.ai",
"name": "Demo User",
"role": "viewer",
"permissions": ["read:dashboard", "read:analytics", "read:requests", "read:applications"],
}
@router.get("/check-demo")
async def check_demo_mode():
"""Check if demo mode is enabled."""
return {"demo_mode": settings.demo_mode}
@router.get("/demo")
async def demo_login(response: Response):
"""
Anonymous demo login - no credentials required.
Only available when DEMO_MODE=true.
Returns demo user info and sets auth cookies.
"""
if not settings.demo_mode:
raise HTTPException(status_code=404, detail="Demo mode not enabled")
# Create a simple demo token (valid for 24 hours in demo mode)
from jose import jwt
from datetime import timedelta
demo_payload = {
"sub": str(DEMO_USER["id"]),
"email": DEMO_USER["email"],
"role": DEMO_USER["role"],
"type": "access",
"exp": datetime.utcnow() + timedelta(hours=24),
}
access_token = jwt.encode(
demo_payload,
settings.jwt_secret_key,
algorithm=settings.jwt_algorithm,
)
# Set cookie with longer expiry for demo
response.set_cookie(
key="access_token",
value=access_token,
httponly=settings.cookie_httponly,
secure=settings.cookie_secure,
samesite=settings.cookie_samesite,
max_age=24 * 60 * 60, # 24 hours
path="/",
)
return {
"user": DEMO_USER,
"message": "Demo login successful",
"demo_mode": True,
}
@router.post("/logout")
async def logout(response: Response):
"""
Logout user by clearing auth cookies.
"""
clear_auth_cookies(response)
return {"message": "Logged out successfully"}
@router.post("/refresh")
async def refresh_token(
request: Request,
response: Response,
db: AsyncSession = Depends(get_db),
):
"""
Refresh access token using refresh token cookie.
"""
refresh_token_cookie = request.cookies.get("refresh_token")
if not refresh_token_cookie:
raise HTTPException(status_code=401, detail="No refresh token")
payload = decode_token(refresh_token_cookie)
if not payload or payload.type != "refresh":
raise HTTPException(status_code=401, detail="Invalid refresh token")
# Fetch user
stmt = select(User).where(User.id == payload.user_id, User.is_active.is_(True))
result = await db.execute(stmt)
user = result.scalar_one_or_none()
if not user:
raise HTTPException(status_code=401, detail="User not found")
# Generate new access token
new_access_token = create_access_token(user)
# Update access token cookie
response.set_cookie(
key="access_token",
value=new_access_token,
httponly=settings.cookie_httponly,
secure=settings.cookie_secure,
samesite=settings.cookie_samesite,
max_age=settings.access_token_expire_minutes * 60,
path="/",
)
return {"message": "Token refreshed"}
@router.get("/me", response_model=UserResponse)
async def get_me(
request: Request,
current_user: AuthenticatedUser = Depends(get_current_user),
):
"""
Get current authenticated user info.
"""
# Check if this is a demo user (id=0)
if current_user.id == 0 and settings.demo_mode:
return UserResponse(
id=DEMO_USER["id"],
email=DEMO_USER["email"],
name=DEMO_USER["name"],
role=DEMO_USER["role"],
permissions=DEMO_USER["permissions"],
)
return UserResponse(
id=current_user.id,
email=current_user.email,
name=current_user.name,
role=current_user.role,
permissions=current_user.permissions,
)
@router.post("/change-password")
async def change_password(
data: PasswordChangeRequest,
current_user: AuthenticatedUser = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
"""
Change password for authenticated user.
"""
stmt = select(User).where(User.id == current_user.id)
result = await db.execute(stmt)
user = result.scalar_one_or_none()
if not user:
raise HTTPException(status_code=404, detail="User not found")
if not user.password_hash or not verify_password(
data.current_password, user.password_hash
):
raise HTTPException(status_code=400, detail="Current password is incorrect")
if len(data.new_password) < 8:
raise HTTPException(
status_code=400, detail="Password must be at least 8 characters"
)
user.password_hash = hash_password(data.new_password)
user.updated_at = datetime.utcnow()
await db.commit()
return {"message": "Password changed successfully"}
@router.post("/set-password")
async def set_initial_password(
data: SetPasswordRequest,
db: AsyncSession = Depends(get_db),
):
"""
Set initial password for a user (one-time setup).
Only works if user exists and has no password set.
"""
stmt = select(User).where(User.email == data.email)
result = await db.execute(stmt)
user = result.scalar_one_or_none()
if not user:
raise HTTPException(status_code=404, detail="User not found")
if user.password_hash:
raise HTTPException(status_code=400, detail="Password already set")
if len(data.password) < 8:
raise HTTPException(
status_code=400, detail="Password must be at least 8 characters"
)
user.password_hash = hash_password(data.password)
user.updated_at = datetime.utcnow()
await db.commit()
return {"message": "Password set successfully"}
|