Make sessions optional via --sessions CLI flag

This commit is contained in:
Dan Sosedoff 2016-01-08 19:44:31 -06:00
parent ed94244741
commit d772ae0b31
4 changed files with 53 additions and 17 deletions

View File

@ -14,11 +14,37 @@ import (
"github.com/sosedoff/pgweb/pkg/connection"
)
var DbClient *client.Client
var DbSessions = map[string]*client.Client{}
var (
DbClient *client.Client
DbSessions = map[string]*client.Client{}
)
func DB(c *gin.Context) *client.Client {
return DbSessions[getSessionId(c)]
if command.Opts.Sessions {
return DbSessions[getSessionId(c)]
} else {
return DbClient
}
}
func setClient(c *gin.Context, newClient *client.Client) error {
currentClient := DB(c)
if currentClient != nil {
currentClient.Close()
}
if !command.Opts.Sessions {
DbClient = newClient
return nil
}
sessionId := getSessionId(c)
if sessionId == "" {
return errors.New("Session ID is required")
}
DbSessions[sessionId] = newClient
return nil
}
func GetHome(c *gin.Context) {
@ -41,12 +67,6 @@ func Connect(c *gin.Context) {
return
}
sessionId := getSessionId(c)
if sessionId == "" {
c.JSON(400, Error{"Session ID is required"})
return
}
opts := command.Options{Url: url}
url, err := connection.FormatUrl(opts)
@ -68,14 +88,13 @@ func Connect(c *gin.Context) {
}
info, err := cl.Info()
if err == nil {
db := DbSessions[sessionId]
if db != nil {
db.Close()
err = setClient(c, cl)
if err != nil {
cl.Close()
c.JSON(400, Error{err.Error()})
return
}
DbSessions[sessionId] = cl
}
c.JSON(200, info.Format()[0])

View File

@ -8,6 +8,8 @@ import (
"strconv"
"github.com/gin-gonic/gin"
"github.com/sosedoff/pgweb/pkg/command"
"github.com/sosedoff/pgweb/pkg/data"
)
@ -98,6 +100,18 @@ func dbCheckMiddleware() gin.HandlerFunc {
return
}
// We dont care about sessions unless they're enabled
if !command.Opts.Sessions {
if DbClient == nil {
c.JSON(400, Error{"Not connected"})
c.Abort()
return
}
c.Next()
return
}
sessionId := getSessionId(c)
if sessionId == "" {
c.JSON(400, Error{"Session ID is required"})
@ -112,7 +126,6 @@ func dbCheckMiddleware() gin.HandlerFunc {
return
}
c.Set("db", conn)
c.Next()
}
}

View File

@ -21,8 +21,11 @@ func SetupRoutes(router *gin.Engine) {
{
SetupMiddlewares(api)
if command.Opts.Sessions {
api.GET("/sessions", GetSessions)
}
api.GET("/info", GetInfo)
api.GET("/sessions", GetSessions)
api.POST("/connect", Connect)
api.GET("/databases", GetDatabases)
api.GET("/connection", GetConnectionInfo)

View File

@ -21,6 +21,7 @@ type Options struct {
AuthUser string `long:"auth-user" description:"HTTP basic auth user"`
AuthPass string `long:"auth-pass" description:"HTTP basic auth password"`
SkipOpen bool `short:"s" long:"skip-open" description:"Skip browser open on start"`
Sessions bool `long:"sessions" description:"Enable multiple database sessions" default:"false"`
}
var Opts Options