1. 调整目录结构
2. 实现user_controller
This commit is contained in:
149
internal/app/controller/user/user_controller.go
Normal file
149
internal/app/controller/user/user_controller.go
Normal file
@@ -0,0 +1,149 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.huangwc.com/pig/pig-farm-controller/internal/app/controller"
|
||||
"git.huangwc.com/pig/pig-farm-controller/internal/infra/logs"
|
||||
"git.huangwc.com/pig/pig-farm-controller/internal/infra/models"
|
||||
"git.huangwc.com/pig/pig-farm-controller/internal/infra/repository"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// jwtSecret 是用于签名 JWT 的密钥。在生产环境中,这应该从环境变量或安全配置中读取。
|
||||
var jwtSecret = []byte("your_super_secret_jwt_key")
|
||||
|
||||
// Controller 用户控制器
|
||||
type Controller struct {
|
||||
userRepo repository.UserRepository
|
||||
logger *logs.Logger
|
||||
}
|
||||
|
||||
// NewController 创建用户控制器实例
|
||||
func NewController(userRepo repository.UserRepository, logger *logs.Logger) *Controller {
|
||||
return &Controller{
|
||||
userRepo: userRepo,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateUserRequest 定义创建用户请求的结构体
|
||||
type CreateUserRequest struct {
|
||||
Username string `json:"username" binding:"required"`
|
||||
Password string `json:"password" binding:"required,min=6"`
|
||||
}
|
||||
|
||||
// LoginRequest 定义登录请求的结构体
|
||||
type LoginRequest struct {
|
||||
Username string `json:"username" binding:"required"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
}
|
||||
|
||||
// CreateUserResponse 定义创建用户成功响应的结构体
|
||||
type CreateUserResponse struct {
|
||||
Username string `json:"username"`
|
||||
ID uint `json:"id"`
|
||||
}
|
||||
|
||||
// LoginResponse 定义登录成功响应的结构体
|
||||
type LoginResponse struct {
|
||||
Username string `json:"username"`
|
||||
ID uint `json:"id"`
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
// generateToken 为给定用户生成 JWT
|
||||
func generateToken(userID uint, username string) (string, error) {
|
||||
expirationTime := time.Now().Add(24 * time.Hour) // Token 24 小时后过期
|
||||
claims := jwt.MapClaims{
|
||||
"user_id": userID,
|
||||
"username": username,
|
||||
"exp": expirationTime.Unix(),
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
tokenString, err := token.SignedString(jwtSecret)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return tokenString, nil
|
||||
}
|
||||
|
||||
// CreateUser 处理创建用户的请求
|
||||
func (c *Controller) CreateUser(ctx *gin.Context) {
|
||||
var req CreateUserRequest
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
c.logger.Errorf("CreateUser: 参数绑定失败: %v", err)
|
||||
controller.SendErrorResponse(ctx, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
user := &models.User{
|
||||
Username: req.Username,
|
||||
Password: req.Password, // 密码会在 BeforeSave 钩子中哈希
|
||||
}
|
||||
|
||||
if err := c.userRepo.Create(user); err != nil {
|
||||
c.logger.Errorf("CreateUser: 创建用户失败: %v", err)
|
||||
|
||||
// 尝试查询用户,以判断是否是用户名重复导致的错误
|
||||
_, findErr := c.userRepo.FindByUsername(req.Username)
|
||||
if findErr == nil { // 如果能找到用户,说明是用户名重复
|
||||
controller.SendErrorResponse(ctx, http.StatusConflict, "用户名已存在")
|
||||
return
|
||||
}
|
||||
|
||||
// 其他创建失败的情况
|
||||
controller.SendErrorResponse(ctx, http.StatusInternalServerError, "创建用户失败")
|
||||
return
|
||||
}
|
||||
|
||||
controller.SendResponse(ctx, http.StatusOK, "用户创建成功", CreateUserResponse{
|
||||
Username: user.Username,
|
||||
ID: user.ID,
|
||||
})
|
||||
}
|
||||
|
||||
// Login 处理用户登录请求
|
||||
func (c *Controller) Login(ctx *gin.Context) {
|
||||
var req LoginRequest
|
||||
if err := ctx.ShouldBindJSON(&req); err != nil {
|
||||
c.logger.Errorf("Login: 参数绑定失败: %v", err)
|
||||
controller.SendErrorResponse(ctx, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
user, err := c.userRepo.FindByUsername(req.Username)
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
controller.SendErrorResponse(ctx, http.StatusUnauthorized, "用户名或密码不正确")
|
||||
return
|
||||
}
|
||||
c.logger.Errorf("Login: 查询用户失败: %v", err)
|
||||
controller.SendErrorResponse(ctx, http.StatusInternalServerError, "登录失败")
|
||||
return
|
||||
}
|
||||
|
||||
if !user.CheckPassword(req.Password) {
|
||||
controller.SendErrorResponse(ctx, http.StatusUnauthorized, "用户名或密码不正确")
|
||||
return
|
||||
}
|
||||
|
||||
// 登录成功,生成 JWT token
|
||||
tokenString, err := generateToken(user.ID, user.Username)
|
||||
if err != nil {
|
||||
c.logger.Errorf("Login: 生成 token 失败: %v", err)
|
||||
controller.SendErrorResponse(ctx, http.StatusInternalServerError, "登录失败,无法生成认证信息")
|
||||
return
|
||||
}
|
||||
|
||||
controller.SendResponse(ctx, http.StatusOK, "登录成功", LoginResponse{
|
||||
Username: user.Username,
|
||||
ID: user.ID,
|
||||
Token: tokenString,
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user