From 99fe7329f7c12fb47bc13a1edc14079ea31da95b Mon Sep 17 00:00:00 2001
From: ShukeBta
Date: Fri, 29 May 2026 15:56:51 +0800
Subject: [PATCH] fix: isolate play profiles per user
---
README.md | 24 +++----
README_EN.md | 22 +++----
docker-compose.yml | 2 +-
internal/handler/handler.go | 2 +-
internal/handler/play_profile.go | 47 +++++++-------
internal/repository/play_profile_repo.go | 8 +++
internal/service/emby_compat.go | 7 ++-
internal/service/emby_compat_test.go | 36 ++++++++++-
internal/service/play_profile.go | 48 +++++++++++++-
internal/service/play_profile_test.go | 80 +++++++++++++++++++++---
web/src/api/play_profiles.ts | 7 +--
web/src/components/Layout.tsx | 2 +-
web/src/pages/ProfileManagementPage.tsx | 36 +++++------
13 files changed, 235 insertions(+), 86 deletions(-)
diff --git a/README.md b/README.md
index 80da051..2b0a708 100644
--- a/README.md
+++ b/README.md
@@ -238,7 +238,7 @@ mkdir -p data cache media downloads
```bash
cat > .env <<'EOF'
# 固定版本;需要升级时改成新的 MediaStationGo-vX.Y.Z 后执行 docker compose pull && docker compose up -d
-MEDIASTATION_IMAGE_TAG=MediaStationGo-v0.0.17
+MEDIASTATION_IMAGE_TAG=MediaStationGo-v0.0.19
MEDIASTATION_HTTP_PORT=18080
# 程序数据和缓存建议放在 MediaStationGo 部署目录下,便于备份和迁移。
@@ -307,7 +307,7 @@ vim docker-compose.yml
#
# 镜像版本:
# 默认拉取 latest;如需固定版本,创建 .env 并写入:
-# MEDIASTATION_IMAGE_TAG=MediaStationGo-v0.0.17
+# MEDIASTATION_IMAGE_TAG=MediaStationGo-v0.0.19
#
# 路径映射总览:
# /data 程序数据目录。保存 SQLite 数据库、JWT secret、系统配置等,必须持久化。
@@ -516,7 +516,7 @@ docker compose up -d
```bash
cat > .env <<'EOF'
-MEDIASTATION_IMAGE_TAG=MediaStationGo-v0.0.17
+MEDIASTATION_IMAGE_TAG=MediaStationGo-v0.0.19
MEDIASTATION_HTTP_PORT=18080
MEDIASTATION_DATA_DIR=./data
MEDIASTATION_CACHE_DIR=./cache
@@ -779,26 +779,26 @@ cd MediaStationGo
| 平台 | 包名示例 |
| --- | --- |
-| Linux x86_64 | `MediaStationGo-v0.0.17-linux-amd64.tar.gz` |
-| Linux ARM64 | `MediaStationGo-v0.0.17-linux-arm64.tar.gz` |
-| Windows x86_64 | `MediaStationGo-v0.0.17-windows-amd64.zip` |
-| macOS Intel | `MediaStationGo-v0.0.17-darwin-amd64.tar.gz` |
-| macOS Apple Silicon | `MediaStationGo-v0.0.17-darwin-arm64.tar.gz` |
+| Linux x86_64 | `MediaStationGo-v0.0.19-linux-amd64.tar.gz` |
+| Linux ARM64 | `MediaStationGo-v0.0.19-linux-arm64.tar.gz` |
+| Windows x86_64 | `MediaStationGo-v0.0.19-windows-amd64.zip` |
+| macOS Intel | `MediaStationGo-v0.0.19-darwin-amd64.tar.gz` |
+| macOS Apple Silicon | `MediaStationGo-v0.0.19-darwin-arm64.tar.gz` |
部署步骤:
```bash
# Linux 示例
-tar -xzf MediaStationGo-v0.0.17-linux-amd64.tar.gz
-cd MediaStationGo-v0.0.17-linux-amd64
+tar -xzf MediaStationGo-v0.0.19-linux-amd64.tar.gz
+cd MediaStationGo-v0.0.19-linux-amd64
MEDIASTATION_APP_PORT=18080 ./mediastation-go
```
Windows:
```powershell
-Expand-Archive .\MediaStationGo-v0.0.17-windows-amd64.zip
-cd .\MediaStationGo-v0.0.17-windows-amd64
+Expand-Archive .\MediaStationGo-v0.0.19-windows-amd64.zip
+cd .\MediaStationGo-v0.0.19-windows-amd64
$env:MEDIASTATION_APP_PORT = "18080"
.\mediastation-go.exe
```
diff --git a/README_EN.md b/README_EN.md
index 580a011..5b485a1 100644
--- a/README_EN.md
+++ b/README_EN.md
@@ -235,7 +235,7 @@ mkdir -p data cache media downloads
```bash
cat > .env <<'EOF'
-MEDIASTATION_IMAGE_TAG=MediaStationGo-v0.0.17
+MEDIASTATION_IMAGE_TAG=MediaStationGo-v0.0.19
MEDIASTATION_HTTP_PORT=18080
MEDIASTATION_DATA_DIR=./data
MEDIASTATION_CACHE_DIR=./cache
@@ -344,7 +344,7 @@ For production, pin a specific release tag instead of using `latest`. Recommende
```bash
cat > .env <<'EOF'
-MEDIASTATION_IMAGE_TAG=MediaStationGo-v0.0.17
+MEDIASTATION_IMAGE_TAG=MediaStationGo-v0.0.19
MEDIASTATION_HTTP_PORT=18080
MEDIASTATION_DATA_DIR=./data
MEDIASTATION_CACHE_DIR=./cache
@@ -593,25 +593,25 @@ Each release provides multi-platform archives:
| Platform | Package example |
| --- | --- |
-| Linux x86_64 | `MediaStationGo-v0.0.17-linux-amd64.tar.gz` |
-| Linux ARM64 | `MediaStationGo-v0.0.17-linux-arm64.tar.gz` |
-| Windows x86_64 | `MediaStationGo-v0.0.17-windows-amd64.zip` |
-| macOS Intel | `MediaStationGo-v0.0.17-darwin-amd64.tar.gz` |
-| macOS Apple Silicon | `MediaStationGo-v0.0.17-darwin-arm64.tar.gz` |
+| Linux x86_64 | `MediaStationGo-v0.0.19-linux-amd64.tar.gz` |
+| Linux ARM64 | `MediaStationGo-v0.0.19-linux-arm64.tar.gz` |
+| Windows x86_64 | `MediaStationGo-v0.0.19-windows-amd64.zip` |
+| macOS Intel | `MediaStationGo-v0.0.19-darwin-amd64.tar.gz` |
+| macOS Apple Silicon | `MediaStationGo-v0.0.19-darwin-arm64.tar.gz` |
Linux example:
```bash
-tar -xzf MediaStationGo-v0.0.17-linux-amd64.tar.gz
-cd MediaStationGo-v0.0.17-linux-amd64
+tar -xzf MediaStationGo-v0.0.19-linux-amd64.tar.gz
+cd MediaStationGo-v0.0.19-linux-amd64
MEDIASTATION_APP_PORT=18080 ./mediastation-go
```
Windows example:
```powershell
-Expand-Archive .\MediaStationGo-v0.0.17-windows-amd64.zip
-cd .\MediaStationGo-v0.0.17-windows-amd64
+Expand-Archive .\MediaStationGo-v0.0.19-windows-amd64.zip
+cd .\MediaStationGo-v0.0.19-windows-amd64
$env:MEDIASTATION_APP_PORT = "18080"
.\mediastation-go.exe
```
diff --git a/docker-compose.yml b/docker-compose.yml
index 0a6bcc5..f352f83 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -17,7 +17,7 @@
#
# 镜像版本:
# 默认拉取 latest;如需固定版本,创建 .env 并写入:
-# MEDIASTATION_IMAGE_TAG=MediaStationGo-v0.0.17
+# MEDIASTATION_IMAGE_TAG=MediaStationGo-v0.0.19
#
# 路径映射总览:
# /data 程序数据目录。保存 SQLite 数据库、JWT secret、系统配置等,必须持久化。
diff --git a/internal/handler/handler.go b/internal/handler/handler.go
index 39eaf3e..8a712f7 100644
--- a/internal/handler/handler.go
+++ b/internal/handler/handler.go
@@ -196,7 +196,7 @@ func Register(r *gin.Engine, cfg *config.Config, log *zap.Logger, svc *service.C
authed.GET("/stats/libraries", statsLibrariesHandler(svc))
authed.GET("/stats/monitor", statsMonitorHandler(svc))
- // Multi-persona play profiles (caller-scoped, admins via ?all=true).
+ // Multi-persona play profiles (caller-scoped).
authed.GET("/play-profiles", listPlayProfilesHandler(svc))
authed.POST("/play-profiles", createPlayProfileHandler(svc))
authed.PUT("/play-profiles/:id", updatePlayProfileHandler(svc))
diff --git a/internal/handler/play_profile.go b/internal/handler/play_profile.go
index edda468..0cb66c3 100644
--- a/internal/handler/play_profile.go
+++ b/internal/handler/play_profile.go
@@ -1,7 +1,7 @@
// Package handler — multi-persona play profile CRUD endpoints.
//
-// Non-admin users see / mutate only their own profiles. Admins see
-// every profile so they can manage child accounts, etc.
+// Every user sees / mutates only their own profiles. Admin user
+// management belongs in a separate admin surface, not this switcher.
package handler
import (
@@ -19,21 +19,10 @@ type verifyPlayProfilePINReq struct {
PIN string `json:"pin"`
}
-// listPlayProfilesHandler returns the caller's profiles, or every
-// profile when the caller is an admin AND ?all=true is set.
+// listPlayProfilesHandler returns only the caller's own profiles.
func listPlayProfilesHandler(svc *service.Container) gin.HandlerFunc {
return func(c *gin.Context) {
uid, _ := c.Get(middleware.CtxUserID)
- role, _ := c.Get(middleware.CtxUserRole)
- if c.Query("all") == "true" && role == "admin" {
- rows, err := svc.PlayProfiles.List(c.Request.Context())
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
- return
- }
- c.JSON(http.StatusOK, rows)
- return
- }
rows, err := svc.PlayProfiles.ListByUser(c.Request.Context(), toString(uid))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
@@ -50,13 +39,13 @@ func createPlayProfileHandler(svc *service.Container) gin.HandlerFunc {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
- // Default the user_id to the caller; admins can override.
uid, _ := c.Get(middleware.CtxUserID)
- role, _ := c.Get(middleware.CtxUserRole)
- if in.UserID == "" || role != "admin" {
- in.UserID = toString(uid)
- }
+ in.UserID = toString(uid)
row, err := svc.PlayProfiles.Create(c.Request.Context(), in)
+ if errors.Is(err, service.ErrPlayProfileLimit) {
+ c.JSON(http.StatusBadRequest, gin.H{"error": "每个用户最多只能创建 3 个观影 Profile"})
+ return
+ }
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
@@ -72,7 +61,16 @@ func updatePlayProfileHandler(svc *service.Container) gin.HandlerFunc {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
- row, err := svc.PlayProfiles.Update(c.Request.Context(), c.Param("id"), in)
+ uid, _ := c.Get(middleware.CtxUserID)
+ row, err := svc.PlayProfiles.UpdateForUser(c.Request.Context(), c.Param("id"), toString(uid), in)
+ if errors.Is(err, service.ErrPlayProfileNotFound) {
+ c.JSON(http.StatusNotFound, gin.H{"error": "profile not found"})
+ return
+ }
+ if errors.Is(err, service.ErrPlayProfileForbidden) {
+ c.JSON(http.StatusForbidden, gin.H{"error": "profile forbidden"})
+ return
+ }
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
@@ -83,7 +81,14 @@ func updatePlayProfileHandler(svc *service.Container) gin.HandlerFunc {
func deletePlayProfileHandler(svc *service.Container) gin.HandlerFunc {
return func(c *gin.Context) {
- if err := svc.PlayProfiles.Delete(c.Request.Context(), c.Param("id")); err != nil {
+ uid, _ := c.Get(middleware.CtxUserID)
+ if err := svc.PlayProfiles.DeleteForUser(c.Request.Context(), c.Param("id"), toString(uid)); errors.Is(err, service.ErrPlayProfileNotFound) {
+ c.JSON(http.StatusNotFound, gin.H{"error": "profile not found"})
+ return
+ } else if errors.Is(err, service.ErrPlayProfileForbidden) {
+ c.JSON(http.StatusForbidden, gin.H{"error": "profile forbidden"})
+ return
+ } else if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
diff --git a/internal/repository/play_profile_repo.go b/internal/repository/play_profile_repo.go
index 6baca63..7dfc4cf 100644
--- a/internal/repository/play_profile_repo.go
+++ b/internal/repository/play_profile_repo.go
@@ -45,6 +45,14 @@ func (r *PlayProfileRepository) ListByUser(ctx context.Context, userID string) (
return rows, err
}
+// CountByUser returns the number of active profiles owned by a user.
+func (r *PlayProfileRepository) CountByUser(ctx context.Context, userID string) (int64, error) {
+ var count int64
+ err := r.db.WithContext(ctx).Model(&model.PlayProfile{}).
+ Where("user_id = ?", userID).Count(&count).Error
+ return count, err
+}
+
// Update applies a partial update to a profile row.
func (r *PlayProfileRepository) Update(ctx context.Context, id string, patch map[string]any) error {
return r.db.WithContext(ctx).Model(&model.PlayProfile{}).
diff --git a/internal/service/emby_compat.go b/internal/service/emby_compat.go
index 3917d36..5e541ab 100644
--- a/internal/service/emby_compat.go
+++ b/internal/service/emby_compat.go
@@ -122,6 +122,7 @@ func (e *EmbyService) FindUser(ctx context.Context, id string) (map[string]any,
}
func (e *EmbyService) userPayload(u *model.User) map[string]any {
+ canDownload := u.Role == "admin"
return map[string]any{
"Id": u.ID,
"Name": u.Username,
@@ -153,9 +154,9 @@ func (e *EmbyService) userPayload(u *model.User) map[string]any {
"EnableVideoPlaybackTranscoding": true,
"EnablePlaybackRemuxing": true,
"EnableLiveTvAccess": false,
- "EnableContentDownloading": true,
- "EnableSyncTranscoding": true,
- "EnableMediaConversion": true,
+ "EnableContentDownloading": canDownload,
+ "EnableSyncTranscoding": canDownload,
+ "EnableMediaConversion": canDownload,
"EnableAllChannels": true,
"EnableAllFolders": true,
"EnableAllDevices": true,
diff --git a/internal/service/emby_compat_test.go b/internal/service/emby_compat_test.go
index 4510d0a..17b8d63 100644
--- a/internal/service/emby_compat_test.go
+++ b/internal/service/emby_compat_test.go
@@ -127,13 +127,47 @@ func TestEmbyRootItemsExposeLibraries(t *testing.T) {
}
}
+func TestEmbyUserPolicyDisablesDownloadsForViewers(t *testing.T) {
+ svc := newTestEmbyService(t)
+ viewer := &model.User{Username: "viewer", Role: "user", Tier: "free", IsActive: true}
+ admin := &model.User{Username: "admin", Role: "admin", Tier: "plus", IsActive: true}
+ if err := svc.repo.User.Create(t.Context(), viewer); err != nil {
+ t.Fatalf("create viewer: %v", err)
+ }
+ if err := svc.repo.User.Create(t.Context(), admin); err != nil {
+ t.Fatalf("create admin: %v", err)
+ }
+
+ viewerPayload, err := svc.FindUser(t.Context(), viewer.ID)
+ if err != nil {
+ t.Fatalf("viewer payload: %v", err)
+ }
+ adminPayload, err := svc.FindUser(t.Context(), admin.ID)
+ if err != nil {
+ t.Fatalf("admin payload: %v", err)
+ }
+ viewerPolicy := viewerPayload["Policy"].(map[string]any)
+ adminPolicy := adminPayload["Policy"].(map[string]any)
+ if viewerPolicy["EnableMediaPlayback"] != true {
+ t.Fatalf("viewer must keep playback enabled: %#v", viewerPolicy)
+ }
+ if viewerPolicy["EnableContentDownloading"] != false ||
+ viewerPolicy["EnableSyncTranscoding"] != false ||
+ viewerPolicy["EnableMediaConversion"] != false {
+ t.Fatalf("viewer must not be allowed to download/sync media: %#v", viewerPolicy)
+ }
+ if adminPolicy["EnableContentDownloading"] != true {
+ t.Fatalf("admin should keep downloading capability: %#v", adminPolicy)
+ }
+}
+
func newTestEmbyService(t *testing.T) *EmbyService {
t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatalf("open db: %v", err)
}
- if err := db.AutoMigrate(&model.Library{}, &model.Series{}, &model.Media{}, &model.Favorite{}, &model.PlaybackHistory{}); err != nil {
+ if err := db.AutoMigrate(&model.Library{}, &model.Series{}, &model.Media{}, &model.Favorite{}, &model.PlaybackHistory{}, &model.User{}); err != nil {
t.Fatalf("migrate: %v", err)
}
repos := repository.New(db)
diff --git a/internal/service/play_profile.go b/internal/service/play_profile.go
index 599435d..b6ae0fe 100644
--- a/internal/service/play_profile.go
+++ b/internal/service/play_profile.go
@@ -29,10 +29,13 @@ type PlayProfileService struct {
repo *repository.Container
}
+const MaxPlayProfilesPerUser = 3
+
var (
ErrPlayProfileNotFound = errors.New("profile not found")
ErrPlayProfileForbidden = errors.New("profile forbidden")
ErrPlayProfilePINInvalid = errors.New("pin invalid")
+ ErrPlayProfileLimit = errors.New("profile limit reached")
)
// NewPlayProfileService is the constructor.
@@ -108,6 +111,13 @@ func (s *PlayProfileService) Create(ctx context.Context, in PlayProfileInput) (*
if err := validateProfileInput(in, true); err != nil {
return nil, err
}
+ count, err := s.repo.PlayProfile.CountByUser(ctx, in.UserID)
+ if err != nil {
+ return nil, err
+ }
+ if count >= MaxPlayProfilesPerUser {
+ return nil, ErrPlayProfileLimit
+ }
libsBlob, _ := json.Marshal(in.AllowedLibraryIDs)
p := &model.PlayProfile{
UserID: in.UserID,
@@ -137,6 +147,21 @@ func (s *PlayProfileService) Create(ctx context.Context, in PlayProfileInput) (*
return &v, nil
}
+// UpdateForUser applies a patch only when the profile belongs to userID.
+func (s *PlayProfileService) UpdateForUser(ctx context.Context, id, userID string, in PlayProfileInput) (*ProfileView, error) {
+ row, err := s.repo.PlayProfile.FindByID(ctx, id)
+ if err != nil {
+ return nil, err
+ }
+ if row == nil {
+ return nil, ErrPlayProfileNotFound
+ }
+ if row.UserID != userID {
+ return nil, ErrPlayProfileForbidden
+ }
+ return s.updateExisting(ctx, row, in)
+}
+
// Update applies a patch to an existing profile.
func (s *PlayProfileService) Update(ctx context.Context, id string, in PlayProfileInput) (*ProfileView, error) {
row, err := s.repo.PlayProfile.FindByID(ctx, id)
@@ -146,6 +171,10 @@ func (s *PlayProfileService) Update(ctx context.Context, id string, in PlayProfi
if row == nil {
return nil, ErrPlayProfileNotFound
}
+ return s.updateExisting(ctx, row, in)
+}
+
+func (s *PlayProfileService) updateExisting(ctx context.Context, row *model.PlayProfile, in PlayProfileInput) (*ProfileView, error) {
if err := validateProfileInput(in, false); err != nil {
return nil, err
}
@@ -175,10 +204,10 @@ func (s *PlayProfileService) Update(ctx context.Context, id string, in PlayProfi
return nil, err
}
}
- if err := s.repo.PlayProfile.Update(ctx, id, patch); err != nil {
+ if err := s.repo.PlayProfile.Update(ctx, row.ID, patch); err != nil {
return nil, err
}
- row, err = s.repo.PlayProfile.FindByID(ctx, id)
+ row, err := s.repo.PlayProfile.FindByID(ctx, row.ID)
if err != nil || row == nil {
return nil, err
}
@@ -191,6 +220,21 @@ func (s *PlayProfileService) Delete(ctx context.Context, id string) error {
return s.repo.PlayProfile.Delete(ctx, id)
}
+// DeleteForUser removes a profile only when it belongs to userID.
+func (s *PlayProfileService) DeleteForUser(ctx context.Context, id, userID string) error {
+ row, err := s.repo.PlayProfile.FindByID(ctx, id)
+ if err != nil {
+ return err
+ }
+ if row == nil {
+ return ErrPlayProfileNotFound
+ }
+ if row.UserID != userID {
+ return ErrPlayProfileForbidden
+ }
+ return s.repo.PlayProfile.Delete(ctx, id)
+}
+
// VerifyPIN validates that the caller can switch to a PIN-protected profile.
func (s *PlayProfileService) VerifyPIN(ctx context.Context, id, userID, pin string) (*ProfileView, error) {
row, err := s.repo.PlayProfile.FindByID(ctx, id)
diff --git a/internal/service/play_profile_test.go b/internal/service/play_profile_test.go
index 6d44f99..c6d438a 100644
--- a/internal/service/play_profile_test.go
+++ b/internal/service/play_profile_test.go
@@ -11,7 +11,8 @@ import (
"gorm.io/gorm"
)
-func TestPlayProfileVerifyPIN(t *testing.T) {
+func newPlayProfileTestService(t *testing.T) *PlayProfileService {
+ t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatal(err)
@@ -19,7 +20,11 @@ func TestPlayProfileVerifyPIN(t *testing.T) {
if err := db.AutoMigrate(&model.PlayProfile{}); err != nil {
t.Fatal(err)
}
- service := NewPlayProfileService(zap.NewNop(), repository.New(db))
+ return NewPlayProfileService(zap.NewNop(), repository.New(db))
+}
+
+func TestPlayProfileVerifyPIN(t *testing.T) {
+ service := newPlayProfileTestService(t)
profile, err := service.Create(t.Context(), PlayProfileInput{
UserID: "user-1",
Name: "成人模式",
@@ -43,14 +48,7 @@ func TestPlayProfileVerifyPIN(t *testing.T) {
}
func TestPlayProfileCreateRequiresPINWhenEnabled(t *testing.T) {
- db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
- if err != nil {
- t.Fatal(err)
- }
- if err := db.AutoMigrate(&model.PlayProfile{}); err != nil {
- t.Fatal(err)
- }
- service := NewPlayProfileService(zap.NewNop(), repository.New(db))
+ service := newPlayProfileTestService(t)
if _, err := service.Create(t.Context(), PlayProfileInput{
UserID: "user-1",
Name: "锁定模式",
@@ -59,3 +57,65 @@ func TestPlayProfileCreateRequiresPINWhenEnabled(t *testing.T) {
t.Fatal("expected PIN-required profile create to fail without PIN")
}
}
+
+func TestPlayProfileCreateLimitIsPerUser(t *testing.T) {
+ service := newPlayProfileTestService(t)
+
+ for i := 1; i <= MaxPlayProfilesPerUser; i++ {
+ if _, err := service.Create(t.Context(), PlayProfileInput{
+ UserID: "user-1",
+ Name: "模式 " + string(rune('0'+i)),
+ }); err != nil {
+ t.Fatalf("create profile %d: %v", i, err)
+ }
+ }
+
+ if _, err := service.Create(t.Context(), PlayProfileInput{
+ UserID: "user-1",
+ Name: "超限模式",
+ }); !errors.Is(err, ErrPlayProfileLimit) {
+ t.Fatalf("expected limit error, got %v", err)
+ }
+
+ if _, err := service.Create(t.Context(), PlayProfileInput{
+ UserID: "user-2",
+ Name: "另一个用户的模式",
+ }); err != nil {
+ t.Fatalf("different user should have independent limit: %v", err)
+ }
+}
+
+func TestPlayProfileUpdateDeleteRequireOwner(t *testing.T) {
+ service := newPlayProfileTestService(t)
+ profile, err := service.Create(t.Context(), PlayProfileInput{
+ UserID: "user-1",
+ Name: "私人模式",
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ if _, err := service.UpdateForUser(t.Context(), profile.ID, "user-2", PlayProfileInput{
+ Name: "越权修改",
+ }); !errors.Is(err, ErrPlayProfileForbidden) {
+ t.Fatalf("expected forbidden update, got %v", err)
+ }
+
+ if err := service.DeleteForUser(t.Context(), profile.ID, "user-2"); !errors.Is(err, ErrPlayProfileForbidden) {
+ t.Fatalf("expected forbidden delete, got %v", err)
+ }
+
+ updated, err := service.UpdateForUser(t.Context(), profile.ID, "user-1", PlayProfileInput{
+ Name: "已修改",
+ })
+ if err != nil {
+ t.Fatalf("owner update failed: %v", err)
+ }
+ if updated.Name != "已修改" || updated.UserID != "user-1" {
+ t.Fatalf("unexpected updated profile: %+v", updated)
+ }
+
+ if err := service.DeleteForUser(t.Context(), profile.ID, "user-1"); err != nil {
+ t.Fatalf("owner delete failed: %v", err)
+ }
+}
diff --git a/web/src/api/play_profiles.ts b/web/src/api/play_profiles.ts
index cf8e1be..502a440 100644
--- a/web/src/api/play_profiles.ts
+++ b/web/src/api/play_profiles.ts
@@ -23,12 +23,9 @@ export interface PlayProfilePINVerifyResponse {
expires_at: string
}
-// playProfilesAPI wraps /play-profiles. The admin variant adds ?all=true.
+// playProfilesAPI wraps caller-scoped /play-profiles.
export const playProfilesAPI = {
- list: (all = false) =>
- api
- .get('/play-profiles', { params: all ? { all: 'true' } : {} })
- .then((r) => r.data),
+ list: () => api.get('/play-profiles').then((r) => r.data),
create: (input: PlayProfileInput) =>
api.post('/play-profiles', input).then((r) => r.data),
diff --git a/web/src/components/Layout.tsx b/web/src/components/Layout.tsx
index 9d1b714..afba076 100644
--- a/web/src/components/Layout.tsx
+++ b/web/src/components/Layout.tsx
@@ -67,7 +67,7 @@ export function Layout() {
return
}
playProfilesAPI
- .list(false)
+ .list()
.then((rows) => {
setProfiles(rows)
const active = rows.find((p) => p.id === activeProfileId)
diff --git a/web/src/pages/ProfileManagementPage.tsx b/web/src/pages/ProfileManagementPage.tsx
index 702d7c3..008b96e 100644
--- a/web/src/pages/ProfileManagementPage.tsx
+++ b/web/src/pages/ProfileManagementPage.tsx
@@ -10,14 +10,15 @@ import { confirmAction } from '../components/ConfirmDialog'
import { requestPIN } from '../components/PinDialog'
import type { Library, PlayProfile } from '../types'
+const MAX_PLAY_PROFILES = 3
+
// ProfileManagementPage replicates the Vue ProfileManagementView. It
-// lets a user (or admin) define multiple "viewing personas" with
+// lets each user define private "viewing personas" with
// different content-rating gates, library access, and player defaults.
//
// All persistence is real: data is written to /api/play-profiles which
// is backed by the Go PlayProfileService.
export function ProfileManagementPage() {
- const isAdmin = useAuthStore((s) => s.user?.role === 'admin')
const userID = useAuthStore((s) => s.user?.id ?? '')
const activeProfileId = usePlayProfileStore((s) => s.activeProfileId)
const setActiveProfile = usePlayProfileStore((s) => s.setActiveProfile)
@@ -32,7 +33,7 @@ export function ProfileManagementPage() {
setLoading(true)
try {
const [p, l] = await Promise.all([
- playProfilesAPI.list(isAdmin),
+ playProfilesAPI.list(),
libraryAPI.list().catch(() => [] as Library[]),
])
setProfiles(p)
@@ -44,7 +45,7 @@ export function ProfileManagementPage() {
useEffect(() => {
refresh().catch(() => undefined)
- }, [isAdmin])
+ }, [])
const onDelete = async (p: PlayProfile) => {
if (!(await confirmAction({ title: '删除播放档案', message: `确定删除 Profile「${p.name}」?`, confirmText: '删除' }))) return
@@ -60,6 +61,10 @@ export function ProfileManagementPage() {
}
const openCreate = () => {
+ if (profiles.length >= MAX_PLAY_PROFILES) {
+ toast.error(`每个用户最多只能创建 ${MAX_PLAY_PROFILES} 个观影 Profile`)
+ return
+ }
setEditing(null)
setShowForm(true)
}
@@ -105,10 +110,18 @@ export function ProfileManagementPage() {
-