100 lines
2.3 KiB
Go
100 lines
2.3 KiB
Go
//go:build ignore
|
|
|
|
package handler
|
|
|
|
import (
|
|
"net/http"
|
|
"time"
|
|
"xboard-go/internal/database"
|
|
"xboard-go/internal/model"
|
|
"xboard-go/internal/service"
|
|
"xboard-go/pkg/utils"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/google/uuid"
|
|
)
|
|
|
|
type LoginRequest struct {
|
|
Email string `json:"email" binding:"required,email"`
|
|
Password string `json:"password" binding:"required"`
|
|
}
|
|
|
|
type RegisterRequest struct {
|
|
Email string `json:"email" binding:"required,email"`
|
|
Password string `json:"password" binding:"required,min=8"`
|
|
InviteCode *string `json:"invite_code"`
|
|
}
|
|
|
|
func Login(c *gin.Context) {
|
|
var req LoginRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "参数错误"})
|
|
return
|
|
}
|
|
|
|
var user model.User
|
|
if err := database.DB.Where("email = ?", req.Email).First(&user).Error; err != nil {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"message": "邮箱或密码错误"})
|
|
return
|
|
}
|
|
|
|
if !utils.CheckPassword(req.Password, user.Password) {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"message": "邮箱或密码错误"})
|
|
return
|
|
}
|
|
|
|
token, err := utils.GenerateToken(user.ID, user.IsAdmin)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "生成Token失败"})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"token": token,
|
|
"is_admin": user.IsAdmin,
|
|
})
|
|
}
|
|
|
|
func Register(c *gin.Context) {
|
|
var req RegisterRequest
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "参数错误"})
|
|
return
|
|
}
|
|
|
|
// Check if email already exists
|
|
var count int64
|
|
database.DB.Model(&model.User{}).Where("email = ?", req.Email).Count(&count)
|
|
if count > 0 {
|
|
c.JSON(http.StatusBadRequest, gin.H{"message": "该邮箱已被注册"})
|
|
return
|
|
}
|
|
|
|
hashedPassword, err := utils.HashPassword(req.Password)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "系统错误"})
|
|
return
|
|
}
|
|
|
|
newUUID := uuid.New().String()
|
|
token := service.GenerateSubscriptionToken()
|
|
|
|
user := model.User{
|
|
Email: req.Email,
|
|
Password: hashedPassword,
|
|
UUID: newUUID,
|
|
Token: token,
|
|
CreatedAt: time.Now().Unix(),
|
|
UpdatedAt: time.Now().Unix(),
|
|
}
|
|
|
|
if err := database.DB.Create(&user).Error; err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"message": "注册失败"})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"message": "注册成功",
|
|
})
|
|
}
|