auth_controller.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. // permissions 用于前端侧边栏显示(后端强校验以 X-User-Id 为准)
  42. "permissions": func() []string {
  43. if user.Role == "admin" {
  44. return service.AllPermissionKeys()
  45. }
  46. keys := service.DecodePermissions(user.Permissions)
  47. if len(keys) == 0 {
  48. return service.DefaultAgentPermissions()
  49. }
  50. return keys
  51. }(),
  52. })
  53. }
  54. // Logout 响应退出登录请求。
  55. func (a *AuthController) Logout(c *gin.Context) {
  56. c.JSON(http.StatusOK, gin.H{"message": "退出成功"})
  57. }