You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
63 lines
2.1 KiB
63 lines
2.1 KiB
package model |
|
|
|
import ( |
|
"gofaster/internal/shared/model" |
|
"time" |
|
) |
|
|
|
type User struct { |
|
model.BaseModel |
|
Username string `gorm:"uniqueIndex;size:50" json:"username"` |
|
Password string `gorm:"size:100" json:"-"` |
|
Email string `gorm:"size:100" json:"email"` |
|
Phone string `gorm:"size:20" json:"phone"` |
|
Status int `gorm:"default:1" json:"status"` // 1-正常 2-禁用 3-锁定 |
|
PasswordErrorCount int `gorm:"default:0" json:"-"` // 密码错误次数 |
|
LockedAt *time.Time `gorm:"index" json:"-"` // 锁定时间 |
|
LastLoginAt *time.Time `gorm:"index" json:"last_login_at"` // 最后登录时间 |
|
LastLoginIP string `gorm:"size:45" json:"last_login_ip"` // 最后登录IP |
|
PasswordChangedAt *time.Time `gorm:"index" json:"password_changed_at"` // 密码最后修改时间 |
|
ForceChangePassword bool `gorm:"default:false" json:"force_change_password"` // 是否强制修改密码 |
|
Roles []Role `gorm:"many2many:user_roles;" json:"roles"` |
|
} |
|
|
|
// IsLocked 检查用户是否被锁定 |
|
func (u *User) IsLocked() bool { |
|
// 如果状态是锁定(3),直接返回true |
|
if u.Status == 3 { |
|
return true |
|
} |
|
|
|
// 如果没有锁定时间,说明没有被锁定 |
|
if u.LockedAt == nil { |
|
return false |
|
} |
|
|
|
// 检查是否超过30分钟锁定时间 |
|
unlockTime := u.LockedAt.Add(30 * time.Minute) |
|
return time.Now().Before(unlockTime) |
|
} |
|
|
|
// CanLogin 检查用户是否可以登录 |
|
func (u *User) CanLogin() bool { |
|
return u.Status == 1 && !u.IsLocked() |
|
} |
|
|
|
// IncrementPasswordError 增加密码错误次数 |
|
func (u *User) IncrementPasswordError() { |
|
u.PasswordErrorCount++ |
|
if u.PasswordErrorCount >= 5 { |
|
u.Status = 3 // 设置为锁定状态 |
|
now := time.Now() |
|
u.LockedAt = &now |
|
} |
|
} |
|
|
|
// ResetPasswordError 重置密码错误次数 |
|
func (u *User) ResetPasswordError() { |
|
u.PasswordErrorCount = 0 |
|
if u.Status == 3 { |
|
u.Status = 1 // 恢复正常状态 |
|
u.LockedAt = nil |
|
} |
|
}
|
|
|