wireguard-dashboard/repository/user.go
2024-03-14 15:33:54 +08:00

113 lines
2.7 KiB
Go

package repository
import (
"gorm.io/gorm"
"wireguard-dashboard/client"
"wireguard-dashboard/http/param"
"wireguard-dashboard/model/entity"
"wireguard-dashboard/model/vo"
"wireguard-dashboard/utils"
)
type user struct {
*gorm.DB
}
func User() user {
return user{
client.DB,
}
}
// List
// @description: 用户列表
// @receiver r
// @param p
// @return data
// @return total
// @return err
func (r user) List(p param.UserList) (data []vo.User, total int64, err error) {
err = r.Model(&entity.User{}).Scopes(utils.Page(p.Current, p.Size)).
Select("id", "created_at", "updated_at", "avatar", "name", "account", "is_admin", "status").Order("created_at DESC").
Find(&data).Offset(-1).Limit(-1).Count(&total).Error
return
}
// GetUserById
// @description: 根据id获取用户信息
// @receiver r
// @param id
// @return *entity.User
// @return error
func (r user) GetUserById(id string) (data *entity.User, err error) {
err = r.Where("id = ?", id).First(&data).Error
return
}
// GetUserByAccount
// @description: 通过账户号获取用户信息
// @receiver r
// @param account
// @return data
// @return err
func (r user) GetUserByAccount(account string) (data *entity.User, err error) {
err = r.Where("account = ?", account).First(&data).Error
return
}
// Save
// @description: 创建/更新用户
// @receiver r
// @param ent
// @return err
func (r user) Save(ent *entity.User) (err error) {
// 更新
if ent.Id != "" {
updates := map[string]any{
"name": ent.Name,
"avatar": ent.Avatar,
"email": ent.Email,
"is_admin": ent.IsAdmin,
"status": ent.Status,
}
return r.Model(&entity.User{}).Where("id = ?", ent.Id).Updates(&updates).Error
}
defaultPassword := utils.Password().GenerateHashPassword("admin123")
if ent.Password == "" { // 没有密码给一个默认密码
ent.Password = defaultPassword
} else {
ent.Password = utils.Password().GenerateHashPassword(ent.Password)
}
// 没有头像就生成一个头像
if ent.Avatar == "" {
ent.Avatar, _ = utils.Avatar().GenerateAvatar()
}
// 创建
return r.Create(&ent).Error
}
// ChangePassword
// @description: 变更密码
// @receiver r
// @param p
// @param userId
// @return err
func (r user) ChangePassword(p param.ChangePassword, userId string) (err error) {
password := utils.Password().GenerateHashPassword(p.NewPassword)
return r.Model(&entity.User{}).Where("id = ?", userId).Update("password", password).Error
}
// ChangeUserState
// @description: 变更用户状态
// @receiver r
// @param p
// @return err
func (r user) ChangeUserState(p param.ChangeUserState) (err error) {
return r.Model(&entity.User{}).Where("id = ?", p.ID).Update("status", p.Status).Error
}