diff --git a/gateway/handlers/auth.go b/gateway/handlers/auth.go index 7c0a64b..7d29de5 100644 --- a/gateway/handlers/auth.go +++ b/gateway/handlers/auth.go @@ -2,6 +2,7 @@ package handlers import ( "net/http" + "net/url" "strconv" "strings" @@ -15,22 +16,32 @@ import ( ) func GetLogin(c *gin.Context) { - c.HTML(http.StatusOK, "login.html", nil) + returnURL := c.Query("return_url") + c.HTML(http.StatusOK, "login.html", gin.H{ + "return_url": returnURL, + }) } func PostLogin(db *gorm.DB) gin.HandlerFunc { return func(c *gin.Context) { username := c.PostForm("username") password := c.PostForm("password") + returnURL := c.PostForm("return_url") var user models.User if err := db.Where("mobile = ?", username).First(&user).Error; err != nil { - c.HTML(http.StatusUnauthorized, "login.html", gin.H{"error": "用户不存在或密码错误"}) + c.HTML(http.StatusUnauthorized, "login.html", gin.H{ + "error": "用户不存在或密码错误", + "return_url": returnURL, + }) return } if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil { - c.HTML(http.StatusUnauthorized, "login.html", gin.H{"error": "用户不存在或密码错误"}) + c.HTML(http.StatusUnauthorized, "login.html", gin.H{ + "error": "用户不存在或密码错误", + "return_url": returnURL, + }) return } @@ -38,9 +49,24 @@ func PostLogin(db *gorm.DB) gin.HandlerFunc { session.Set("user", user.ID) if err := session.Save(); err != nil { utils.Logger.Errorf("Session保存失败: %v", err) - c.HTML(http.StatusInternalServerError, "login.html", gin.H{"error": "登录状态保存失败"}) + c.HTML(http.StatusInternalServerError, "login.html", gin.H{ + "error": "登录状态保存失败", + "return_url": returnURL, + }) return } + + if returnURL != "" { + decodedURL, err := url.QueryUnescape(returnURL) + if err != nil { + utils.Logger.Errorf("URL解码失败: %v", err) + c.Redirect(http.StatusSeeOther, "/") + return + } + c.Redirect(http.StatusSeeOther, decodedURL) + return + } + c.Redirect(http.StatusSeeOther, "/") } } diff --git a/gateway/middleware/auth.go b/gateway/middleware/auth.go index 432f190..5d58d73 100644 --- a/gateway/middleware/auth.go +++ b/gateway/middleware/auth.go @@ -2,6 +2,7 @@ package middleware import ( "net/http" + "net/url" "github.com/gin-contrib/sessions" "github.com/gin-gonic/gin" @@ -12,7 +13,11 @@ func AuthRequired() gin.HandlerFunc { session := sessions.Default(c) user := session.Get("user") if user == nil { - c.Redirect(http.StatusFound, "/login") + // 获取当前请求的完整URL + returnURL := c.Request.URL.String() + // URL编码处理,避免特殊字符造成问题 + encodedURL := url.QueryEscape(returnURL) + c.Redirect(http.StatusFound, "/login?return_url="+encodedURL) c.Abort() return } diff --git a/gateway/templates/login.html b/gateway/templates/login.html index a361cf8..9cfb693 100644 --- a/gateway/templates/login.html +++ b/gateway/templates/login.html @@ -122,6 +122,7 @@ +