jdysya 42fcb4f754 feat(auth): 添加登录后重定向功能
- 在 GetLogin 和 PostLogin 函数中添加 return_url 参数
- 在 AuthRequired 中间件中添加重定向到登录页面的逻辑
- 修改登录表单,添加隐藏的 return_url 字段
- 优化错误处理,保留 return_url 以便登录失败后重新显示
2025-02-16 00:55:23 +08:00

27 lines
553 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package middleware
import (
"net/http"
"net/url"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
)
func AuthRequired() gin.HandlerFunc {
return func(c *gin.Context) {
session := sessions.Default(c)
user := session.Get("user")
if user == nil {
// 获取当前请求的完整URL
returnURL := c.Request.URL.String()
// URL编码处理避免特殊字符造成问题
encodedURL := url.QueryEscape(returnURL)
c.Redirect(http.StatusFound, "/login?return_url="+encodedURL)
c.Abort()
return
}
c.Next()
}
}