项目初始化
This commit is contained in:
70
internal/api/admin/auth.go
Normal file
70
internal/api/admin/auth.go
Normal file
@@ -0,0 +1,70 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"FileRelay/internal/auth"
|
||||
"FileRelay/internal/bootstrap"
|
||||
"FileRelay/internal/model"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
type AuthHandler struct{}
|
||||
|
||||
func NewAuthHandler() *AuthHandler {
|
||||
return &AuthHandler{}
|
||||
}
|
||||
|
||||
type LoginRequest struct {
|
||||
Password string `json:"password" binding:"required" example:"admin"`
|
||||
}
|
||||
|
||||
type LoginResponse struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
// Login 管理员登录
|
||||
// @Summary 管理员登录
|
||||
// @Description 通过密码换取 JWT Token
|
||||
// @Tags Admin
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param request body LoginRequest true "登录请求"
|
||||
// @Success 200 {object} model.Response{data=LoginResponse}
|
||||
// @Failure 401 {object} model.Response
|
||||
// @Router /admin/login [post]
|
||||
func (h *AuthHandler) Login(c *gin.Context) {
|
||||
var req LoginRequest
|
||||
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, model.ErrorResponse(model.CodeBadRequest, "Invalid request"))
|
||||
return
|
||||
}
|
||||
|
||||
var admin model.Admin
|
||||
if err := bootstrap.DB.First(&admin).Error; err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.ErrorResponse(model.CodeInternalError, "Admin not found"))
|
||||
return
|
||||
}
|
||||
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(admin.PasswordHash), []byte(req.Password)); err != nil {
|
||||
c.JSON(http.StatusUnauthorized, model.ErrorResponse(model.CodeUnauthorized, "Incorrect password"))
|
||||
return
|
||||
}
|
||||
|
||||
token, err := auth.GenerateToken(admin.ID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, model.ErrorResponse(model.CodeInternalError, "Failed to generate token"))
|
||||
return
|
||||
}
|
||||
|
||||
// 更新登录时间
|
||||
now := time.Now()
|
||||
bootstrap.DB.Model(&admin).Update("last_login", &now)
|
||||
|
||||
c.JSON(http.StatusOK, model.SuccessResponse(LoginResponse{
|
||||
Token: token,
|
||||
}))
|
||||
}
|
||||
Reference in New Issue
Block a user