- 新增 utils.InternalMsg:内部错误详情只进服务端日志,对外统一脱敏 消息,不再向客户端泄露 GORM/SQL 实现细节;九个 controller 的 err.Error() 出口全部切换 - 新增 .github/workflows/ci.yml:go build/vet/test(backend,go 1.25)
82 lines
2.4 KiB
Go
82 lines
2.4 KiB
Go
package auth
|
|
|
|
import (
|
|
"backend/config"
|
|
authservice "backend/internal/service/auth"
|
|
"backend/utils"
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"gorm.io/gorm"
|
|
)
|
|
|
|
// 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
|
|
func (ctrl *AuthController) Login(c *gin.Context) {
|
|
var req struct {
|
|
Username string `json:"username" binding:"required"`
|
|
Password string `json:"password" binding:"required"`
|
|
}
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "请求参数错误: " + err.Error()})
|
|
return
|
|
}
|
|
|
|
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": utils.InternalMsg(err)})
|
|
return
|
|
}
|
|
|
|
utils.LogAuthAction(ctrl.db, c, "login", req.Username, "登录成功", "success")
|
|
c.JSON(http.StatusOK, gin.H{"code": 0, "message": "登录成功", "data": result})
|
|
}
|
|
|
|
// Me 获取当前登录用户信息 // Logan.Li
|
|
func (ctrl *AuthController) Me(c *gin.Context) {
|
|
userID, _ := c.Get("user_id")
|
|
|
|
userInfo, err := ctrl.authService.GetCurrentUser(userID.(uint))
|
|
if err != nil {
|
|
c.JSON(http.StatusOK, gin.H{"code": 1, "message": utils.InternalMsg(err)})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{"code": 0, "data": userInfo})
|
|
}
|
|
|
|
// ChangePassword 修改当前用户密码 // Logan.Li
|
|
func (ctrl *AuthController) ChangePassword(c *gin.Context) {
|
|
userID, _ := c.Get("user_id")
|
|
|
|
var req struct {
|
|
OldPassword string `json:"old_password" binding:"required"`
|
|
NewPassword string `json:"new_password" binding:"required,min=6"`
|
|
}
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "请求参数错误: " + err.Error()})
|
|
return
|
|
}
|
|
|
|
if err := ctrl.authService.ChangePassword(userID.(uint), req); err != nil {
|
|
c.JSON(http.StatusOK, gin.H{"code": 1, "message": utils.InternalMsg(err)})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{"code": 0, "message": "密码修改成功"})
|
|
}
|