Files
PR-Helper/handlers/middleware.go
T

59 lines
1.6 KiB
Go
Raw Normal View History

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
}