Merge pull request #111 from sosedoff/sessions

Database sessions
This commit is contained in:
Dan Sosedoff
2016-01-10 15:36:02 -06:00
8 changed files with 188 additions and 92 deletions

View File

@@ -14,7 +14,38 @@ import (
"github.com/sosedoff/pgweb/pkg/connection"
)
var DbClient *client.Client
var (
DbClient *client.Client
DbSessions = map[string]*client.Client{}
)
func DB(c *gin.Context) *client.Client {
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) {
serveStaticAsset("/index.html", c)
@@ -24,6 +55,17 @@ func GetAsset(c *gin.Context) {
serveStaticAsset(c.Params.ByName("path"), c)
}
func GetSessions(c *gin.Context) {
// In debug mode endpoint will return a lot of sensitive information
// like full database connection string and all query history.
if command.Opts.Debug {
c.JSON(200, DbSessions)
return
}
c.JSON(200, map[string]int{"sessions": len(DbSessions)})
}
func Connect(c *gin.Context) {
url := c.Request.FormValue("url")
@@ -53,20 +95,20 @@ func Connect(c *gin.Context) {
}
info, err := cl.Info()
if err == nil {
if DbClient != nil {
DbClient.Close()
err = setClient(c, cl)
if err != nil {
cl.Close()
c.JSON(400, Error{err.Error()})
return
}
DbClient = cl
}
c.JSON(200, info.Format()[0])
}
func GetDatabases(c *gin.Context) {
names, err := DbClient.Databases()
names, err := DB(c).Databases()
serveResult(names, err, c)
}
@@ -93,17 +135,17 @@ func ExplainQuery(c *gin.Context) {
}
func GetSchemas(c *gin.Context) {
names, err := DbClient.Schemas()
names, err := DB(c).Schemas()
serveResult(names, err, c)
}
func GetTables(c *gin.Context) {
names, err := DbClient.Tables()
names, err := DB(c).Tables()
serveResult(names, err, c)
}
func GetTable(c *gin.Context) {
res, err := DbClient.Table(c.Params.ByName("table"))
res, err := DB(c).Table(c.Params.ByName("table"))
serveResult(res, err, c)
}
@@ -128,13 +170,13 @@ func GetTableRows(c *gin.Context) {
Where: c.Request.FormValue("where"),
}
res, err := DbClient.TableRows(c.Params.ByName("table"), opts)
res, err := DB(c).TableRows(c.Params.ByName("table"), opts)
if err != nil {
c.JSON(400, NewError(err))
return
}
countRes, err := DbClient.TableRowsCount(c.Params.ByName("table"), opts)
countRes, err := DB(c).TableRowsCount(c.Params.ByName("table"), opts)
if err != nil {
c.JSON(400, NewError(err))
return
@@ -160,7 +202,7 @@ func GetTableRows(c *gin.Context) {
}
func GetTableInfo(c *gin.Context) {
res, err := DbClient.TableInfo(c.Params.ByName("table"))
res, err := DB(c).TableInfo(c.Params.ByName("table"))
if err != nil {
c.JSON(400, NewError(err))
@@ -171,11 +213,11 @@ func GetTableInfo(c *gin.Context) {
}
func GetHistory(c *gin.Context) {
c.JSON(200, DbClient.History)
c.JSON(200, DB(c).History)
}
func GetConnectionInfo(c *gin.Context) {
res, err := DbClient.Info()
res, err := DB(c).Info()
if err != nil {
c.JSON(400, NewError(err))
@@ -186,22 +228,22 @@ func GetConnectionInfo(c *gin.Context) {
}
func GetSequences(c *gin.Context) {
res, err := DbClient.Sequences()
res, err := DB(c).Sequences()
serveResult(res, err, c)
}
func GetActivity(c *gin.Context) {
res, err := DbClient.Activity()
res, err := DB(c).Activity()
serveResult(res, err, c)
}
func GetTableIndexes(c *gin.Context) {
res, err := DbClient.TableIndexes(c.Params.ByName("table"))
res, err := DB(c).TableIndexes(c.Params.ByName("table"))
serveResult(res, err, c)
}
func GetTableConstraints(c *gin.Context) {
res, err := DbClient.TableConstraints(c.Params.ByName("table"))
res, err := DB(c).TableConstraints(c.Params.ByName("table"))
serveResult(res, err, c)
}
@@ -211,7 +253,7 @@ func HandleQuery(query string, c *gin.Context) {
query = string(rawQuery)
}
result, err := DbClient.Query(query)
result, err := DB(c).Query(query)
if err != nil {
c.JSON(400, NewError(err))
return

View File

@@ -2,13 +2,11 @@ package api
import (
"fmt"
"log"
"mime"
"path/filepath"
"strconv"
"github.com/gin-gonic/gin"
"github.com/sosedoff/pgweb/pkg/data"
)
var extraMimeTypes = map[string]string{
@@ -20,10 +18,27 @@ var extraMimeTypes = map[string]string{
".html": "text/html; charset-utf-8",
}
// Paths that dont require database connection
var allowedPaths = map[string]bool{
"/api/sessions": true,
"/api/info": true,
"/api/connect": true,
"/api/bookmarks": true,
"/api/history": true,
}
type Error struct {
Message string `json:"error"`
}
func getSessionId(c *gin.Context) string {
id := c.Request.Header.Get("x-session-id")
if id == "" {
id = c.Request.URL.Query().Get("_session_id")
}
return id
}
func getQueryParam(c *gin.Context, name string) string {
result := ""
q := c.Request.URL.Query()
@@ -72,67 +87,3 @@ func assetContentType(name string) string {
func NewError(err error) Error {
return Error{err.Error()}
}
// Middleware function to check database connection status before running queries
func dbCheckMiddleware() gin.HandlerFunc {
allowedPaths := []string{
"/api/info",
"/api/connect",
"/api/bookmarks",
"/api/history",
}
return func(c *gin.Context) {
if DbClient != nil {
c.Next()
return
}
currentPath := c.Request.URL.Path
allowed := false
for _, path := range allowedPaths {
if path == currentPath {
allowed = true
break
}
}
if allowed {
c.Next()
} else {
c.JSON(400, Error{"Not connected"})
c.Abort()
}
return
}
}
// Middleware function to print out request parameters and body for debugging
func requestInspectMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
err := c.Request.ParseForm()
log.Println("Request params:", err, c.Request.Form)
}
}
func serveStaticAsset(path string, c *gin.Context) {
data, err := data.Asset("static" + path)
if err != nil {
c.String(400, err.Error())
return
}
c.Data(200, assetContentType(path), data)
}
func serveResult(result interface{}, err error, c *gin.Context) {
if err != nil {
c.JSON(400, NewError(err))
return
}
c.JSON(200, result)
}

75
pkg/api/middleware.go Normal file
View File

@@ -0,0 +1,75 @@
package api
import (
"log"
"github.com/gin-gonic/gin"
"github.com/sosedoff/pgweb/pkg/command"
"github.com/sosedoff/pgweb/pkg/data"
)
// Middleware function to check database connection status before running queries
func dbCheckMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
if allowedPaths[c.Request.URL.Path] == true {
c.Next()
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"})
c.Abort()
return
}
conn := DbSessions[sessionId]
if conn == nil {
c.JSON(400, Error{"Not connected"})
c.Abort()
return
}
c.Next()
}
}
// Middleware function to print out request parameters and body for debugging
func requestInspectMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
err := c.Request.ParseForm()
log.Println("Request params:", err, c.Request.Form)
}
}
func serveStaticAsset(path string, c *gin.Context) {
data, err := data.Asset("static" + path)
if err != nil {
c.String(400, err.Error())
return
}
c.Data(200, assetContentType(path), data)
}
func serveResult(result interface{}, err error, c *gin.Context) {
if err != nil {
c.JSON(400, NewError(err))
return
}
c.JSON(200, result)
}

View File

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

View File

@@ -15,8 +15,8 @@ import (
type Client struct {
db *sqlx.DB
History []history.Record
ConnectionString string
History []history.Record `json:"history"`
ConnectionString string `json:"connection_string"`
}
// Struct to hold table rows browsing options

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
@@ -35,5 +36,9 @@ func ParseOptions() error {
Opts.Url = os.Getenv("DATABASE_URL")
}
if os.Getenv("SESSIONS") != "" {
Opts.Sessions = true
}
return nil
}

File diff suppressed because one or more lines are too long

View File

@@ -16,6 +16,22 @@ var filterOptions = {
"not_null": "IS NOT NULL"
};
function guid() {
function s4() { return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); }
return [s4(), s4(), "-", s4(), "-", s4(), "-", s4(), "-", s4(), s4(), s4()].join("");
}
function getSessionId() {
var id = localStorage.getItem("session_id");
if (!id) {
id = guid();
localStorage.setItem("session_id", id);
}
return id;
}
function setRowsLimit(num) {
localStorage.setItem("rows_limit", num);
}
@@ -47,6 +63,9 @@ function apiCall(method, path, params, cb) {
method: method,
cache: false,
data: params,
headers: {
"x-session-id": getSessionId()
},
success: function(data) {
cb(data);
},