Update Local Permission Assignments

This commit is contained in:
2026-02-03 18:48:25 +08:00
parent 86b3e4402c
commit 47e1411390
13 changed files with 94 additions and 147 deletions

View File

@@ -14,7 +14,7 @@ from core.security import (
decode_access_token
)
from db.database import get_db
from db.crud import get_user_by_username, get_user_by_email, create_user, change_user_password, update_user_aliyun_key, get_user_preferences, update_user_preferences, is_local_model_enabled
from db.crud import get_user_by_username, get_user_by_email, create_user, change_user_password, update_user_aliyun_key, get_user_preferences, update_user_preferences, can_user_use_local_model
from schemas.user import User, UserCreate, Token, PasswordChange, AliyunKeyUpdate, AliyunKeyVerifyResponse, UserPreferences, UserPreferencesResponse
router = APIRouter(prefix="/auth", tags=["authentication"])
@@ -247,9 +247,8 @@ async def get_preferences(
):
prefs = get_user_preferences(db, current_user.id)
local_enabled = is_local_model_enabled(db)
available_backends = ["aliyun"]
if local_enabled or current_user.is_superuser:
if can_user_use_local_model(current_user):
available_backends.append("local")
return {
@@ -267,8 +266,7 @@ async def update_preferences(
db: Session = Depends(get_db)
):
if preferences.default_backend == "local":
local_enabled = is_local_model_enabled(db)
if not local_enabled and not current_user.is_superuser:
if not can_user_use_local_model(current_user):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Local model is not available. Please contact administrator."

View File

@@ -285,13 +285,12 @@ async def create_custom_voice_job(
db: Session = Depends(get_db)
):
from core.security import decrypt_api_key
from db.crud import get_user_preferences, is_local_model_enabled
from db.crud import get_user_preferences, can_user_use_local_model
user_prefs = get_user_preferences(db, current_user.id)
preferred_backend = user_prefs.get("default_backend", "aliyun")
local_enabled = is_local_model_enabled(db)
can_use_local = local_enabled or current_user.is_superuser
can_use_local = can_user_use_local_model(current_user)
backend_type = req_data.backend if hasattr(req_data, 'backend') and req_data.backend else preferred_backend
@@ -375,13 +374,12 @@ async def create_voice_design_job(
db: Session = Depends(get_db)
):
from core.security import decrypt_api_key
from db.crud import get_user_preferences, is_local_model_enabled
from db.crud import get_user_preferences, can_user_use_local_model
user_prefs = get_user_preferences(db, current_user.id)
preferred_backend = user_prefs.get("default_backend", "aliyun")
local_enabled = is_local_model_enabled(db)
can_use_local = local_enabled or current_user.is_superuser
can_use_local = can_user_use_local_model(current_user)
backend_type = req_data.backend if hasattr(req_data, 'backend') and req_data.backend else preferred_backend
@@ -476,13 +474,12 @@ async def create_voice_clone_job(
db: Session = Depends(get_db)
):
from core.security import decrypt_api_key
from db.crud import get_user_preferences, is_local_model_enabled
from db.crud import get_user_preferences, can_user_use_local_model
user_prefs = get_user_preferences(db, current_user.id)
preferred_backend = user_prefs.get("default_backend", "aliyun")
local_enabled = is_local_model_enabled(db)
can_use_local = local_enabled or current_user.is_superuser
can_use_local = can_user_use_local_model(current_user)
backend_type = backend if backend else preferred_backend

View File

@@ -15,12 +15,9 @@ from db.crud import (
list_users,
create_user_by_admin,
update_user,
delete_user,
get_system_setting,
update_system_setting,
is_local_model_enabled
delete_user
)
from schemas.user import User, UserCreateByAdmin, UserUpdate, UserListResponse, SystemSettingsUpdate, SystemSettingsResponse
from schemas.user import User, UserCreateByAdmin, UserUpdate, UserListResponse
router = APIRouter(prefix="/users", tags=["users"])
limiter = Limiter(key_func=get_remote_address)
@@ -75,7 +72,8 @@ async def create_user(
username=user_data.username,
email=user_data.email,
hashed_password=hashed_password,
is_superuser=user_data.is_superuser
is_superuser=user_data.is_superuser,
can_use_local_model=user_data.can_use_local_model
)
return user
@@ -139,7 +137,8 @@ async def update_user_info(
email=user_data.email,
hashed_password=hashed_password,
is_active=user_data.is_active,
is_superuser=user_data.is_superuser
is_superuser=user_data.is_superuser,
can_use_local_model=user_data.can_use_local_model
)
if not user:
@@ -170,42 +169,3 @@ async def delete_user_by_id(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found"
)
@router.get("/system/settings", response_model=SystemSettingsResponse)
async def get_system_settings(
current_user: Annotated[User, Depends(require_superuser)],
db: Session = Depends(get_db)
):
local_enabled = is_local_model_enabled(db)
return {"local_model_enabled": local_enabled}
@router.put("/system/settings")
async def update_system_settings(
settings: SystemSettingsUpdate,
current_user: Annotated[User, Depends(require_superuser)],
db: Session = Depends(get_db)
):
from db.models import User
from datetime import datetime
update_system_setting(db, "local_model_enabled", {"enabled": settings.local_model_enabled})
if not settings.local_model_enabled:
users = db.query(User).filter(User.is_superuser == False).all()
migrated_count = 0
for user in users:
prefs = user.user_preferences or {}
if prefs.get("default_backend") == "local":
prefs["default_backend"] = "aliyun"
user.user_preferences = prefs
user.updated_at = datetime.utcnow()
migrated_count += 1
db.commit()
return {
"message": "System settings updated",
"users_migrated": migrated_count
}
return {"message": "System settings updated", "users_migrated": 0}

View File

@@ -30,13 +30,15 @@ def create_user_by_admin(
username: str,
email: str,
hashed_password: str,
is_superuser: bool = False
is_superuser: bool = False,
can_use_local_model: bool = False
) -> User:
user = User(
username=username,
email=email,
hashed_password=hashed_password,
is_superuser=is_superuser
is_superuser=is_superuser,
can_use_local_model=can_use_local_model
)
db.add(user)
db.commit()
@@ -58,7 +60,8 @@ def update_user(
email: Optional[str] = None,
hashed_password: Optional[str] = None,
is_active: Optional[bool] = None,
is_superuser: Optional[bool] = None
is_superuser: Optional[bool] = None,
can_use_local_model: Optional[bool] = None
) -> Optional[User]:
user = get_user_by_id(db, user_id)
if not user:
@@ -74,6 +77,8 @@ def update_user(
user.is_active = is_active
if is_superuser is not None:
user.is_superuser = is_superuser
if can_use_local_model is not None:
user.can_use_local_model = can_use_local_model
user.updated_at = datetime.utcnow()
db.commit()
@@ -264,8 +269,5 @@ def update_system_setting(db: Session, key: str, value: dict) -> SystemSettings:
db.refresh(setting)
return setting
def is_local_model_enabled(db: Session) -> bool:
setting = get_system_setting(db, "local_model_enabled")
if not setting:
return False
return setting.get("enabled", False)
def can_user_use_local_model(user: User) -> bool:
return user.is_superuser or user.can_use_local_model

View File

@@ -0,0 +1,17 @@
from sqlalchemy import create_engine, text
from core.config import settings
def migrate():
engine = create_engine(settings.DATABASE_URL)
with engine.connect() as conn:
conn.execute(text(
"ALTER TABLE users ADD COLUMN can_use_local_model BOOLEAN DEFAULT 0 NOT NULL"
))
conn.execute(text(
"UPDATE users SET can_use_local_model = 1 WHERE is_superuser = 1"
))
conn.commit()
print("Migration completed: Added can_use_local_model column")
if __name__ == "__main__":
migrate()

View File

@@ -21,6 +21,7 @@ class User(Base):
is_active = Column(Boolean, default=True, nullable=False)
is_superuser = Column(Boolean, default=False, nullable=False)
aliyun_api_key = Column(Text, nullable=True)
can_use_local_model = Column(Boolean, default=False, nullable=False)
user_preferences = Column(JSON, nullable=True, default=lambda: {"default_backend": "aliyun", "onboarding_completed": False})
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)

View File

@@ -32,6 +32,7 @@ class User(UserBase):
id: int
is_active: bool
is_superuser: bool
can_use_local_model: bool
created_at: datetime
model_config = ConfigDict(from_attributes=True)
@@ -39,6 +40,7 @@ class User(UserBase):
class UserCreateByAdmin(UserBase):
password: str = Field(..., min_length=8, max_length=128)
is_superuser: bool = False
can_use_local_model: bool = False
@field_validator('password')
@classmethod
@@ -57,6 +59,7 @@ class UserUpdate(BaseModel):
password: Optional[str] = Field(None, min_length=8, max_length=128)
is_active: Optional[bool] = None
is_superuser: Optional[bool] = None
can_use_local_model: Optional[bool] = None
@field_validator('username')
@classmethod
@@ -127,9 +130,3 @@ class UserPreferencesResponse(BaseModel):
default_backend: str = Field(default="aliyun", pattern="^(local|aliyun)$")
onboarding_completed: bool = Field(default=False)
available_backends: list[str] = Field(default=["aliyun"])
class SystemSettingsUpdate(BaseModel):
local_model_enabled: bool
class SystemSettingsResponse(BaseModel):
local_model_enabled: bool

View File

@@ -29,6 +29,7 @@ const userFormSchema = z.object({
password: z.string().optional(),
is_active: z.boolean(),
is_superuser: z.boolean(),
can_use_local_model: z.boolean(),
})
type UserFormValues = z.infer<typeof userFormSchema>
@@ -58,6 +59,7 @@ export function UserDialog({
password: '',
is_active: true,
is_superuser: false,
can_use_local_model: false,
},
})
@@ -69,6 +71,7 @@ export function UserDialog({
password: '',
is_active: user.is_active,
is_superuser: user.is_superuser,
can_use_local_model: user.can_use_local_model,
})
} else {
form.reset({
@@ -77,6 +80,7 @@ export function UserDialog({
password: '',
is_active: true,
is_superuser: false,
can_use_local_model: false,
})
}
}, [user, form])
@@ -178,6 +182,27 @@ export function UserDialog({
)}
/>
<FormField
control={form.control}
name="can_use_local_model"
render={({ field }) => (
<FormItem className="flex flex-row items-start space-x-3 space-y-0">
<FormControl>
<Checkbox
checked={field.value}
onCheckedChange={field.onChange}
/>
</FormControl>
<div className="space-y-1 leading-none">
<FormLabel></FormLabel>
<p className="text-xs text-muted-foreground">
使 TTS
</p>
</div>
</FormItem>
)}
/>
<DialogFooter className="flex-col sm:flex-row gap-2">
<Button
type="button"

