55bfdf08ce
Deploy PR-Helper / deploy (push) Successful in 31s
- Go 后端 handler 错误消息统一中文化(middleware/repos/generate/review/settings) - 前端 JS 加载和错误消息中文化(diff-viewer.js, graph.js) - 模板页面错误 fallback 和静态文本中文化(index/generate/review/base) - 消除中英文混杂,提升中文用户体验
59 lines
1.6 KiB
Go
59 lines
1.6 KiB
Go
package handlers
|
|
|
|
import (
|
|
"database/sql"
|
|
"net/http"
|
|
|
|
"github.com/gin-contrib/sessions"
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"github.com/HoHD/PR-Helper/models"
|
|
)
|
|
|
|
// AuthRequired returns middleware that requires a logged-in user.
|
|
// Page requests are redirected to /login; API requests get 401 JSON.
|
|
func AuthRequired(db *sql.DB) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
session := sessions.Default(c)
|
|
userID := session.Get("user_id")
|
|
if userID == nil {
|
|
// Check if it's an API request
|
|
if len(c.Request.URL.Path) > 4 && c.Request.URL.Path[:5] == "/api/" {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "未登录"})
|
|
} else {
|
|
c.Redirect(http.StatusFound, "/login")
|
|
c.Abort()
|
|
}
|
|
return
|
|
}
|
|
|
|
// Load user from DB and store in context
|
|
var user models.User
|
|
err := db.QueryRow(`SELECT id, email, password_hash, created_at, updated_at FROM users WHERE id = ?`,
|
|
userID).Scan(&user.ID, &user.Email, &user.PasswordHash, &user.CreatedAt, &user.UpdatedAt)
|
|
if err != nil {
|
|
// User no longer exists, clear session
|
|
session.Clear()
|
|
session.Save()
|
|
if len(c.Request.URL.Path) > 4 && c.Request.URL.Path[:5] == "/api/" {
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "未登录"})
|
|
} else {
|
|
c.Redirect(http.StatusFound, "/login")
|
|
c.Abort()
|
|
}
|
|
return
|
|
}
|
|
|
|
c.Set("user", &user)
|
|
c.Next()
|
|
}
|
|
}
|
|
|
|
// GetCurrentUser extracts the authenticated user from the Gin context.
|
|
func GetCurrentUser(c *gin.Context) *models.User {
|
|
if user, exists := c.Get("user"); exists {
|
|
return user.(*models.User)
|
|
}
|
|
return nil
|
|
}
|