Add user CRUD actions, add permission level for user

Signed-off-by: Asai Neko <sugar@sne.moe>
This commit is contained in:
2025-12-25 16:40:26 +08:00
parent 5b571f7a84
commit 9135edbd60
3 changed files with 97 additions and 24 deletions

View File

@@ -4,6 +4,8 @@ import (
"time"
"github.com/google/uuid"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type User struct {
@@ -16,6 +18,7 @@ type User struct {
Subtitle string `json:"subtitle"`
Avatar string `json:"avatar"`
Checkin time.Time `json:"checkin" gorm:"index"`
PermissionLevel uint `json:"permission_level" gorm:"default:0;not null"`
}
func (self *User) GetByEmail(email string) error {
@@ -32,11 +35,80 @@ func (self *User) GetByUserId(userId uuid.UUID) error {
return nil
}
func (self *User) SetCheckinState(userId uuid.UUID, time time.Time) error {
if err := Database.Where("user_id = ?", userId).First(&self).Error; err != nil {
func (self *User) UpdateCheckin(userId uuid.UUID, time time.Time) error {
return Database.Transaction(func(tx *gorm.DB) error {
if err := tx.
Clauses(clause.Locking{Strength: "UPDATE"}).
Where("user_id = ?", userId).
First(self).Error; err != nil {
return err // if error then rollback
}
self.Checkin = time
if err := tx.Save(self).Error; err != nil {
return err // rollback
}
return nil // commit
})
}
func (self *User) Create() error {
return Database.Transaction(func(tx *gorm.DB) error {
if self.UUID == uuid.Nil {
self.UUID = uuid.New()
}
if self.UserId == uuid.Nil {
self.UserId = uuid.New()
}
if err := tx.Create(self).Error; err != nil {
return err
}
self.Checkin = time
Database.Save(&self)
return nil
})
}
type UserUpdateInput struct {
Email *string
Nickname *string
Subtitle *string
Avatar *string
Type *string
}
func (self *User) UpdateByUserID(userID uuid.UUID, in *UserUpdateInput) error {
return Database.Transaction(func(tx *gorm.DB) error {
if err := tx.
Where("user_id = ?", userID).
First(self).Error; err != nil {
return err
}
updates := map[string]any{}
if in.Email != nil {
updates["email"] = *in.Email
}
if in.Nickname != nil {
updates["nickname"] = *in.Nickname
}
if in.Subtitle != nil {
updates["subtitle"] = *in.Subtitle
}
if in.Avatar != nil {
updates["avatar"] = *in.Avatar
}
if in.Type != nil {
updates["type"] = *in.Type
}
if len(updates) == 0 {
return nil
}
return tx.Model(self).Updates(updates).Error
})
}

View File

@@ -18,7 +18,7 @@ func Checkin(ctx *gin.Context) {
})
return
}
data.SetCheckinState(userId.(uuid.UUID), time.Now())
data.UpdateCheckin(userId.(uuid.UUID), time.Now())
ctx.JSON(http.StatusOK, gin.H{
"status": "success",
})

View File

@@ -36,5 +36,6 @@ func UserInfo(c *gin.Context) {
"subtitle": data.Subtitle,
"avatar": data.Avatar,
"checkin": checkinTime,
"permission_level": data.PermissionLevel,
})
}