feat: complete external auth V2 migration with advanced features

This commit implements comprehensive external Azure AD authentication
with complete task management, file download, and admin monitoring systems.

## Core Features Implemented (80% Complete)

### 1. Token Auto-Refresh Mechanism 
- Backend: POST /api/v2/auth/refresh endpoint
- Frontend: Auto-refresh 5 minutes before expiration
- Auto-retry on 401 errors with seamless token refresh

### 2. File Download System 
- Three format support: JSON / Markdown / PDF
- Endpoints: GET /api/v2/tasks/{id}/download/{format}
- File access control with ownership validation
- Frontend download buttons in TaskHistoryPage

### 3. Complete Task Management 
Backend Endpoints:
- POST /api/v2/tasks/{id}/start - Start task
- POST /api/v2/tasks/{id}/cancel - Cancel task
- POST /api/v2/tasks/{id}/retry - Retry failed task
- GET /api/v2/tasks - List with filters (status, filename, date range)
- GET /api/v2/tasks/stats - User statistics

Frontend Features:
- Status-based action buttons (Start/Cancel/Retry)
- Advanced search and filtering (status, filename, date range)
- Pagination and sorting
- Task statistics dashboard (5 stat cards)

### 4. Admin Monitoring System  (Backend)
Admin APIs:
- GET /api/v2/admin/stats - System statistics
- GET /api/v2/admin/users - User list with stats
- GET /api/v2/admin/users/top - User leaderboard
- GET /api/v2/admin/audit-logs - Audit log query system
- GET /api/v2/admin/audit-logs/user/{id}/summary

Admin Features:
- Email-based admin check (ymirliu@panjit.com.tw)
- Comprehensive system metrics (users, tasks, sessions, activity)
- Audit logging service for security tracking

### 5. User Isolation & Security 
- Row-level security on all task queries
- File access control with ownership validation
- Strict user_id filtering on all operations
- Session validation and expiry checking
- Admin privilege verification

## New Files Created

Backend:
- backend/app/models/user_v2.py - User model for external auth
- backend/app/models/task.py - Task model with user isolation
- backend/app/models/session.py - Session management
- backend/app/models/audit_log.py - Audit log model
- backend/app/services/external_auth_service.py - External API client
- backend/app/services/task_service.py - Task CRUD with isolation
- backend/app/services/file_access_service.py - File access control
- backend/app/services/admin_service.py - Admin operations
- backend/app/services/audit_service.py - Audit logging
- backend/app/routers/auth_v2.py - V2 auth endpoints
- backend/app/routers/tasks.py - Task management endpoints
- backend/app/routers/admin.py - Admin endpoints
- backend/alembic/versions/5e75a59fb763_*.py - DB migration

Frontend:
- frontend/src/services/apiV2.ts - Complete V2 API client
- frontend/src/types/apiV2.ts - V2 type definitions
- frontend/src/pages/TaskHistoryPage.tsx - Task history UI

Modified Files:
- backend/app/core/deps.py - Added get_current_admin_user_v2
- backend/app/main.py - Registered admin router
- frontend/src/pages/LoginPage.tsx - V2 login integration
- frontend/src/components/Layout.tsx - User display and logout
- frontend/src/App.tsx - Added /tasks route

## Documentation
- openspec/changes/.../PROGRESS_UPDATE.md - Detailed progress report

## Pending Items (20%)
1. Database migration execution for audit_logs table
2. Frontend admin dashboard page
3. Frontend audit log viewer

## Testing Status
- Manual testing:  Authentication flow verified
- Unit tests:  Pending
- Integration tests:  Pending

## Security Enhancements
-  User isolation (row-level security)
-  File access control
-  Token expiry validation
-  Admin privilege verification
-  Audit logging infrastructure
-  Token encryption (noted, low priority)
-  Rate limiting (noted, low priority)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
egg
2025-11-14 17:19:43 +08:00
parent 470fa96428
commit ad2b832fb6
32 changed files with 6450 additions and 26 deletions

View File