View File

@@ -38,6 +38,7 @@ export function UserTable({ users, isLoading, onEdit, onDelete }: UserTableProps
<th className="px-4 py-3 font-medium"></th>
<th className="px-4 py-3 font-medium"></th>
<th className="px-4 py-3 font-medium"></th>
<th className="px-4 py-3 font-medium"></th>
<th className="px-4 py-3 font-medium"></th>
<th className="px-4 py-3 font-medium text-right"></th>
</tr>
@@ -58,6 +59,11 @@ export function UserTable({ users, isLoading, onEdit, onDelete }: UserTableProps
{user.is_superuser ? '超级管理员' : '普通用户'}
</Badge>
</td>
<td className="px-4 py-3">
{(user.is_superuser || user.can_use_local_model) && (
<Badge variant="secondary"></Badge>
)}
</td>
<td className="px-4 py-3">
{new Date(user.created_at).toLocaleString('zh-CN')}
</td>
@@ -129,6 +135,14 @@ export function UserTable({ users, isLoading, onEdit, onDelete }: UserTableProps
{user.is_superuser ? '超级管理员' : '普通用户'}
</Badge>
</div>
<div className="flex justify-between items-center">
<span className="text-muted-foreground">:</span>
{(user.is_superuser || user.can_use_local_model) ? (
<Badge variant="secondary"></Badge>
) : (
<span className="text-xs text-muted-foreground"></span>
)}
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">:</span>
<span className="text-xs">{new Date(user.created_at).toLocaleString('zh-CN')}</span>

View File

@@ -1,5 +1,5 @@
import axios from 'axios'
import type { LoginRequest, LoginResponse, User, PasswordChangeRequest, UserPreferences, SystemSettings } from '@/types/auth'
import type { LoginRequest, LoginResponse, User, PasswordChangeRequest, UserPreferences } from '@/types/auth'
import type { Job, JobCreateResponse, JobListResponse, JobType } from '@/types/job'
import type { Language, Speaker, CustomVoiceForm, VoiceDesignForm, VoiceCloneForm } from '@/types/tts'
import type { UserCreateRequest, UserUpdateRequest, UserListResponse } from '@/types/user'
@@ -210,14 +210,6 @@ export const authApi = {
return response.data
},
getSystemSettings: async (): Promise<SystemSettings> => {
const response = await apiClient.get<SystemSettings>('/users/system/settings')
return response.data
},
updateSystemSettings: async (settings: { local_model_enabled: boolean }): Promise<void> => {
await apiClient.put('/users/system/settings', settings)
},
}
export const ttsApi = {

View File

@@ -1,4 +1,4 @@
import { useState, useEffect } from 'react'
import { useState } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import * as z from 'zod'
@@ -10,7 +10,6 @@ import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { Switch } from '@/components/ui/switch'
import {
Form,
FormControl,
@@ -38,7 +37,6 @@ export default function Settings() {
const [isLoading, setIsLoading] = useState(false)
const [showPasswordDialog, setShowPasswordDialog] = useState(false)
const [isPasswordLoading, setIsPasswordLoading] = useState(false)
const [localModelEnabled, setLocalModelEnabled] = useState(false)
const form = useForm<ApiKeyFormValues>({
resolver: zodResolver(apiKeySchema),
@@ -47,34 +45,6 @@ export default function Settings() {
},
})
useEffect(() => {
if (user?.is_superuser) {
fetchSystemSettings()
}
}, [user])
const fetchSystemSettings = async () => {
try {
const settings = await authApi.getSystemSettings()
setLocalModelEnabled(settings.local_model_enabled)
} catch (error) {
console.error('Failed to fetch system settings:', error)
}
}
const handleToggleLocalModel = async (enabled: boolean) => {
try {
await authApi.updateSystemSettings({ local_model_enabled: enabled })
setLocalModelEnabled(enabled)
toast.success(`本地模型已${enabled ? '启用' : '禁用'}`)
await refetchPreferences()
} catch (error) {
toast.error('更新失败,请重试')
console.error('Failed to update system settings:', error)
}
}
const handleBackendChange = async (value: string) => {
try {
await updatePreferences({ default_backend: value as 'local' | 'aliyun' })
@@ -182,8 +152,10 @@ export default function Settings() {
<Label htmlFor="backend-local" className="flex-1 cursor-pointer">
<div className="font-medium text-sm sm:text-base"></div>
<div className="text-xs sm:text-sm text-muted-foreground">
使 Qwen3-TTS
{!isBackendAvailable('local') && ' (管理员未启用)'}
{!isBackendAvailable('local')
? '请联系管理员开启使用本地模型权限'
: '免费使用本地 Qwen3-TTS 模型'
}
</div>
</Label>
</div>
@@ -291,33 +263,6 @@ export default function Settings() {
</CardContent>
</Card>
{user.is_superuser && (
<Card>
<CardHeader className="p-4 sm:p-6">
<CardTitle className="text-lg sm:text-xl"></CardTitle>
<CardDescription className="text-sm"></CardDescription>
</CardHeader>
<CardContent className="p-4 sm:p-6">
<div className="space-y-3 sm:space-y-4">
<div className="flex items-start sm:items-center justify-between gap-4">
<div className="space-y-0.5 flex-1">
<Label htmlFor="local-model-toggle" className="text-sm sm:text-base"></Label>
<p className="text-xs sm:text-sm text-muted-foreground">
使 Qwen3-TTS
</p>
</div>
<Switch
id="local-model-toggle"
checked={localModelEnabled}
onCheckedChange={handleToggleLocalModel}
className="shrink-0"
/>
</div>
</div>
</CardContent>
</Card>
)}
<Card>
<CardHeader className="p-4 sm:p-6">
<CardTitle className="text-lg sm:text-xl"></CardTitle>

View File

@@ -4,6 +4,7 @@ export interface User {
email: string
is_active: boolean
is_superuser: boolean
can_use_local_model: boolean
created_at: string
}
@@ -35,7 +36,3 @@ export interface UserPreferences {
onboarding_completed: boolean
available_backends?: string[]
}
export interface SystemSettings {
local_model_enabled: boolean
}

View File

@@ -6,6 +6,7 @@ export interface UserCreateRequest {
password: string
is_active: boolean
is_superuser: boolean
can_use_local_model: boolean
}
export interface UserUpdateRequest {
@@ -14,6 +15,7 @@ export interface UserUpdateRequest {
password?: string
is_active?: boolean
is_superuser?: boolean
can_use_local_model?: boolean
}
export interface UserListResponse {