增加session验证
This commit is contained in:
@@ -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")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user