auth_controller.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package controller
  2. import (
  3. "net/http"
  4. "github.com/2930134478/AI-CS/backend/service"
  5. "github.com/gin-gonic/gin"
  6. )
  7. // AuthController 负责处理认证相关的 HTTP 请求。
  8. type AuthController struct {
  9. authService *service.AuthService
  10. }
  11. // NewAuthController 创建 AuthController 实例。
  12. func NewAuthController(authService *service.AuthService) *AuthController {
  13. return &AuthController{authService: authService}
  14. }
  15. type loginRequest struct {
  16. Username string `json:"username"`
  17. Password string `json:"password"`
  18. }
  19. // Login 处理登录请求。
  20. func (a *AuthController) Login(c *gin.Context) {
  21. var req loginRequest
  22. if err := c.ShouldBindJSON(&req); err != nil || req.Username == "" || req.Password == "" {
  23. c.JSON(http.StatusBadRequest, gin.H{"error": "用户名和密码不能为空"})
  24. return
  25. }
  26. user, err := a.authService.Login(req.Username, req.Password)
  27. if err != nil {
  28. switch err {
  29. case service.ErrInvalidCredentials:
  30. c.JSON(http.StatusUnauthorized, gin.H{"error": "用户名或密码错误"})
  31. default:
  32. c.JSON(http.StatusInternalServerError, gin.H{"error": "登录失败"})
  33. }
  34. return
  35. }
  36. c.JSON(http.StatusOK, gin.H{
  37. "message": "登录成功",
  38. "user_id": user.ID,
  39. "username": user.Username,
  40. "role": user.Role,
  41. })
  42. }
  43. // Logout 响应退出登录请求。
  44. func (a *AuthController) Logout(c *gin.Context) {
  45. c.JSON(http.StatusOK, gin.H{"message": "退出成功"})
  46. }