Files
nl-blogs/server/handlers/auth.go

97 lines
2.0 KiB
Go
Raw Normal View History

2026-01-15 13:51:44 +08:00
package handlers
import (
2026-01-16 17:03:34 +08:00
"fmt"
2026-01-15 13:51:44 +08:00
"github.com/gin-gonic/gin"
2026-01-19 16:14:08 +08:00
"github.com/niangaodev/art-code/middleware"
2026-01-15 13:51:44 +08:00
"github.com/niangaodev/art-code/models"
"github.com/niangaodev/art-code/repositories"
2026-01-16 17:03:34 +08:00
"github.com/niangaodev/art-code/utils"
2026-01-15 13:51:44 +08:00
)
2026-01-16 17:03:34 +08:00
// Login 请求结构
type LoginRequest struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}
// Login 登录
func Login(c *gin.Context) {
var req LoginRequest
2026-01-15 13:51:44 +08:00
if err := c.ShouldBindJSON(&req); err != nil {
2026-01-16 17:03:34 +08:00
utils.Error(c, 400, "Invalid request")
2026-01-15 13:51:44 +08:00
return
}
// 获取用户
user, err := repositories.GetUserByUsername(req.Username)
if err != nil {
2026-01-16 17:03:34 +08:00
utils.ServerError(c, err)
2026-01-15 13:51:44 +08:00
return
}
if user == nil {
2026-01-16 17:03:34 +08:00
utils.Error(c, 401, "Invalid username or password")
2026-01-15 13:51:44 +08:00
return
}
// 验证密码
2026-01-19 16:14:08 +08:00
if !utils.CheckPasswordHash(req.Password, user.PasswordHash) {
2026-01-16 17:03:34 +08:00
utils.Error(c, 401, "Invalid username or password")
2026-01-15 13:51:44 +08:00
return
}
2026-01-16 17:03:34 +08:00
// 生成JWT Token
2026-01-19 16:14:08 +08:00
tokenString, expireUnix, err := middleware.GenerateToken(user.ID, user.Username, user.Role)
2026-01-15 13:51:44 +08:00
if err != nil {
2026-01-16 17:03:34 +08:00
utils.ServerError(c, err)
2026-01-15 13:51:44 +08:00
return
}
2026-01-16 17:03:34 +08:00
// 记录登录日志
go func() {
ip := c.ClientIP()
location := utils.GetRegion(ip)
logEntry := &models.UserAccessLog{
UserID: user.ID,
UserIP: ip,
UserLocation: location,
}
if err := repositories.CreateUserAccessLog(logEntry); err != nil {
fmt.Printf("Failed to create login log: %v\n", err)
}
}()
utils.Success(c, gin.H{
2026-01-19 16:14:08 +08:00
"token": tokenString,
"expire": expireUnix,
2026-01-16 17:03:34 +08:00
"user": gin.H{
"id": user.ID,
"username": user.Username,
"email": user.Email,
"role": user.Role,
},
})
}
// GetCurrentUser 获取当前用户信息
func GetCurrentUser(c *gin.Context) {
userID, exists := c.Get("userID")
if !exists {
utils.Error(c, 401, "Unauthorized")
return
}
user, err := repositories.GetUserByID(userID.(uint))
if err != nil {
utils.ServerError(c, err)
return
}
if user == nil {
utils.Error(c, 404, "User not found")
return
2026-01-15 13:51:44 +08:00
}
2026-01-16 17:03:34 +08:00
utils.Success(c, repositories.BuildUserResponse(user))
2026-01-15 13:51:44 +08:00
}