pgweb/pkg/api/middleware.go

68 lines
1.5 KiB
Go
Raw Permalink Normal View History

2016-01-10 15:03:33 -06:00
package api
import (
"log"
"strings"
2016-01-10 15:03:33 -06:00
"github.com/gin-gonic/gin"
"github.com/sosedoff/pgweb/pkg/command"
)
2018-11-30 21:40:28 -06:00
// Middleware to check database connection status before running queries
2016-01-10 15:03:33 -06:00
func dbCheckMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
path := strings.Replace(c.Request.URL.Path, command.Opts.Prefix, "", -1)
2018-11-30 21:40:28 -06:00
// Allow whitelisted paths
if allowedPaths[path] {
2016-01-10 15:03:33 -06:00
c.Next()
return
}
2018-11-30 21:40:28 -06:00
// Check if session exists in single-session mode
2016-01-10 15:03:33 -06:00
if !command.Opts.Sessions {
if DbClient == nil {
2018-11-30 21:40:28 -06:00
badRequest(c, "Not connected")
2016-01-10 15:03:33 -06:00
return
}
c.Next()
return
}
2018-11-30 21:40:28 -06:00
// Determine session ID from the client request
2016-02-26 08:48:55 -08:00
sessionId := getSessionId(c.Request)
2016-01-10 15:03:33 -06:00
if sessionId == "" {
2018-11-30 21:40:28 -06:00
badRequest(c, "Session ID is required")
2016-01-10 15:03:33 -06:00
return
}
2018-11-30 21:40:28 -06:00
// Determine the database connection handle for the session
2016-01-10 15:03:33 -06:00
conn := DbSessions[sessionId]
if conn == nil {
2018-11-30 21:40:28 -06:00
badRequest(c, "Not connected")
2016-01-10 15:03:33 -06:00
return
}
c.Next()
}
}
2018-11-30 21:40:28 -06:00
// Middleware to print out request parameters and body for debugging
2016-01-10 15:03:33 -06:00
func requestInspectMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
err := c.Request.ParseForm()
log.Println("Request params:", err, c.Request.Form)
}
}
2018-11-30 21:40:28 -06:00
// Middleware to inject CORS headers
2017-11-15 15:26:31 -06:00
func corsMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
c.Header("Access-Control-Expose-Headers", "*")
c.Header("Access-Control-Allow-Origin", command.Opts.CorsOrigin)
2017-11-15 15:26:31 -06:00
}
}