feat(auth): 添加登录后重定向功能

- 在 GetLogin 和 PostLogin 函数中添加 return_url 参数
- 在 AuthRequired 中间件中添加重定向到登录页面的逻辑
- 修改登录表单,添加隐藏的 return_url 字段
- 优化错误处理,保留 return_url 以便登录失败后重新显示
This commit is contained in:
高手 2025-02-16 00:55:23 +08:00
parent 5cb134fa9d
commit 42fcb4f754
3 changed files with 37 additions and 5 deletions

View File

@ -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, "/")
}
}

View File

@ -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
}

View File

@ -122,6 +122,7 @@
<input type="password" id="password" name="password" required
placeholder="请输入密码">
</div>
<input type="hidden" name="return_url" value="{{ .return_url }}">
<button type="submit">立即登录</button>
</form>
<div class="login-link">