2016-01-10 15:03:33 -06:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
2016-02-19 21:14:56 -06:00
|
|
|
"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) {
|
2016-02-19 21:14:56 -06:00
|
|
|
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 {
|
2019-09-29 12:16:42 -05:00
|
|
|
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
|
2019-09-29 12:16:42 -05:00
|
|
|
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 {
|
2019-09-29 12:16:42 -05:00
|
|
|
badRequest(c, errNotConnected)
|
2016-01-10 15:03:33 -06:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
c.Next()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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", "*")
|
2017-11-16 22:10:14 -06:00
|
|
|
c.Header("Access-Control-Allow-Origin", command.Opts.CorsOrigin)
|
2017-11-15 15:26:31 -06:00
|
|
|
}
|
|
|
|
}
|
2023-02-02 16:13:14 -06:00
|
|
|
|
|
|
|
func requireLocalQueries() gin.HandlerFunc {
|
|
|
|
return func(c *gin.Context) {
|
|
|
|
if QueryStore == nil {
|
|
|
|
badRequest(c, "local queries are disabled")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
c.Next()
|
|
|
|
}
|
|
|
|
}
|