Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { Switch } from '$ui/switch'
import { Button } from '$ui/button'
import { Label } from '$ui/label'
import { Input } from '$ui/input'
import { untrack } from 'svelte'

interface Props {
open: boolean
Expand Down Expand Up @@ -47,25 +48,28 @@ let formError = $state('')
*/
$effect(() => {
if (!open) return
name = target?.name ?? ''
slug = target?.slug ?? ''
description = target?.description ?? ''
coverImage = target?.coverImage ?? ''
parentId = target?.parentId != null ? String(target.parentId) : ''
sortOrder = target?.sortOrder ?? 0
status = target?.status ?? 1
isFeatured = target?.isFeatured ?? false
seoTitle = target?.seoTitle ?? ''
seoDescription = target?.seoDescription ?? ''
// 回填写入不参与依赖收集,否则表单字段会被 effect 订阅,键入即触发重跑并覆盖用户输入。
untrack(() => {
name = target?.name ?? ''
slug = target?.slug ?? ''
description = target?.description ?? ''
coverImage = target?.coverImage ?? ''
parentId = target?.parentId != null ? String(target.parentId) : ''
sortOrder = target?.sortOrder ?? 0
status = target?.status ?? 1
isFeatured = target?.isFeatured ?? false
seoTitle = target?.seoTitle ?? ''
seoDescription = target?.seoDescription ?? ''

// 英文翻译行允许按字段缺失,缺失字段回填为空串。
const en = target?.translations?.find(row => row.locale === 'en') ?? null
enName = en?.name ?? ''
enDescription = en?.description ?? ''
enSeoTitle = en?.seoTitle ?? ''
enSeoDescription = en?.seoDescription ?? ''
enSnapshot = JSON.stringify([enName, enDescription, enSeoTitle, enSeoDescription])
formError = ''
// 英文翻译行允许按字段缺失,缺失字段回填为空串。
const en = target?.translations?.find(row => row.locale === 'en') ?? null
enName = en?.name ?? ''
enDescription = en?.description ?? ''
enSeoTitle = en?.seoTitle ?? ''
enSeoDescription = en?.seoDescription ?? ''
enSnapshot = JSON.stringify([enName, enDescription, enSeoTitle, enSeoDescription])
formError = ''
})
})

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Switch } from '$ui/switch'
import { Button } from '$ui/button'
import { Label } from '$ui/label'
import { Input } from '$ui/input'
import { untrack } from 'svelte'

interface Props {
open: boolean
Expand Down Expand Up @@ -34,18 +35,21 @@ let formError = $state('')

$effect(() => {
if (!open) return
value = target?.value ?? ''
label = target?.label ?? ''
description = target?.description ?? ''
status = (target?.status ?? 1) as DictStatus
sortOrder = target?.sortOrder ?? 0

// 英文翻译行允许按字段缺失,缺失字段回填为空串。
const en = target?.translations?.find(row => row.locale === 'en') ?? null
enLabel = en?.label ?? ''
enDescription = en?.description ?? ''
enSnapshot = JSON.stringify([enLabel, enDescription])
formError = ''
// 回填写入不参与依赖收集,否则表单字段会被 effect 订阅,键入即触发重跑并覆盖用户输入。
untrack(() => {
value = target?.value ?? ''
label = target?.label ?? ''
description = target?.description ?? ''
status = (target?.status ?? 1) as DictStatus
sortOrder = target?.sortOrder ?? 0

// 英文翻译行允许按字段缺失,缺失字段回填为空串。
const en = target?.translations?.find(row => row.locale === 'en') ?? null
enLabel = en?.label ?? ''
enDescription = en?.description ?? ''
enSnapshot = JSON.stringify([enLabel, enDescription])
formError = ''
})
})

// 组装英文翻译补丁,存在既有翻译或任一字段非空时携带。
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Switch } from '$ui/switch'
import { Button } from '$ui/button'
import { Label } from '$ui/label'
import { Input } from '$ui/input'
import { untrack } from 'svelte'

