Files
opsx-licence/backend/internal/controller/auth/auth_controller.go
T

82 lines
2.3 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": err.Error()})
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": err.Error()})
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": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"code": 0, "message": "密码修改成功"})
}