pgweb/pkg/api/middleware.go

68 lines
1.4 KiB
Go
Raw 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 {
badRequest(c, errNotConnected)
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
sid := getSessionId(c.Request)
if sid == "" {
badRequest(c, errSessionRequired)
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
2022-12-02 13:36:31 -06:00
conn := DbSessions.Get(sid)
2016-01-10 15:03:33 -06:00
if conn == nil {
badRequest(c, errNotConnected)
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
}
}