@@ -0,0 +1,431 @@
/**
* API V2 Client - External Authentication & Task Management
*
* Features:
* - External Azure AD authentication
* - Task history and management
* - User task isolation
* - Session management
*/
import axios, { AxiosError, AxiosInstance } from 'axios'
import type {
LoginRequest,
ApiError,
} from '@/types/api'
import type {
LoginResponseV2,
UserInfo,
TaskCreate,
TaskUpdate,
Task,
TaskDetail,
TaskListResponse,
TaskStats,
SessionInfo,
} from '@/types/apiV2'
/**
* API Client Configuration
* - In Docker: VITE_API_BASE_URL is empty string, use relative path
* - In development: Use VITE_API_BASE_URL from .env or default to localhost:8000
*/
const envApiBaseUrl = import.meta.env.VITE_API_BASE_URL
const API_BASE_URL = envApiBaseUrl !== undefined ? envApiBaseUrl : 'http://localhost:8000'
const API_VERSION = 'v2'
class ApiClientV2 {
private client: AxiosInstance
private token: string | null = null
private userInfo: UserInfo | null = null
private tokenExpiresAt: number | null = null
private refreshTimer: NodeJS.Timeout | null = null
constructor() {
this.client = axios.create({
baseURL: `${API_BASE_URL}/api/${API_VERSION}`,
timeout: 30000,
headers: {
'Content-Type': 'application/json',
},
})
// Request interceptor to add auth token
this.client.interceptors.request.use(
(config) => {
if (this.token) {
config.headers.Authorization = `Bearer ${this.token}`
}
return config
},
(error) => Promise.reject(error)
)
// Response interceptor for error handling
this.client.interceptors.response.use(
(response) => response,
async (error: AxiosError<ApiError>) => {
if (error.response?.status === 401) {
// Token expired or invalid
const detail = error.response?.data?.detail
if (detail?.includes('Session expired') || detail?.includes('Invalid session')) {
console.warn('Session expired, attempting refresh')
// Try to refresh token once
try {
await this.refreshToken()
// Retry the original request
if (error.config) {
return this.client.request(error.config)
}
} catch (refreshError) {
console.error('Token refresh failed, redirecting to login')
this.clearAuth()
window.location.href = '/login'
}
} else {
this.clearAuth()
window.location.href = '/login'
}
}
return Promise.reject(error)
}
)
// Load auth data from localStorage
this.loadAuth()
}
/**
* Set authentication data
*/
setAuth(token: string, user: UserInfo, expiresIn?: number) {
this.token = token
this.userInfo = user
localStorage.setItem('auth_token_v2', token)
localStorage.setItem('user_info_v2', JSON.stringify(user))
// Schedule token refresh if expiresIn is provided
if (expiresIn) {
this.tokenExpiresAt = Date.now() + expiresIn * 1000
localStorage.setItem('token_expires_at', this.tokenExpiresAt.toString())
this.scheduleTokenRefresh(expiresIn)
}
}
/**
* Clear authentication data
*/
clearAuth() {
this.token = null
this.userInfo = null
this.tokenExpiresAt = null
// Clear refresh timer
if (this.refreshTimer) {
clearTimeout(this.refreshTimer)
this.refreshTimer = null
}
localStorage.removeItem('auth_token_v2')
localStorage.removeItem('user_info_v2')
localStorage.removeItem('token_expires_at')
}
/**
* Load auth data from localStorage
*/
private loadAuth() {
const token = localStorage.getItem('auth_token_v2')
const userInfoStr = localStorage.getItem('user_info_v2')
const expiresAtStr = localStorage.getItem('token_expires_at')
if (token && userInfoStr) {
try {
this.token = token
this.userInfo = JSON.parse(userInfoStr)
// Load and check token expiry
if (expiresAtStr) {
this.tokenExpiresAt = parseInt(expiresAtStr, 10)
const timeUntilExpiry = this.tokenExpiresAt - Date.now()
// If token is expired, clear auth
if (timeUntilExpiry <= 0) {
console.warn('Token expired, clearing auth')
this.clearAuth()
return
}
// Schedule refresh if token is expiring soon
const refreshBuffer = 5 * 60 * 1000 // 5 minutes
if (timeUntilExpiry < refreshBuffer) {
console.log('Token expiring soon, refreshing immediately')
this.refreshToken().catch(() => this.clearAuth())
} else {
// Schedule refresh for later
this.scheduleTokenRefresh(Math.floor(timeUntilExpiry / 1000))
}
}
} catch (error) {
console.error('Failed to parse user info from localStorage:', error)
this.clearAuth()
}
}
}
/**
* Check if user is authenticated
*/
isAuthenticated(): boolean {
return this.token !== null && this.userInfo !== null
}
/**
* Get current user info
*/
getCurrentUser(): UserInfo | null {
return this.userInfo
}
/**
* Schedule token refresh before expiration
* @param expiresIn - Token expiry time in seconds
*/
private scheduleTokenRefresh(expiresIn: number): void {
// Clear existing timer
if (this.refreshTimer) {
clearTimeout(this.refreshTimer)
}
// Schedule refresh 5 minutes before expiry
const refreshBuffer = 5 * 60 // 5 minutes in seconds
const refreshTime = Math.max(0, expiresIn - refreshBuffer) * 1000 // Convert to milliseconds
console.log(`Scheduling token refresh in ${refreshTime / 1000} seconds`)
this.refreshTimer = setTimeout(() => {
console.log('Auto-refreshing token')
this.refreshToken().catch((error) => {
console.error('Auto token refresh failed:', error)
// Don't redirect on auto-refresh failure, let user continue
// Redirect will happen on next API call with 401
})
}, refreshTime)
}
/**
* Refresh access token
*/
private async refreshToken(): Promise<void> {
try {
const response = await this.client.post<LoginResponseV2>('/auth/refresh')
// Update token and schedule next refresh
this.setAuth(response.data.access_token, response.data.user, response.data.expires_in)
console.log('Token refreshed successfully')
} catch (error) {
console.error('Token refresh failed:', error)
throw error
}
}
// ==================== Authentication ====================
/**
* Login via external Azure AD API
*/
async login(data: LoginRequest): Promise<LoginResponseV2> {
const response = await this.client.post<LoginResponseV2>('/auth/login', {
username: data.username,
password: data.password,
})
// Store token and user info with auto-refresh
this.setAuth(response.data.access_token, response.data.user, response.data.expires_in)
return response.data
}
/**
* Logout (invalidate session)
*/
async logout(sessionId?: number): Promise<void> {
try {
await this.client.post('/auth/logout', { session_id: sessionId })
} finally {
// Always clear local auth data
this.clearAuth()
}
}
/**
* Get current user info from server
*/
async getMe(): Promise<UserInfo> {
const response = await this.client.get<UserInfo>('/auth/me')
this.userInfo = response.data
localStorage.setItem('user_info_v2', JSON.stringify(response.data))
return response.data
}
/**
* List user sessions
*/
async listSessions(): Promise<SessionInfo[]> {
const response = await this.client.get<{ sessions: SessionInfo[] }>('/auth/sessions')
return response.data.sessions
}
// ==================== Task Management ====================
/**
* Create a new task
*/
async createTask(data: TaskCreate): Promise<Task> {
const response = await this.client.post<Task>('/tasks/', data)
return response.data
}
/**
* List tasks with pagination and filtering
*/
async listTasks(params: {
status?: 'pending' | 'processing' | 'completed' | 'failed'
filename?: string
date_from?: string
date_to?: string
page?: number
page_size?: number
order_by?: string
order_desc?: boolean
} = {}): Promise<TaskListResponse> {
const response = await this.client.get<TaskListResponse>('/tasks/', { params })
return response.data
}
/**
* Get task statistics
*/
async getTaskStats(): Promise<TaskStats> {
const response = await this.client.get<TaskStats>('/tasks/stats')
return response.data
}
/**
* Get task details by ID
*/
async getTask(taskId: string): Promise<TaskDetail> {
const response = await this.client.get<TaskDetail>(`/tasks/${taskId}`)
return response.data
}
/**
* Update task
*/
async updateTask(taskId: string, data: TaskUpdate): Promise<Task> {
const response = await this.client.patch<Task>(`/tasks/${taskId}`, data)
return response.data
}
/**
* Delete task
*/
async deleteTask(taskId: string): Promise<void> {
await this.client.delete(`/tasks/${taskId}`)
}
/**
* Start task processing
*/
async startTask(taskId: string): Promise<Task> {
const response = await this.client.post<Task>(`/tasks/${taskId}/start`)
return response.data
}
/**
* Cancel task
*/
async cancelTask(taskId: string): Promise<Task> {
const response = await this.client.post<Task>(`/tasks/${taskId}/cancel`)
return response.data
}
/**
* Retry failed task
*/
async retryTask(taskId: string): Promise<Task> {
const response = await this.client.post<Task>(`/tasks/${taskId}/retry`)
return response.data
}
// ==================== Helper Methods ====================
/**
* Download file from task result
*/
async downloadTaskFile(url: string, filename: string): Promise<void> {
const response = await this.client.get(url, {
responseType: 'blob',
})
// Create download link
const blob = new Blob([response.data])
const link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = filename
link.click()
window.URL.revokeObjectURL(link.href)
}
/**
* Download task result as JSON
*/
async downloadJSON(taskId: string): Promise<void> {
const response = await this.client.get(`/tasks/${taskId}/download/json`, {
responseType: 'blob',
})
const blob = new Blob([response.data], { type: 'application/json' })
const link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = `${taskId}_result.json`
link.click()
window.URL.revokeObjectURL(link.href)
}
/**
* Download task result as Markdown
*/
async downloadMarkdown(taskId: string): Promise<void> {
const response = await this.client.get(`/tasks/${taskId}/download/markdown`, {
responseType: 'blob',
})
const blob = new Blob([response.data], { type: 'text/markdown' })
const link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = `${taskId}_result.md`
link.click()
window.URL.revokeObjectURL(link.href)
}
/**
* Download task result as PDF
*/
async downloadPDF(taskId: string): Promise<void> {
const response = await this.client.get(`/tasks/${taskId}/download/pdf`, {
responseType: 'blob',
})
const blob = new Blob([response.data], { type: 'application/pdf' })
const link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = `${taskId}_result.pdf`
link.click()
window.URL.revokeObjectURL(link.href)
}
}
// Export singleton instance
export const apiClientV2 = new ApiClientV2()