feat: 管理后台认证加固——改密即失效旧令牌/账号锁定/登录审计/release随机初始密码

This commit is contained in:
Logan.Li committed 2026-09-14 21:08:39 +08:00
1 parent b76111dfc3
commit 2f0cb71fc2
7 files changed
+127 -11

No files matched your search

@@ -3,6 +3,7 @@ package auth
import (
"backend/config"
authservice "backend/internal/service/auth"
"backend/utils"
"net/http"
"github.com/gin-gonic/gin"
@@ -12,16 +13,18 @@ import (
// AuthController 认证控制器 // Logan.Li
type AuthController struct {
authService *authservice.AuthService
db *gorm.DB
}
// NewAuthController 创建控制器实例 // Logan.Li
func NewAuthController(db *gorm.DB, cfg *config.Config) *AuthController {
return &AuthController{
authService: authservice.NewAuthService(db, cfg),
db: db,
}
}
// Login 管理员登录 // Logan.Li
// Login 管理员登录(成功/失败均记审计) // Logan.Li
func (ctrl *AuthController) Login(c *gin.Context) {
var req struct {
Username string `json:"username" binding:"required"`
@@ -34,10 +37,12 @@ func (ctrl *AuthController) Login(c *gin.Context) {
result, err := ctrl.authService.Login(req)
if err != nil {
utils.LogAuthAction(ctrl.db, c, "login", req.Username, err.Error(), "failure")
c.JSON(http.StatusOK, gin.H{"code": 1, "message": err.Error()})
return
}
utils.LogAuthAction(ctrl.db, c, "login", req.Username, "登录成功", "success")
c.JSON(http.StatusOK, gin.H{"code": 0, "message": "登录成功", "data": result})
}
+8 -3
View File
@@ -16,9 +16,14 @@ type User struct {
Role string `json:"role" gorm:"size:20;default:'admin'"` // 固定 admin,预留扩展
IsActive bool `json:"is_active" gorm:"default:true"`
LastLogin *time.Time `json:"last_login,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"deleted_at,omitempty" gorm:"index"`
// 会话失效基线:签发时间早于该值的 JWT 一律拒绝(改密码时刷新为当前时间) // Logan.Li
TokenValidAfter time.Time `json:"-" gorm:"default:CURRENT_TIMESTAMP"`
// 账号级登录防护:连续失败计数与锁定截止时间 // Logan.Li
FailedLoginAttempts int `json:"-" gorm:"default:0"`
LockedUntil *time.Time `json:"-" gorm:"default:null"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"deleted_at,omitempty" gorm:"index"`
}
// TableName 指定表名 // Logan.Li
+40 -2
View File
@@ -6,6 +6,7 @@ import (
"backend/internal/model"
"backend/utils"
"errors"
"fmt"
"time"
"gorm.io/gorm"
@@ -17,12 +18,19 @@ type AuthService struct {
cfg *config.Config
}
// 登录防护参数:连续失败 5 次锁定 15 分钟(账号级,与 IP 限流互补) // Logan.Li
const (
maxLoginAttempts = 5
loginLockDuration = 15 * time.Minute
)
// NewAuthService 创建 service 实例 // Logan.Li
func NewAuthService(db *gorm.DB, cfg *config.Config) *AuthService {
return &AuthService{db: db, cfg: cfg}
}
// Login 校验账号密码并签发 JWT // Logan.Li
// Login 校验账号密码并签发 JWT。
// 含账号级防护:连续失败达上限后锁定一段时间;成功登录清零计数。 // Logan.Li
func (s *AuthService) Login(req dto.LoginRequest) (*dto.LoginResponse, error) {
var user model.User
if err := s.db.Where("username = ?", req.Username).First(&user).Error; err != nil {
@@ -33,10 +41,25 @@ func (s *AuthService) Login(req dto.LoginRequest) (*dto.LoginResponse, error) {
return nil, errors.New("账号已被禁用")
}
// 账号锁定检查(到点自动解锁) // Logan.Li
if user.LockedUntil != nil && user.LockedUntil.After(time.Now()) {
remaining := int(time.Until(*user.LockedUntil).Minutes()) + 1
return nil, fmt.Errorf("失败次数过多,账号已锁定,请约 %d 分钟后再试", remaining)
}
if !utils.CheckPassword(req.Password, user.Password) {
s.registerLoginFailure(&user)
return nil, errors.New("用户名或密码错误")
}
// 登录成功:清零失败计数与锁定 // Logan.Li
if user.FailedLoginAttempts > 0 || user.LockedUntil != nil {
s.db.Model(&user).Updates(map[string]interface{}{
"failed_login_attempts": 0,
"locked_until": nil,
})
}
// 更新最后登录时间 // Logan.Li
now := time.Now()
s.db.Model(&user).Update("last_login", now)
@@ -59,6 +82,18 @@ func (s *AuthService) Login(req dto.LoginRequest) (*dto.LoginResponse, error) {
}, nil
}
// registerLoginFailure 记录一次登录失败,达到上限则锁定账号 // Logan.Li
func (s *AuthService) registerLoginFailure(user *model.User) {
attempts := user.FailedLoginAttempts + 1
updates := map[string]interface{}{"failed_login_attempts": attempts}
if attempts >= maxLoginAttempts {
lockedUntil := time.Now().Add(loginLockDuration)
updates["locked_until"] = &lockedUntil
updates["failed_login_attempts"] = 0 // 锁定期结束后重新计数 // Logan.Li
}
s.db.Model(user).Updates(updates)
}
// GetCurrentUser 根据 ID 获取当前用户信息 // Logan.Li
func (s *AuthService) GetCurrentUser(userID uint) (*dto.UserInfoResponse, error) {
var user model.User
@@ -75,7 +110,7 @@ func (s *AuthService) GetCurrentUser(userID uint) (*dto.UserInfoResponse, error)
}, nil
}
// ChangePassword 修改当前用户密码 // Logan.Li
// ChangePassword 修改当前用户密码;同时刷新会话失效基线,使所有旧令牌立即作废 // Logan.Li
func (s *AuthService) ChangePassword(userID uint, req dto.ChangePasswordRequest) error {
var user model.User
if err := s.db.First(&user, userID).Error; err != nil {
@@ -87,5 +122,8 @@ func (s *AuthService) ChangePassword(userID uint, req dto.ChangePasswordRequest)
}
user.Password = utils.HashPassword(req.NewPassword)
user.TokenValidAfter = time.Now() // 旧 JWT 全部失效,需重新登录 // Logan.Li
user.FailedLoginAttempts = 0
user.LockedUntil = nil
return s.db.Save(&user).Error
}