9c843b79ba
- 新增 users 和 user_settings 表,repositories/analyses/review_notes 添加 user_id 列 - 实现基于邮箱+密码的注册登录,密码使用 bcrypt 哈希 - 使用 gin-contrib/sessions cookie-based session 管理 - 所有仓库、分析记录、review notes 按用户隔离 - 用户设置(LLM 配置、review 参数、缓存配置)独立存储 - 新增登录/注册页面,导航栏显示用户邮箱和退出按钮 - 前端 fetch 请求统一添加 credentials: 'same-origin' - 支持 SESSION_SECRET 环境变量配置会话密钥
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": "unauthenticated"})
|
|
} 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": "unauthenticated"})
|
|
} 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
|
|
}
|