fix: isolate play profiles per user

This commit is contained in:
ShukeBta
2026-05-29 15:56:51 +08:00
parent 633a8cf715
commit 99fe7329f7
13 changed files with 235 additions and 86 deletions
+12 -12
View File
@@ -238,7 +238,7 @@ mkdir -p data cache media downloads
```bash ```bash
cat > .env <<'EOF' cat > .env <<'EOF'
# 固定版本;需要升级时改成新的 MediaStationGo-vX.Y.Z 后执行 docker compose pull && docker compose up -d # 固定版本;需要升级时改成新的 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 MEDIASTATION_HTTP_PORT=18080
# 程序数据和缓存建议放在 MediaStationGo 部署目录下,便于备份和迁移。 # 程序数据和缓存建议放在 MediaStationGo 部署目录下,便于备份和迁移。
@@ -307,7 +307,7 @@ vim docker-compose.yml
# #
# 镜像版本: # 镜像版本:
# 默认拉取 latest;如需固定版本,创建 .env 并写入: # 默认拉取 latest;如需固定版本,创建 .env 并写入:
# MEDIASTATION_IMAGE_TAG=MediaStationGo-v0.0.17 # MEDIASTATION_IMAGE_TAG=MediaStationGo-v0.0.19
# #
# 路径映射总览: # 路径映射总览:
# /data 程序数据目录。保存 SQLite 数据库、JWT secret、系统配置等,必须持久化。 # /data 程序数据目录。保存 SQLite 数据库、JWT secret、系统配置等,必须持久化。
@@ -516,7 +516,7 @@ docker compose up -d
```bash ```bash
cat > .env <<'EOF' cat > .env <<'EOF'
MEDIASTATION_IMAGE_TAG=MediaStationGo-v0.0.17 MEDIASTATION_IMAGE_TAG=MediaStationGo-v0.0.19
MEDIASTATION_HTTP_PORT=18080 MEDIASTATION_HTTP_PORT=18080
MEDIASTATION_DATA_DIR=./data MEDIASTATION_DATA_DIR=./data
MEDIASTATION_CACHE_DIR=./cache MEDIASTATION_CACHE_DIR=./cache
@@ -779,26 +779,26 @@ cd MediaStationGo
| 平台 | 包名示例 | | 平台 | 包名示例 |
| --- | --- | | --- | --- |
| Linux x86_64 | `MediaStationGo-v0.0.17-linux-amd64.tar.gz` | | Linux x86_64 | `MediaStationGo-v0.0.19-linux-amd64.tar.gz` |
| Linux ARM64 | `MediaStationGo-v0.0.17-linux-arm64.tar.gz` | | Linux ARM64 | `MediaStationGo-v0.0.19-linux-arm64.tar.gz` |
| Windows x86_64 | `MediaStationGo-v0.0.17-windows-amd64.zip` | | Windows x86_64 | `MediaStationGo-v0.0.19-windows-amd64.zip` |
| macOS Intel | `MediaStationGo-v0.0.17-darwin-amd64.tar.gz` | | macOS Intel | `MediaStationGo-v0.0.19-darwin-amd64.tar.gz` |
| macOS Apple Silicon | `MediaStationGo-v0.0.17-darwin-arm64.tar.gz` | | macOS Apple Silicon | `MediaStationGo-v0.0.19-darwin-arm64.tar.gz` |
部署步骤: 部署步骤:
```bash ```bash
# Linux 示例 # Linux 示例
tar -xzf MediaStationGo-v0.0.17-linux-amd64.tar.gz tar -xzf MediaStationGo-v0.0.19-linux-amd64.tar.gz
cd MediaStationGo-v0.0.17-linux-amd64 cd MediaStationGo-v0.0.19-linux-amd64
MEDIASTATION_APP_PORT=18080 ./mediastation-go MEDIASTATION_APP_PORT=18080 ./mediastation-go
``` ```
Windows: Windows:
```powershell ```powershell
Expand-Archive .\MediaStationGo-v0.0.17-windows-amd64.zip Expand-Archive .\MediaStationGo-v0.0.19-windows-amd64.zip
cd .\MediaStationGo-v0.0.17-windows-amd64 cd .\MediaStationGo-v0.0.19-windows-amd64
$env:MEDIASTATION_APP_PORT = "18080" $env:MEDIASTATION_APP_PORT = "18080"
.\mediastation-go.exe .\mediastation-go.exe
``` ```
+11 -11
View File
@@ -235,7 +235,7 @@ mkdir -p data cache media downloads
```bash ```bash
cat > .env <<'EOF' cat > .env <<'EOF'
MEDIASTATION_IMAGE_TAG=MediaStationGo-v0.0.17 MEDIASTATION_IMAGE_TAG=MediaStationGo-v0.0.19
MEDIASTATION_HTTP_PORT=18080 MEDIASTATION_HTTP_PORT=18080
MEDIASTATION_DATA_DIR=./data MEDIASTATION_DATA_DIR=./data
MEDIASTATION_CACHE_DIR=./cache MEDIASTATION_CACHE_DIR=./cache
@@ -344,7 +344,7 @@ For production, pin a specific release tag instead of using `latest`. Recommende
```bash ```bash
cat > .env <<'EOF' cat > .env <<'EOF'
MEDIASTATION_IMAGE_TAG=MediaStationGo-v0.0.17 MEDIASTATION_IMAGE_TAG=MediaStationGo-v0.0.19
MEDIASTATION_HTTP_PORT=18080 MEDIASTATION_HTTP_PORT=18080
MEDIASTATION_DATA_DIR=./data MEDIASTATION_DATA_DIR=./data
MEDIASTATION_CACHE_DIR=./cache MEDIASTATION_CACHE_DIR=./cache
@@ -593,25 +593,25 @@ Each release provides multi-platform archives:
| Platform | Package example | | Platform | Package example |
| --- | --- | | --- | --- |
| Linux x86_64 | `MediaStationGo-v0.0.17-linux-amd64.tar.gz` | | Linux x86_64 | `MediaStationGo-v0.0.19-linux-amd64.tar.gz` |
| Linux ARM64 | `MediaStationGo-v0.0.17-linux-arm64.tar.gz` | | Linux ARM64 | `MediaStationGo-v0.0.19-linux-arm64.tar.gz` |
| Windows x86_64 | `MediaStationGo-v0.0.17-windows-amd64.zip` | | Windows x86_64 | `MediaStationGo-v0.0.19-windows-amd64.zip` |
| macOS Intel | `MediaStationGo-v0.0.17-darwin-amd64.tar.gz` | | macOS Intel | `MediaStationGo-v0.0.19-darwin-amd64.tar.gz` |
| macOS Apple Silicon | `MediaStationGo-v0.0.17-darwin-arm64.tar.gz` | | macOS Apple Silicon | `MediaStationGo-v0.0.19-darwin-arm64.tar.gz` |
Linux example: Linux example:
```bash ```bash
tar -xzf MediaStationGo-v0.0.17-linux-amd64.tar.gz tar -xzf MediaStationGo-v0.0.19-linux-amd64.tar.gz
cd MediaStationGo-v0.0.17-linux-amd64 cd MediaStationGo-v0.0.19-linux-amd64
MEDIASTATION_APP_PORT=18080 ./mediastation-go MEDIASTATION_APP_PORT=18080 ./mediastation-go
``` ```
Windows example: Windows example:
```powershell ```powershell
Expand-Archive .\MediaStationGo-v0.0.17-windows-amd64.zip Expand-Archive .\MediaStationGo-v0.0.19-windows-amd64.zip
cd .\MediaStationGo-v0.0.17-windows-amd64 cd .\MediaStationGo-v0.0.19-windows-amd64
$env:MEDIASTATION_APP_PORT = "18080" $env:MEDIASTATION_APP_PORT = "18080"
.\mediastation-go.exe .\mediastation-go.exe
``` ```
+1 -1
View File
@@ -17,7 +17,7 @@
# #
# 镜像版本: # 镜像版本:
# 默认拉取 latest;如需固定版本,创建 .env 并写入: # 默认拉取 latest;如需固定版本,创建 .env 并写入:
# MEDIASTATION_IMAGE_TAG=MediaStationGo-v0.0.17 # MEDIASTATION_IMAGE_TAG=MediaStationGo-v0.0.19
# #
# 路径映射总览: # 路径映射总览:
# /data 程序数据目录。保存 SQLite 数据库、JWT secret、系统配置等,必须持久化。 # /data 程序数据目录。保存 SQLite 数据库、JWT secret、系统配置等,必须持久化。
+1 -1
View File
@@ -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/libraries", statsLibrariesHandler(svc))
authed.GET("/stats/monitor", statsMonitorHandler(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.GET("/play-profiles", listPlayProfilesHandler(svc))
authed.POST("/play-profiles", createPlayProfileHandler(svc)) authed.POST("/play-profiles", createPlayProfileHandler(svc))
authed.PUT("/play-profiles/:id", updatePlayProfileHandler(svc)) authed.PUT("/play-profiles/:id", updatePlayProfileHandler(svc))
+26 -21
View File
@@ -1,7 +1,7 @@
// Package handler — multi-persona play profile CRUD endpoints. // Package handler — multi-persona play profile CRUD endpoints.
// //
// Non-admin users see / mutate only their own profiles. Admins see // Every user sees / mutates only their own profiles. Admin user
// every profile so they can manage child accounts, etc. // management belongs in a separate admin surface, not this switcher.
package handler package handler
import ( import (
@@ -19,21 +19,10 @@ type verifyPlayProfilePINReq struct {
PIN string `json:"pin"` PIN string `json:"pin"`
} }
// listPlayProfilesHandler returns the caller's profiles, or every // listPlayProfilesHandler returns only the caller's own profiles.
// profile when the caller is an admin AND ?all=true is set.
func listPlayProfilesHandler(svc *service.Container) gin.HandlerFunc { func listPlayProfilesHandler(svc *service.Container) gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
uid, _ := c.Get(middleware.CtxUserID) 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)) rows, err := svc.PlayProfiles.ListByUser(c.Request.Context(), toString(uid))
if err != nil { if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) 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()}) c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return return
} }
// Default the user_id to the caller; admins can override.
uid, _ := c.Get(middleware.CtxUserID) uid, _ := c.Get(middleware.CtxUserID)
role, _ := c.Get(middleware.CtxUserRole) in.UserID = toString(uid)
if in.UserID == "" || role != "admin" {
in.UserID = toString(uid)
}
row, err := svc.PlayProfiles.Create(c.Request.Context(), in) 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 { if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return return
@@ -72,7 +61,16 @@ func updatePlayProfileHandler(svc *service.Container) gin.HandlerFunc {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return 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 { if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return return
@@ -83,7 +81,14 @@ func updatePlayProfileHandler(svc *service.Container) gin.HandlerFunc {
func deletePlayProfileHandler(svc *service.Container) gin.HandlerFunc { func deletePlayProfileHandler(svc *service.Container) gin.HandlerFunc {
return func(c *gin.Context) { 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()}) c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return return
} }
+8
View File
@@ -45,6 +45,14 @@ func (r *PlayProfileRepository) ListByUser(ctx context.Context, userID string) (
return rows, err 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. // Update applies a partial update to a profile row.
func (r *PlayProfileRepository) Update(ctx context.Context, id string, patch map[string]any) error { func (r *PlayProfileRepository) Update(ctx context.Context, id string, patch map[string]any) error {
return r.db.WithContext(ctx).Model(&model.PlayProfile{}). return r.db.WithContext(ctx).Model(&model.PlayProfile{}).
+4 -3
View File
@@ -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 { func (e *EmbyService) userPayload(u *model.User) map[string]any {
canDownload := u.Role == "admin"
return map[string]any{ return map[string]any{
"Id": u.ID, "Id": u.ID,
"Name": u.Username, "Name": u.Username,
@@ -153,9 +154,9 @@ func (e *EmbyService) userPayload(u *model.User) map[string]any {
"EnableVideoPlaybackTranscoding": true, "EnableVideoPlaybackTranscoding": true,
"EnablePlaybackRemuxing": true, "EnablePlaybackRemuxing": true,
"EnableLiveTvAccess": false, "EnableLiveTvAccess": false,
"EnableContentDownloading": true, "EnableContentDownloading": canDownload,
"EnableSyncTranscoding": true, "EnableSyncTranscoding": canDownload,
"EnableMediaConversion": true, "EnableMediaConversion": canDownload,
"EnableAllChannels": true, "EnableAllChannels": true,
"EnableAllFolders": true, "EnableAllFolders": true,
"EnableAllDevices": true, "EnableAllDevices": true,
+35 -1
View File
@@ -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 { func newTestEmbyService(t *testing.T) *EmbyService {
t.Helper() t.Helper()
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil { if err != nil {
t.Fatalf("open db: %v", err) 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) t.Fatalf("migrate: %v", err)
} }
repos := repository.New(db) repos := repository.New(db)
+46 -2
View File
@@ -29,10 +29,13 @@ type PlayProfileService struct {
repo *repository.Container repo *repository.Container
} }
const MaxPlayProfilesPerUser = 3
var ( var (
ErrPlayProfileNotFound = errors.New("profile not found") ErrPlayProfileNotFound = errors.New("profile not found")
ErrPlayProfileForbidden = errors.New("profile forbidden") ErrPlayProfileForbidden = errors.New("profile forbidden")
ErrPlayProfilePINInvalid = errors.New("pin invalid") ErrPlayProfilePINInvalid = errors.New("pin invalid")
ErrPlayProfileLimit = errors.New("profile limit reached")
) )
// NewPlayProfileService is the constructor. // NewPlayProfileService is the constructor.
@@ -108,6 +111,13 @@ func (s *PlayProfileService) Create(ctx context.Context, in PlayProfileInput) (*
if err := validateProfileInput(in, true); err != nil { if err := validateProfileInput(in, true); err != nil {
return nil, err 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) libsBlob, _ := json.Marshal(in.AllowedLibraryIDs)
p := &model.PlayProfile{ p := &model.PlayProfile{
UserID: in.UserID, UserID: in.UserID,
@@ -137,6 +147,21 @@ func (s *PlayProfileService) Create(ctx context.Context, in PlayProfileInput) (*
return &v, nil 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. // Update applies a patch to an existing profile.
func (s *PlayProfileService) Update(ctx context.Context, id string, in PlayProfileInput) (*ProfileView, error) { func (s *PlayProfileService) Update(ctx context.Context, id string, in PlayProfileInput) (*ProfileView, error) {
row, err := s.repo.PlayProfile.FindByID(ctx, id) 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 { if row == nil {
return nil, ErrPlayProfileNotFound 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 { if err := validateProfileInput(in, false); err != nil {
return nil, err return nil, err
} }
@@ -175,10 +204,10 @@ func (s *PlayProfileService) Update(ctx context.Context, id string, in PlayProfi
return nil, err 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 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 { if err != nil || row == nil {
return nil, err return nil, err
} }
@@ -191,6 +220,21 @@ func (s *PlayProfileService) Delete(ctx context.Context, id string) error {
return s.repo.PlayProfile.Delete(ctx, id) 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. // 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) { func (s *PlayProfileService) VerifyPIN(ctx context.Context, id, userID, pin string) (*ProfileView, error) {
row, err := s.repo.PlayProfile.FindByID(ctx, id) row, err := s.repo.PlayProfile.FindByID(ctx, id)
+70 -10
View File
@@ -11,7 +11,8 @@ import (
"gorm.io/gorm" "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{}) db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@@ -19,7 +20,11 @@ func TestPlayProfileVerifyPIN(t *testing.T) {
if err := db.AutoMigrate(&model.PlayProfile{}); err != nil { if err := db.AutoMigrate(&model.PlayProfile{}); err != nil {
t.Fatal(err) 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{ profile, err := service.Create(t.Context(), PlayProfileInput{
UserID: "user-1", UserID: "user-1",
Name: "成人模式", Name: "成人模式",
@@ -43,14 +48,7 @@ func TestPlayProfileVerifyPIN(t *testing.T) {
} }
func TestPlayProfileCreateRequiresPINWhenEnabled(t *testing.T) { func TestPlayProfileCreateRequiresPINWhenEnabled(t *testing.T) {
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{}) service := newPlayProfileTestService(t)
if err != nil {
t.Fatal(err)
}
if err := db.AutoMigrate(&model.PlayProfile{}); err != nil {
t.Fatal(err)
}
service := NewPlayProfileService(zap.NewNop(), repository.New(db))
if _, err := service.Create(t.Context(), PlayProfileInput{ if _, err := service.Create(t.Context(), PlayProfileInput{
UserID: "user-1", UserID: "user-1",
Name: "锁定模式", Name: "锁定模式",
@@ -59,3 +57,65 @@ func TestPlayProfileCreateRequiresPINWhenEnabled(t *testing.T) {
t.Fatal("expected PIN-required profile create to fail without PIN") 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)
}
}
+2 -5
View File
@@ -23,12 +23,9 @@ export interface PlayProfilePINVerifyResponse {
expires_at: string expires_at: string
} }
// playProfilesAPI wraps /play-profiles. The admin variant adds ?all=true. // playProfilesAPI wraps caller-scoped /play-profiles.
export const playProfilesAPI = { export const playProfilesAPI = {
list: (all = false) => list: () => api.get<PlayProfile[]>('/play-profiles').then((r) => r.data),
api
.get<PlayProfile[]>('/play-profiles', { params: all ? { all: 'true' } : {} })
.then((r) => r.data),
create: (input: PlayProfileInput) => create: (input: PlayProfileInput) =>
api.post<PlayProfile>('/play-profiles', input).then((r) => r.data), api.post<PlayProfile>('/play-profiles', input).then((r) => r.data),
+1 -1
View File
@@ -67,7 +67,7 @@ export function Layout() {
return return
} }
playProfilesAPI playProfilesAPI
.list(false) .list()
.then((rows) => { .then((rows) => {
setProfiles(rows) setProfiles(rows)
const active = rows.find((p) => p.id === activeProfileId) const active = rows.find((p) => p.id === activeProfileId)
+18 -18
View File
@@ -10,14 +10,15 @@ import { confirmAction } from '../components/ConfirmDialog'
import { requestPIN } from '../components/PinDialog' import { requestPIN } from '../components/PinDialog'
import type { Library, PlayProfile } from '../types' import type { Library, PlayProfile } from '../types'
const MAX_PLAY_PROFILES = 3
// ProfileManagementPage replicates the Vue ProfileManagementView. It // 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. // different content-rating gates, library access, and player defaults.
// //
// All persistence is real: data is written to /api/play-profiles which // All persistence is real: data is written to /api/play-profiles which
// is backed by the Go PlayProfileService. // is backed by the Go PlayProfileService.
export function ProfileManagementPage() { export function ProfileManagementPage() {
const isAdmin = useAuthStore((s) => s.user?.role === 'admin')
const userID = useAuthStore((s) => s.user?.id ?? '') const userID = useAuthStore((s) => s.user?.id ?? '')
const activeProfileId = usePlayProfileStore((s) => s.activeProfileId) const activeProfileId = usePlayProfileStore((s) => s.activeProfileId)
const setActiveProfile = usePlayProfileStore((s) => s.setActiveProfile) const setActiveProfile = usePlayProfileStore((s) => s.setActiveProfile)
@@ -32,7 +33,7 @@ export function ProfileManagementPage() {
setLoading(true) setLoading(true)
try { try {
const [p, l] = await Promise.all([ const [p, l] = await Promise.all([
playProfilesAPI.list(isAdmin), playProfilesAPI.list(),
libraryAPI.list().catch(() => [] as Library[]), libraryAPI.list().catch(() => [] as Library[]),
]) ])
setProfiles(p) setProfiles(p)
@@ -44,7 +45,7 @@ export function ProfileManagementPage() {
useEffect(() => { useEffect(() => {
refresh().catch(() => undefined) refresh().catch(() => undefined)
}, [isAdmin]) }, [])
const onDelete = async (p: PlayProfile) => { const onDelete = async (p: PlayProfile) => {
if (!(await confirmAction({ title: '删除播放档案', message: `确定删除 Profile「${p.name}」?`, confirmText: '删除' }))) return if (!(await confirmAction({ title: '删除播放档案', message: `确定删除 Profile「${p.name}」?`, confirmText: '删除' }))) return
@@ -60,6 +61,10 @@ export function ProfileManagementPage() {
} }
const openCreate = () => { const openCreate = () => {
if (profiles.length >= MAX_PLAY_PROFILES) {
toast.error(`每个用户最多只能创建 ${MAX_PLAY_PROFILES} 个观影 Profile`)
return
}
setEditing(null) setEditing(null)
setShowForm(true) setShowForm(true)
} }
@@ -105,10 +110,18 @@ export function ProfileManagementPage() {
</p> </p>
</div> </div>
</div> </div>
<button onClick={openCreate} className="neon-button"> <button
onClick={openCreate}
disabled={profiles.length >= MAX_PLAY_PROFILES}
className="neon-button disabled:cursor-not-allowed disabled:opacity-50"
title={`每个用户最多 ${MAX_PLAY_PROFILES} 个 Profile`}
>
<Plus size={16} /> 创建 Profile <Plus size={16} /> 创建 Profile
</button> </button>
</div> </div>
<div className="rounded-2xl border border-primary-400/15 bg-primary-400/5 px-4 py-3 text-sm text-ink-100">
当前账号已创建 {profiles.length}/{MAX_PLAY_PROFILES} 个 Profile。Profile 仅当前用户可见,不会与其他用户共享。
</div>
{loading && ( {loading && (
<div className="flex justify-center py-12 text-ink-50"> <div className="flex justify-center py-12 text-ink-50">
@@ -145,7 +158,6 @@ export function ProfileManagementPage() {
editing={editing} editing={editing}
libraries={libraries} libraries={libraries}
defaultUserID={userID} defaultUserID={userID}
isAdmin={isAdmin}
onClose={() => setShowForm(false)} onClose={() => setShowForm(false)}
onSaved={async () => { onSaved={async () => {
setShowForm(false) setShowForm(false)
@@ -216,7 +228,6 @@ function ProfileCard({
<div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-ink-50"> <div className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-ink-50">
{profile.content_rating_limit && <span>分级: {profile.content_rating_limit}</span>} {profile.content_rating_limit && <span>分级: {profile.content_rating_limit}</span>}
<span>媒体库: {libNames}</span> <span>媒体库: {libNames}</span>
<span>用户: {profile.user_id.slice(0, 8)}…</span>
</div> </div>
<div className="text-xs text-sand-500"> <div className="text-xs text-sand-500">
观看时长 {Math.round(profile.total_watch_time / 3600)} 小时 观看时长 {Math.round(profile.total_watch_time / 3600)} 小时
@@ -252,14 +263,12 @@ function ProfileFormModal({
editing, editing,
libraries, libraries,
defaultUserID, defaultUserID,
isAdmin,
onClose, onClose,
onSaved, onSaved,
}: { }: {
editing: PlayProfile | null editing: PlayProfile | null
libraries: Library[] libraries: Library[]
defaultUserID: string defaultUserID: string
isAdmin: boolean
onClose: () => void onClose: () => void
onSaved: () => void | Promise<void> onSaved: () => void | Promise<void>
}) { }) {
@@ -315,15 +324,6 @@ function ProfileFormModal({
{editing ? '编辑 Profile' : '创建 Profile'} {editing ? '编辑 Profile' : '创建 Profile'}
</h2> </h2>
<form onSubmit={onSubmit} className="space-y-4"> <form onSubmit={onSubmit} className="space-y-4">
{!editing && isAdmin && (
<Field label="用户 ID">
<input
className="input-base"
value={form.user_id ?? ''}
onChange={(e) => update({ user_id: e.target.value })}
/>
</Field>
)}
<Field label="名称"> <Field label="名称">
<input <input
required required