mirror of
https://github.com/Sagit-chu/flvx.git
synced 2026-11-17 01:44:23 +08:00
feat: persist administrator user and speed-limit order (#575)
This commit is contained in:
@@ -10,6 +10,7 @@ import "database/sql"
|
||||
// User maps to the "user" table. PostgreSQL treats "user" as a reserved
|
||||
// word, so TableName() is required for correct quoting.
|
||||
type User struct {
|
||||
DisplayOrder int64 `gorm:"not null;default:0"`
|
||||
ID int64 `gorm:"primaryKey;autoIncrement"`
|
||||
User string `gorm:"column:user;type:varchar(100);not null"`
|
||||
Pwd string `gorm:"type:varchar(100);not null"`
|
||||
@@ -151,14 +152,15 @@ type NftCounterState struct {
|
||||
func (NftCounterState) TableName() string { return "nft_counter_state" }
|
||||
|
||||
type SpeedLimit struct {
|
||||
ID int64 `gorm:"primaryKey;autoIncrement"`
|
||||
Name string `gorm:"type:varchar(100);not null"`
|
||||
Speed int `gorm:"not null"`
|
||||
TunnelID sql.NullInt64 `gorm:"column:tunnel_id"`
|
||||
TunnelName sql.NullString `gorm:"column:tunnel_name;type:varchar(100)"`
|
||||
CreatedTime int64 `gorm:"column:created_time;not null"`
|
||||
UpdatedTime sql.NullInt64 `gorm:"column:updated_time"`
|
||||
Status int `gorm:"not null"`
|
||||
DisplayOrder int64 `gorm:"not null;default:0"`
|
||||
ID int64 `gorm:"primaryKey;autoIncrement"`
|
||||
Name string `gorm:"type:varchar(100);not null"`
|
||||
Speed int `gorm:"not null"`
|
||||
TunnelID sql.NullInt64 `gorm:"column:tunnel_id"`
|
||||
TunnelName sql.NullString `gorm:"column:tunnel_name;type:varchar(100)"`
|
||||
CreatedTime int64 `gorm:"column:created_time;not null"`
|
||||
UpdatedTime sql.NullInt64 `gorm:"column:updated_time"`
|
||||
Status int `gorm:"not null"`
|
||||
}
|
||||
|
||||
func (SpeedLimit) TableName() string { return "speed_limit" }
|
||||
@@ -417,6 +419,7 @@ type BackupData struct {
|
||||
}
|
||||
|
||||
type UserBackup struct {
|
||||
DisplayOrder *int64 `json:"displayOrder,omitempty"`
|
||||
ID int64 `json:"id"`
|
||||
User string `json:"user"`
|
||||
Pwd string `json:"pwd"`
|
||||
@@ -540,14 +543,15 @@ type UserTunnelBackup struct {
|
||||
}
|
||||
|
||||
type SpeedLimitBackup struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Speed int64 `json:"speed"`
|
||||
TunnelID *int64 `json:"tunnelId,omitempty"`
|
||||
TunnelName string `json:"tunnelName,omitempty"`
|
||||
CreatedTime int64 `json:"createdTime"`
|
||||
UpdatedTime int64 `json:"updatedTime,omitempty"`
|
||||
Status int `json:"status"`
|
||||
DisplayOrder *int64 `json:"displayOrder,omitempty"`
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Speed int64 `json:"speed"`
|
||||
TunnelID *int64 `json:"tunnelId,omitempty"`
|
||||
TunnelName string `json:"tunnelName,omitempty"`
|
||||
CreatedTime int64 `json:"createdTime"`
|
||||
UpdatedTime int64 `json:"updatedTime,omitempty"`
|
||||
Status int `json:"status"`
|
||||
}
|
||||
|
||||
type TunnelGroupBackup struct {
|
||||
|
||||
@@ -914,7 +914,7 @@ func (r *Repository) ListUsers() ([]map[string]interface{}, error) {
|
||||
return nil, errors.New("repository not initialized")
|
||||
}
|
||||
var users []model.User
|
||||
if err := r.db.Where("role_id != ?", 0).Order("id DESC").Find(&users).Error; err != nil {
|
||||
if err := r.db.Where("role_id != ?", 0).Order("display_order ASC, id DESC").Find(&users).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
userIDs := make([]int64, 0, len(users))
|
||||
@@ -954,7 +954,7 @@ func (r *Repository) ListSpeedLimits() ([]map[string]interface{}, error) {
|
||||
return nil, errors.New("repository not initialized")
|
||||
}
|
||||
var limits []model.SpeedLimit
|
||||
if err := r.db.Order("id DESC").Find(&limits).Error; err != nil {
|
||||
if err := r.db.Order("display_order ASC, id DESC").Find(&limits).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items := make([]map[string]interface{}, 0, len(limits))
|
||||
@@ -2092,7 +2092,8 @@ func (r *Repository) exportUsers() ([]model.UserBackup, error) {
|
||||
out := make([]model.UserBackup, 0, len(users))
|
||||
for _, u := range users {
|
||||
b := model.UserBackup{
|
||||
ID: u.ID, User: u.User, Pwd: u.Pwd, RoleID: u.RoleID,
|
||||
DisplayOrder: &u.DisplayOrder,
|
||||
ID: u.ID, User: u.User, Pwd: u.Pwd, RoleID: u.RoleID,
|
||||
ExpTime: u.ExpTime, Flow: u.Flow, FlowMiB: u.FlowMiB, InFlow: u.InFlow, OutFlow: u.OutFlow,
|
||||
FlowResetTime: u.FlowResetTime, Num: u.Num,
|
||||
CreatedTime: u.CreatedTime, Status: u.Status,
|
||||
@@ -2289,7 +2290,8 @@ func (r *Repository) exportSpeedLimits() ([]model.SpeedLimitBackup, error) {
|
||||
out := make([]model.SpeedLimitBackup, 0, len(sls))
|
||||
for _, sl := range sls {
|
||||
b := model.SpeedLimitBackup{
|
||||
ID: sl.ID, Name: sl.Name, Speed: int64(sl.Speed),
|
||||
DisplayOrder: &sl.DisplayOrder,
|
||||
ID: sl.ID, Name: sl.Name, Speed: int64(sl.Speed),
|
||||
CreatedTime: sl.CreatedTime, Status: sl.Status,
|
||||
}
|
||||
if sl.UpdatedTime.Valid {
|
||||
@@ -2373,6 +2375,17 @@ func (r *Repository) Import(backup *model.BackupData, types []string) (*model.Im
|
||||
}
|
||||
|
||||
err := r.db.Transaction(func(tx *gorm.DB) error {
|
||||
// Lock in a stable order before touching either membership.
|
||||
if typeSet["users"] {
|
||||
if err := lockDisplayOrder(tx, "user"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if typeSet["speedLimits"] {
|
||||
if err := lockDisplayOrder(tx, "speed_limit"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
now := unixMilliNow()
|
||||
|
||||
if typeSet["users"] && len(backup.Users) > 0 {
|
||||
@@ -2477,12 +2490,17 @@ func importUsers(tx *gorm.DB, users []model.UserBackup, now int64) (int, error)
|
||||
Status: status,
|
||||
PasswordChangedAt: now,
|
||||
}
|
||||
// An omitted old-backup rank preserves existing order on conflict.
|
||||
// New legacy records use rank zero and ID descending, matching upgrades.
|
||||
columns := []string{"user", "pwd", "role_id", "exp_time", "flow", "flow_mib", "in_flow", "out_flow",
|
||||
"flow_reset_time", "num", "updated_time", "status", "password_changed_at"}
|
||||
if u.DisplayOrder != nil {
|
||||
item.DisplayOrder = *u.DisplayOrder
|
||||
columns = append(columns, "display_order")
|
||||
}
|
||||
err = tx.Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "id"}},
|
||||
DoUpdates: clause.AssignmentColumns([]string{
|
||||
"user", "pwd", "role_id", "exp_time", "flow", "flow_mib", "in_flow", "out_flow",
|
||||
"flow_reset_time", "num", "updated_time", "status", "password_changed_at",
|
||||
}),
|
||||
Columns: []clause.Column{{Name: "id"}},
|
||||
DoUpdates: clause.AssignmentColumns(columns),
|
||||
}).Create(&item).Error
|
||||
if err != nil {
|
||||
return count, err
|
||||
@@ -2765,11 +2783,16 @@ func importSpeedLimits(tx *gorm.DB, speedLimits []model.SpeedLimitBackup, now in
|
||||
UpdatedTime: sql.NullInt64{Int64: now, Valid: true},
|
||||
Status: sl.Status,
|
||||
}
|
||||
// An omitted old-backup rank preserves existing order on conflict.
|
||||
// New legacy records use rank zero and ID descending, matching upgrades.
|
||||
columns := []string{"name", "speed", "tunnel_id", "tunnel_name", "updated_time", "status"}
|
||||
if sl.DisplayOrder != nil {
|
||||
item.DisplayOrder = *sl.DisplayOrder
|
||||
columns = append(columns, "display_order")
|
||||
}
|
||||
err := tx.Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "id"}},
|
||||
DoUpdates: clause.AssignmentColumns([]string{
|
||||
"name", "speed", "tunnel_id", "tunnel_name", "updated_time", "status",
|
||||
}),
|
||||
Columns: []clause.Column{{Name: "id"}},
|
||||
DoUpdates: clause.AssignmentColumns(columns),
|
||||
}).Create(&item).Error
|
||||
if err != nil {
|
||||
return count, err
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
package repo
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"gorm.io/gorm"
|
||||
"slices"
|
||||
)
|
||||
|
||||
var ErrDisplayOrderConflict = errors.New("列表已变更,请刷新后重试")
|
||||
var ErrInvalidDisplayOrder = errors.New("排序必须包含全部条目且不能重复")
|
||||
|
||||
// Lock the entire membership, including an empty list and concurrent INSERTs.
|
||||
// PostgreSQL row locks alone cannot protect the missing-row/phantom case.
|
||||
// SQLite's first write acquires its writer reservation before reading the list.
|
||||
func lockDisplayOrder(tx *gorm.DB, table string) error {
|
||||
if tx.Dialector.Name() == "postgres" {
|
||||
return tx.Exec("LOCK TABLE \"" + table + "\" IN SHARE ROW EXCLUSIVE MODE").Error
|
||||
}
|
||||
return tx.Table(table).Where("1 = 0").UpdateColumn("display_order", gorm.Expr("display_order")).Error
|
||||
}
|
||||
|
||||
func (r *Repository) UpdateUserDisplayOrder(ids, expected []int64) error {
|
||||
return r.updateDisplayOrder("user", ids, expected)
|
||||
}
|
||||
func (r *Repository) UpdateSpeedLimitDisplayOrder(ids, expected []int64) error {
|
||||
return r.updateDisplayOrder("speed_limit", ids, expected)
|
||||
}
|
||||
func (r *Repository) updateDisplayOrder(table string, ids, expected []int64) error {
|
||||
if ids == nil || expected == nil {
|
||||
return ErrInvalidDisplayOrder
|
||||
}
|
||||
seen := map[int64]bool{}
|
||||
for _, id := range ids {
|
||||
if id <= 0 || seen[id] {
|
||||
return ErrInvalidDisplayOrder
|
||||
}
|
||||
seen[id] = true
|
||||
}
|
||||
seenExpected := map[int64]bool{}
|
||||
for _, id := range expected {
|
||||
if id <= 0 || seenExpected[id] {
|
||||
return ErrInvalidDisplayOrder
|
||||
}
|
||||
seenExpected[id] = true
|
||||
}
|
||||
if len(ids) != len(expected) {
|
||||
return ErrInvalidDisplayOrder
|
||||
}
|
||||
for id := range seen {
|
||||
if !seenExpected[id] {
|
||||
return ErrInvalidDisplayOrder
|
||||
}
|
||||
}
|
||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := lockDisplayOrder(tx, table); err != nil {
|
||||
return err
|
||||
}
|
||||
q := tx.Table(table)
|
||||
if table == "user" {
|
||||
var admins int64
|
||||
if err := tx.Table(table).Where("role_id = ? AND id IN ?", 0, ids).Count(&admins).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if admins != 0 {
|
||||
return ErrInvalidDisplayOrder
|
||||
}
|
||||
q = q.Where("role_id != ?", 0)
|
||||
}
|
||||
var current []int64
|
||||
if err := q.Order("display_order ASC, id DESC").Pluck("id", ¤t).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if !slices.Equal(current, expected) {
|
||||
return ErrDisplayOrderConflict
|
||||
}
|
||||
for i, id := range ids {
|
||||
result := tx.Table(table).Where("id = ?", id).UpdateColumn("display_order", int64(i))
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected != 1 {
|
||||
return ErrDisplayOrderConflict
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// New items precede all saved ranks. Zero is only the legacy migration default.
|
||||
func createFirst(tx *gorm.DB, table string, item interface{}, rank *int64) error {
|
||||
return tx.Transaction(func(tx *gorm.DB) error {
|
||||
if err := lockDisplayOrder(tx, table); err != nil {
|
||||
return err
|
||||
}
|
||||
q := tx.Table(table)
|
||||
if table == "user" {
|
||||
q = q.Where("role_id != ?", 0)
|
||||
}
|
||||
var first int64
|
||||
if err := q.Select("COALESCE(MIN(display_order), 0)").Scan(&first).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if first == -1<<63 {
|
||||
return errors.New("display order exhausted")
|
||||
}
|
||||
*rank = first - 1
|
||||
return tx.Create(item).Error
|
||||
})
|
||||
}
|
||||
@@ -65,7 +65,7 @@ func (r *Repository) CreateUser(username, pwdHash string, roleID int, expTime, f
|
||||
Status: status,
|
||||
PasswordChangedAt: now,
|
||||
}
|
||||
if err := r.db.Create(&user).Error; err != nil {
|
||||
if err := createFirst(r.db, "user", &user, &user.DisplayOrder); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return user.ID, nil
|
||||
@@ -940,7 +940,7 @@ func (r *Repository) CreateSpeedLimit(name string, speed int, now int64, status
|
||||
UpdatedTime: sql.NullInt64{Int64: now, Valid: true},
|
||||
Status: status,
|
||||
}
|
||||
if err := r.db.Create(&sl).Error; err != nil {
|
||||
if err := createFirst(r.db, "speed_limit", &sl, &sl.DisplayOrder); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return sl.ID, nil
|
||||
|
||||
Reference in New Issue
Block a user