interface Props {
open: boolean
Expand Down Expand Up @@ -34,18 +35,21 @@ let formError = $state('')

$effect(() => {
if (!open) return
code = target?.code ?? ''
name = target?.name ?? ''
description = target?.description ?? ''
status = (target?.status ?? 1) as DictStatus
sortOrder = target?.sortOrder ?? 0

// 英文翻译行允许按字段缺失,缺失字段回填为空串。
const en = target?.translations?.find(row => row.locale === 'en') ?? null
enName = en?.name ?? ''
enDescription = en?.description ?? ''
enSnapshot = JSON.stringify([enName, enDescription])
formError = ''
// 回填写入不参与依赖收集,否则表单字段会被 effect 订阅,键入即触发重跑并覆盖用户输入。
untrack(() => {
code = target?.code ?? ''
name = target?.name ?? ''
description = target?.description ?? ''
status = (target?.status ?? 1) as DictStatus
sortOrder = target?.sortOrder ?? 0

// 英文翻译行允许按字段缺失,缺失字段回填为空串。
const en = target?.translations?.find(row => row.locale === 'en') ?? null
enName = en?.name ?? ''
enDescription = en?.description ?? ''
enSnapshot = JSON.stringify([enName, enDescription])
formError = ''
})
})

// 组装英文翻译补丁,存在既有翻译或任一字段非空时携带。
Expand Down
30 changes: 17 additions & 13 deletions apps/admin/src/lib/components/admin/tag/tag-form-dialog.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { Switch } from '$ui/switch'
import { Button } from '$ui/button'
import { Label } from '$ui/label'
import { Input } from '$ui/input'
import { untrack } from 'svelte'

interface Props {
open: boolean
Expand Down Expand Up @@ -39,19 +40,22 @@ let formError = $state('')
*/
$effect(() => {
if (!open) return
name = target?.name ?? ''
slug = target?.slug ?? ''
color = target?.color || '#808080'
description = target?.description ?? ''
status = target?.status ?? 1
isHot = target?.isHot ?? false

// 英文翻译行允许按字段缺失,缺失字段回填为空串。
const en = target?.translations?.find(row => row.locale === 'en') ?? null
enName = en?.name ?? ''
enDescription = en?.description ?? ''
enSnapshot = JSON.stringify([enName, enDescription])
formError = ''
// 回填写入不参与依赖收集,否则表单字段会被 effect 订阅,键入即触发重跑并覆盖用户输入。
untrack(() => {
name = target?.name ?? ''
slug = target?.slug ?? ''
color = target?.color || '#808080'
description = target?.description ?? ''
status = target?.status ?? 1
isHot = target?.isHot ?? false

// 英文翻译行允许按字段缺失,缺失字段回填为空串。
const en = target?.translations?.find(row => row.locale === 'en') ?? null
enName = en?.name ?? ''
enDescription = en?.description ?? ''
enSnapshot = JSON.stringify([enName, enDescription])
formError = ''
})
})

/**
Expand Down
8 changes: 4 additions & 4 deletions server/docs/api/media-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
- **静态访问**: 服务启动时按 `media.base_url` 挂载静态目录(`internal/router/router.go` 的 `engine.Static`),`fileUrl` 可直接公开访问且目录列表关闭;生产部署经 `deploy/nginx.conf` 的 `location /uploads/` 反代到该静态服务
- **单文件上限**: `media.max_size_mb` 配置,默认 10MB
- **允许类型**: `media.allowed_types` 白名单,默认 `image/jpeg`、`image/png`、`image/gif`、`image/webp`、`application/pdf`;校验对象是内容嗅探结果(`http.DetectContentType`),客户端声明的文件名与 Content-Type 均不参与判定,白名单为空表示不限制
- **存储扩展名**: 命中白名单映射的上述 5 种类型按嗅探结果推导扩展名,其余类型沿用原始扩展名;`svg`、`html` 等可承载脚本的类型不在映射内
- **存储扩展名**: 一律由内容嗅探结果推导,仅上述 5 种类型可确定存储扩展名,客户端提供的文件名不参与存储命名;命中白名单但无法确定存储扩展名的类型会被拒绝,`svg`、`html` 等可承载脚本的类型刻意不在映射内
- **文件命名**: 上传后以 UUID 重命名,按年月分目录归档
- **目录创建**: 上传目录由上传动作按 `0755` 创建;就绪探针 `pkg/storage.CheckWritable` 以真实写入探测目录可写性

Expand Down Expand Up @@ -81,7 +81,7 @@ curl -X POST http://localhost:3000/api/media/upload \
| data.uploader | object | 否 | 上传者窄化视图,仅普通上传路径输出 |

> `data.uploader` 为 `domain.UploaderPublic` 窄化视图,仅含 `id`、`username`、`nickname`、`avatar`;
> 秒传去重路径复用 `GetByFileHash` 查询结果,未预加载上传者关联,该键整体省略。
> 秒传去重路径复用 `GetByFileHashAndUploader` 查询结果,未预加载上传者关联,该键整体省略。
> 上传者 IP `uploadIP` 在实体上为 `json:"-"`,任何响应都不输出。

#### 响应示例
Expand Down Expand Up @@ -111,11 +111,11 @@ curl -X POST http://localhost:3000/api/media/upload \

| 状态码 | 说明 |
|--------|------|
| 400 | 表单缺少 file 字段、请求参数不合法:文件大小超过限制 / 文件类型不在白名单(哨兵错误 `ErrInvalidRequest`) |
| 400 | 表单缺少 file 字段、请求参数不合法:文件大小超过限制 / 文件类型不在白名单 / 内容类型无法确定安全的存储扩展名(后两者哨兵错误均为 `ErrInvalidRequest`,文案可区分) |
| 401 | 未登录或令牌无效 |
| 500 | 打开或读取上传文件失败、创建目录或写入文件失败、保存媒体记录失败(错误原文仅落日志) |

> 相同内容的文件会通过 SHA256 哈希命中已有记录,返回已存在的媒体文件(秒传去重);
> 同一上传者重复上传相同内容时会通过 SHA256 哈希命中已有记录,返回已存在的媒体文件(秒传去重);
> 哈希比对先于类型白名单校验,白名单调整后旧文件仍可按哈希命中。

### 2. 获取文件详情
Expand Down
1 change: 1 addition & 0 deletions server/internal/config/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
- `server.port` 超出 1 至 65535。
- `database.host`、`database.username`、`database.dbname` 为空。
- `token.access_expire` 或 `token.refresh_expire` 不为正数。
- `media.max_size_mb` 不为正数。
- `rbac.role_hierarchy` 或 `rbac.role_permissions` 缺少 superadmin、admin、editor、user 任一类角色的定义。
- `i18n.supported_languages` 为空,或 `i18n.default_language` 不在该列表内。
- `security.trusted_proxies` 含空项、非法 IP 或 CIDR,或出现 `0.0.0.0/0` 与 `::/0` 这类覆盖全部地址的取值。
Expand Down
7 changes: 6 additions & 1 deletion server/internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ type RBACConfig struct {
type MediaConfig struct {
UploadDir string `mapstructure:"upload_dir"` // 本地存储目录
BaseURL string `mapstructure:"base_url"` // 文件访问 URL 前缀
MaxSizeMB int `mapstructure:"max_size_mb"` // 单文件大小上限,单位 MB
MaxSizeMB int `mapstructure:"max_size_mb"` // 单文件大小上限,单位 MB,必须为正数
AllowedTypes []string `mapstructure:"allowed_types"` // 允许的 MIME 类型,空表示不限制
}

Expand Down Expand Up @@ -388,6 +388,11 @@ func validateConfig(cfg *Config) error {
return fmt.Errorf("刷新令牌过期时间必须大于0")
}

// 媒体大小上限必须为正,非正取值会让上传读取被截断而声明大小照原样落库。
if cfg.Media.MaxSizeMB <= 0 {
return fmt.Errorf("无效的媒体单文件大小上限: %dMB", cfg.Media.MaxSizeMB)
}

// RBAC 配置校验:四类角色必须全部登记层级与权限。
for _, role := range []string{"superadmin", "admin", "editor", "user"} {
if _, ok := cfg.RBAC.RoleHierarchy[role]; !ok {
Expand Down
14 changes: 14 additions & 0 deletions server/internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ func validTestConfig() *Config {
return &Config{
Server: ServerConfig{Port: 3000},
Database: DatabaseConfig{Host: "localhost", Username: "root", DBName: "blog"},
Media: MediaConfig{MaxSizeMB: 10},
Token: TokenConfig{
AccessExpire: 15,
RefreshExpire: 168,
Expand Down Expand Up @@ -113,6 +114,19 @@ func TestValidateConfigAcceptsValidConfig(t *testing.T) {
}
}

// TestValidateConfigRejectsNonPositiveMediaMaxSize 验证媒体单文件大小上限非正即拒绝启动。
// 上限为零会让上传读取被截断为一个字节,而声明大小照原样落库,存储内容与记录大小不一致。
func TestValidateConfigRejectsNonPositiveMediaMaxSize(t *testing.T) {
for _, maxSizeMB := range []int{0, -1} {
cfg := validTestConfig()
cfg.Media.MaxSizeMB = maxSizeMB

if err := validateConfig(cfg); err == nil {
t.Errorf("media.max_size_mb = %d,应返回错误", maxSizeMB)
}
}
}

// TestValidateConfigRejectsEmptyI18NSupportedLanguages 验证 i18n 白名单为空即拒绝启动。
func TestValidateConfigRejectsEmptyI18NSupportedLanguages(t *testing.T) {
cfg := validTestConfig()
Expand Down
11 changes: 11 additions & 0 deletions server/internal/handler/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,17 @@ func (h *UserHandler) CreateUser(c *gin.Context) {
return
}

// 拥有 user:create 权限的管理员可借此创建超级管理员,从而获得 system:config 等管理员不具备的权限,因此在调用服务层前按角色可分配范围拦截。
currentUserRole, exists := c.Get("userRole")
if !exists {
response.Unauthorized(c, "无法获取用户权限信息")
return
}
if req.Role != "" && !h.userService.CanUserManageRole(currentUserRole.(string), req.Role) {
response.Forbidden(c, "权限不足,无法分配该角色")
return
}

// 调用服务层创建用户
user, err := h.userService.CreateUser(&req)
if err != nil {
Expand Down
Loading
Loading