95 lines
2.5 KiB
Go
95 lines
2.5 KiB
Go
package model
|
|
|
|
import (
|
|
"time"
|
|
|
|
"github.com/jinzhu/gorm"
|
|
"golang.org/x/crypto/bcrypt"
|
|
)
|
|
|
|
// User 用户模型
|
|
type User struct {
|
|
ID uint `json:"id" gorm:"primary_key;auto_increment"`
|
|
Name string `json:"name" gorm:"type:varchar(100);not null;unique_index"`
|
|
Password string `json:"-" gorm:"type:varchar(255);not null"`
|
|
Status int `json:"status" gorm:"type:tinyint;default:1;comment:'用户状态 1:正常 0:禁用'"`
|
|
CreatedAt time.Time `json:"created_at" gorm:"type:datetime;not null"`
|
|
UpdatedAt time.Time `json:"updated_at" gorm:"type:datetime;not null"`
|
|
}
|
|
|
|
// TableName 指定表名
|
|
func (User) TableName() string {
|
|
return "user"
|
|
}
|
|
|
|
// BeforeCreate 创建前钩子
|
|
func (u *User) BeforeCreate(scope *gorm.Scope) error {
|
|
if u.Password != "" {
|
|
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
u.Password = string(hashedPassword)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// CheckPassword 验证密码
|
|
func (u *User) CheckPassword(password string) bool {
|
|
err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
|
|
return err == nil
|
|
}
|
|
|
|
// SetPassword 设置密码
|
|
func (u *User) SetPassword(password string) error {
|
|
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
u.Password = string(hashedPassword)
|
|
return nil
|
|
}
|
|
|
|
// UserRegisterRequest 用户注册请求
|
|
type UserRegisterRequest struct {
|
|
Name string `json:"name" binding:"required,min=3,max=50" example:"testuser"`
|
|
Password string `json:"password" binding:"required,min=6,max=100" example:"password123"`
|
|
}
|
|
|
|
// UserLoginRequest 用户登录请求
|
|
type UserLoginRequest struct {
|
|
Name string `json:"name" binding:"required" example:"testuser"`
|
|
Password string `json:"password" binding:"required" example:"password123"`
|
|
}
|
|
|
|
// UserResponse 用户响应
|
|
type UserResponse struct {
|
|
ID uint `json:"id"`
|
|
Name string `json:"name"`
|
|
Status int `json:"status"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
}
|
|
|
|
// ToResponse 转换为响应格式
|
|
func (u *User) ToResponse() *UserResponse {
|
|
return &UserResponse{
|
|
ID: u.ID,
|
|
Name: u.Name,
|
|
Status: u.Status,
|
|
CreatedAt: u.CreatedAt,
|
|
UpdatedAt: u.UpdatedAt,
|
|
}
|
|
}
|
|
|
|
// LoginResponse 登录响应
|
|
type LoginResponse struct {
|
|
User *UserResponse `json:"user"`
|
|
Token string `json:"token"`
|
|
}
|
|
|
|
// IsActive 检查用户是否激活
|
|
func (u *User) IsActive() bool {
|
|
return u.Status == 1
|
|
}
|