增加session验证

This commit is contained in:
张超
2025-06-13 08:59:01 +08:00
parent 7913a2b381
commit 67c85327ee
8 changed files with 201 additions and 207 deletions

View File

@@ -9,14 +9,13 @@ package controllers
import (
"fmt"
"go_blog/models"
"go_blog/pkg/jwt"
"go_blog/pkg/util"
"go_blog/serializers"
"go_blog/themes"
"html/template"
"net/http"
"time"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
)
@@ -29,44 +28,30 @@ func UsersLoginHandler(ctx *gin.Context) {
return
}
// 修正:通过数据库查询获取用户记录(原逻辑直接使用 loginUser.GetUser() 未查询数据库)
// 验证用户逻辑不变
user := &models.Account{Username: loginUser.Username}
if err := models.DB.Where("username = ?", user.Username).First(user).Error; err != nil {
response.BadRequest("用户不存在")
return
}
// 修正:使用 IsPasswordEqual 验证密码
if !user.IsPasswordEqual(loginUser.Password) {
response.BadRequest("密码错误")
return
}
token, err := jwt.GenerateToken(user)
if err != nil {
response.ServerError("生成令牌失败: " + err.Error())
return
}
// 改为设置Session替代JWT
session := sessions.Default(ctx)
session.Set("user_id", user.ID) // 存储用户ID到Session
session.Save()
// 添加 Authorization 响应头(格式与 auth.go 的 AuthRequired 方法一致
ctx.Header("Authorization", "Bearer " + token)
// 表单提交场景设置Cookie并跳转需配合前端使用Cookie存储JWT
// 表单提交场景直接跳转无需设置JWT Cookie
if ctx.ContentType() == "application/x-www-form-urlencoded" {
http.SetCookie(ctx.Writer, &http.Cookie{
Name: "token",
Value: token,
Path: "/",
Expires: time.Now().Add(24 * time.Hour),
HttpOnly: true, // 防止XSS
})
ctx.Redirect(http.StatusFound, "/admin/index")
return
}
// API请求场景返回JSON
// API请求场景返回登录成功无需返回token
data, _ := util.PrecisionLost(user)
data["token"] = token
response.Response(data, nil)
}
@@ -231,3 +216,20 @@ func ShowRegisterPage(c *gin.Context) {
c.String(http.StatusInternalServerError, "Error rendering template: "+err.Error())
}
}
// 退出登录
func UsersLogoutHandler(ctx *gin.Context) {
response := Response{Ctx: ctx}
session := sessions.Default(ctx) // 获取当前请求的Session
// 清除Session中的用户ID
session.Delete("user_id")
// 保存Session修改必须调用
if err := session.Save(); err != nil {
response.ServerError("退出失败: " + err.Error())
return
}
// 重定向到登录页
ctx.Redirect(http.StatusFound, "/admin/login")
}