1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
| package handlers
import ( "gin-demo/models" "gin-demo/utils" "net/http" "github.com/gin-gonic/gin" "gorm.io/gorm" )
type AuthHandler struct { DB *gorm.DB }
func NewAuthHandler(db *gorm.DB) *AuthHandler { return &AuthHandler{DB: db} }
func (h *AuthHandler) Register(c *gin.Context) { var user models.User if err := c.ShouldBindJSON(&user); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } var existingUser models.User if err := h.DB.Where("email = ?", user.Email).First(&existingUser).Error; err == nil { c.JSON(http.StatusBadRequest, gin.H{"error": "邮箱已存在"}) return } hashedPassword, err := utils.HashPassword(user.Password) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "密码加密失败"}) return } user.Password = hashedPassword if err := h.DB.Create(&user).Error; err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "创建用户失败"}) return } c.JSON(http.StatusCreated, gin.H{ "message": "注册成功", "user": gin.H{ "id": user.ID, "name": user.Name, "email": user.Email, }, }) }
func (h *AuthHandler) Login(c *gin.Context) { var loginData struct { Email string `json:"email" binding:"required,email"` Password string `json:"password" binding:"required"` } if err := c.ShouldBindJSON(&loginData); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } var user models.User if err := h.DB.Where("email = ?", loginData.Email).First(&user).Error; err != nil { c.JSON(http.StatusUnauthorized, gin.H{"error": "邮箱或密码错误"}) return } if !utils.CheckPasswordHash(loginData.Password, user.Password) { c.JSON(http.StatusUnauthorized, gin.H{"error": "邮箱或密码错误"}) return } token, err := utils.GenerateToken(user.ID) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "token生成失败"}) return } c.JSON(http.StatusOK, gin.H{ "message": "登录成功", "token": token, "user": gin.H{ "id": user.ID, "name": user.Name, "email": user.Email, }, }) }
func (h *AuthHandler) GetCurrentUser(c *gin.Context) { userID, exists := c.Get("userID") if !exists { c.JSON(http.StatusUnauthorized, gin.H{"error": "未认证"}) return } var user models.User if err := h.DB.First(&user, userID).Error; err != nil { c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"}) return } c.JSON(http.StatusOK, gin.H{ "user": gin.H{ "id": user.ID, "name": user.Name, "email": user.Email, }, }) }
|