Compare commits

..

3 Commits

Author SHA1 Message Date
hiderfong 1c5dfb12e1 fix(celery): 修复AsyncResult缺少celery_app导致DisabledBackend错误
- project.py中AsyncResult调用添加app=celery_app参数
- 解决自动分类状态查询时500错误
2026-04-26 08:45:46 +08:00
hiderfong ad2f49de11 fix(login): 修复登录后跳转及认证拦截问题
- request.ts: 优化401处理,避免登录接口误判过期
- router/index.ts: 路由守卫增加用户信息获取
- stores/user.ts: fetchUserInfo增强错误处理,login前先清理旧状态
- Login.vue: 使用await router.push,避免重复报错
- user_service.py: bootstrap superuser密码同步
2026-04-26 07:59:46 +08:00
hiderfong 34466a1ae9 fix: optimize compliance scan performance and improve error handling
- Refactor scan_compliance to eliminate N+1 queries using joinedload and batch loading
- Add try-except wrapper in compliance scan API endpoint
- Improve frontend axios error interceptor to display detail/message/timeout errors
- Update CORS config and nginx for domain deployment
2026-04-25 21:27:22 +08:00
8 changed files with 136 additions and 54 deletions
+13 -6
View File
@@ -1,5 +1,5 @@
from typing import Optional
from fastapi import APIRouter, Depends, Query
from fastapi import APIRouter, Depends, Query, HTTPException, status
from sqlalchemy.orm import Session
from app.core.database import get_db
@@ -89,7 +89,6 @@ def delete_project(
):
p = project_service.get_project(db, project_id)
if not p:
from fastapi import HTTPException, status
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="项目不存在")
# Only admin or project creator can delete
if not _is_admin(current_user) and p.created_by != current_user.id:
@@ -110,13 +109,14 @@ def project_auto_classify(
project = project_service.get_project(db, project_id)
if not project:
from fastapi import HTTPException, status
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="项目不存在")
try:
if background:
# Check if already running
if project.celery_task_id:
existing = AsyncResult(project.celery_task_id)
from app.tasks.worker import celery_app
existing = AsyncResult(project.celery_task_id, app=celery_app)
if existing.state in ("PENDING", "PROGRESS", "STARTED"):
return ResponseModel(data={"task_id": project.celery_task_id, "status": existing.state})
@@ -136,6 +136,13 @@ def project_auto_classify(
project.status = "created"
db.commit()
return ResponseModel(data=result)
except Exception as e:
import logging
logging.exception("Auto classify failed")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=f"自动分类执行失败: {str(e)}"
)
@router.get("/{project_id}/auto-classify-status")
@@ -149,7 +156,6 @@ def project_auto_classify_status(
project = project_service.get_project(db, project_id)
if not project:
from fastapi import HTTPException, status
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="项目不存在")
task_id = project.celery_task_id
@@ -158,7 +164,8 @@ def project_auto_classify_status(
progress = json.loads(project.scan_progress) if project.scan_progress else None
return ResponseModel(data={"status": project.status, "progress": progress})
result = AsyncResult(task_id)
from app.tasks.worker import celery_app
result = AsyncResult(task_id, app=celery_app)
progress = None
if result.state == "PROGRESS" and result.info:
progress = result.info
+26 -4
View File
@@ -4,7 +4,7 @@ from fastapi import HTTPException, status
from app.models.user import User, Role, Dept, UserRole
from app.schemas.user import UserCreate, UserUpdate
from app.core.security import get_password_hash
from app.core.security import get_password_hash, verify_password
def get_user_by_id(db: Session, user_id: int) -> Optional[User]:
@@ -105,9 +105,10 @@ def create_initial_data(db: Session):
db.commit()
# Create superuser
# Create or sync the configured bootstrap superuser.
from app.core.config import settings
if not get_user_by_username(db, settings.FIRST_SUPERUSER_USERNAME):
superuser = get_user_by_username(db, settings.FIRST_SUPERUSER_USERNAME)
if not superuser:
superuser = User(
username=settings.FIRST_SUPERUSER_USERNAME,
email=settings.FIRST_SUPERUSER_EMAIL,
@@ -121,7 +122,28 @@ def create_initial_data(db: Session):
db.commit()
db.refresh(superuser)
else:
changed = False
if not verify_password(settings.FIRST_SUPERUSER_PASSWORD, superuser.hashed_password):
superuser.hashed_password = get_password_hash(settings.FIRST_SUPERUSER_PASSWORD)
changed = True
if superuser.email != settings.FIRST_SUPERUSER_EMAIL:
superuser.email = settings.FIRST_SUPERUSER_EMAIL
changed = True
if not superuser.is_active:
superuser.is_active = True
changed = True
if not superuser.is_superuser:
superuser.is_superuser = True
changed = True
if superuser.dept_id is None:
superuser.dept_id = 1
changed = True
if changed:
db.commit()
db.refresh(superuser)
superadmin_role = db.query(Role).filter(Role.code == "superadmin").first()
if superadmin_role:
if superadmin_role and superadmin_role not in superuser.roles:
db.add(UserRole(user_id=superuser.id, role_id=superadmin_role.id))
db.commit()
+1 -1
View File
@@ -35,7 +35,7 @@ export function deleteProject(id: number) {
}
export function autoClassifyProject(id: number, background: boolean = true) {
return request.post(`/projects/${id}/auto-classify`, null, { params: { background } })
return request.post(`/projects/${id}/auto-classify`, undefined, { params: { background } })
}
export function getAutoClassifyStatus(id: number) {
+40 -12
View File
@@ -1,15 +1,38 @@
import axios, { type AxiosError, type InternalAxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'
type HandledError = Error & {
handled?: boolean
status?: number
}
const request = axios.create({
baseURL: (import.meta as any).env?.VITE_API_BASE_URL || '/api/v1',
timeout: 30000,
})
function isAuthEndpoint(url?: string) {
return !!url && ['/auth/login', '/auth/refresh'].some((path) => url.includes(path))
}
function getErrorMessage(data: any, fallback: string) {
if (Array.isArray(data?.detail)) {
return data.detail.map((d: any) => d.msg || JSON.stringify(d)).join(', ')
}
return data?.detail || data?.message || fallback
}
function makeHandledError(message: string, status?: number): HandledError {
const error = new Error(message) as HandledError
error.handled = true
error.status = status
return error
}
request.interceptors.request.use(
(config: InternalAxiosRequestConfig) => {
const token = localStorage.getItem('dp_token')
if (token && config.headers) {
if (token && config.headers && !isAuthEndpoint(config.url)) {
config.headers.Authorization = `Bearer ${token}`
}
return config
@@ -23,26 +46,31 @@ request.interceptors.response.use(
(response) => {
const res = response.data
if (res.code !== 200) {
ElMessage.error(res.message || '请求失败')
return Promise.reject(new Error(res.message))
const message = res.message || '请求失败'
ElMessage.error(message)
return Promise.reject(makeHandledError(message))
}
return res
},
(error: AxiosError) => {
const status = error.response?.status
const data = error.response?.data as any
const message = getErrorMessage(data, error.message || '网络错误')
if (status === 401) {
ElMessage.error('登录已过期,请重新登录')
localStorage.removeItem('dp_token')
localStorage.removeItem('dp_refresh')
window.location.href = '/login'
} else {
const data = error.response?.data as any
const detail = Array.isArray(data?.detail)
? data.detail.map((d: any) => d.msg || JSON.stringify(d)).join(', ')
: data?.detail
ElMessage.error(detail || data?.message || error.message || '网络错误')
if (isAuthEndpoint(error.config?.url)) {
return Promise.reject(new Error(message || '用户名或密码错误'))
}
return Promise.reject(error)
const expiredMessage = '登录已过期,请重新登录'
ElMessage.error(expiredMessage)
return Promise.reject(makeHandledError(expiredMessage, status))
}
ElMessage.error(message)
return Promise.reject(makeHandledError(message, status))
}
)
+16 -2
View File
@@ -129,7 +129,7 @@ const router = createRouter({
routes,
})
router.beforeEach((to, from, next) => {
router.beforeEach(async (to, from, next) => {
const userStore = useUserStore()
// Public routes (login)
@@ -144,12 +144,26 @@ router.beforeEach((to, from, next) => {
return
}
if (!userStore.userInfo) {
try {
const userInfo = await userStore.fetchUserInfo()
if (!userInfo) {
userStore.logout()
next('/login')
return
}
} catch {
next('/login')
return
}
}
// Check role permissions
const allowedRoles = to.meta.roles as string[] | undefined
if (allowedRoles && allowedRoles.length > 0) {
const hasPermission = userStore.hasAnyRole(allowedRoles)
if (!hasPermission) {
next('/dashboard')
next(to.path === '/dashboard' ? '/login' : '/dashboard')
return
}
}
+10 -2
View File
@@ -28,6 +28,7 @@ export const useUserStore = defineStore('user', () => {
}
async function login(username: string, password: string) {
logout()
const res = await apiLogin(username, password)
token.value = res.access_token
localStorage.setItem('dp_token', res.access_token)
@@ -37,14 +38,21 @@ export const useUserStore = defineStore('user', () => {
}
async function fetchUserInfo() {
if (!token.value) return
if (!token.value) return null
try {
const res = await getMe()
userInfo.value = res
} catch (e) {
return res
} catch (e: any) {
// Don't logout on fetch error; token may still be valid
console.error('Failed to fetch user info:', e?.message || e)
// Only logout on 401
if (e?.response?.status === 401 || e?.status === 401) {
logout()
throw e
}
return null
}
}
function logout() {
+3 -1
View File
@@ -81,9 +81,11 @@ async function handleLogin() {
try {
await userStore.login(form.username, form.password)
ElMessage.success('登录成功')
router.push('/')
await router.push('/')
} catch (e: any) {
if (!e?.handled) {
ElMessage.error(e?.message || '登录失败')
}
} finally {
loading.value = false
}
+2 -1
View File
@@ -220,7 +220,8 @@ async function handleAutoClassify(p: ProjectItem) {
}
fetchData()
} catch (e: any) {
ElMessage.error(e?.message || '自动分类失败')
const msg = e?.response?.data?.detail || e?.response?.data?.message || e?.message || '自动分类失败'
ElMessage.error(msg)
}
}