Skip to content

Commit

Permalink
added pgpass feature to wrong command
Browse files Browse the repository at this point in the history
also fixed writing to file
  • Loading branch information
davidsteinsland committed Mar 17, 2022
1 parent 268fb16 commit 018c96e
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 8 deletions.
27 changes: 26 additions & 1 deletion cmd/root/postgres/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"log"
"net"
"os"
"os/signal"
"syscall"
"time"
Expand Down Expand Up @@ -44,10 +45,34 @@ var proxyCmd = &cobra.Command{
if err != nil {
return err
}
connectionInfo, err := dbInfo.DBConnection(ctx)
if err != nil {
return err
}
email, err := currentEmail(ctx)
if err != nil {
return err
}

token, err := getGCPToken(ctx)
if err != nil {
return err
}

fmt.Printf("Starting proxy on %v:%v\n", host, port)

return runProxy(ctx, projectID, connectionName, fmt.Sprintf("%v:%v", host, port), make(chan int, 1))
address := fmt.Sprintf("%v:%v", host, port)

pgpass := []byte(fmt.Sprintf("%s:%s:%s:%s", address, connectionInfo.dbName, email, token))
if home, err := os.UserHomeDir(); err == nil {
if err := os.WriteFile(fmt.Sprintf("%s/.pgpass", home), pgpass, 0600); err != nil {
fmt.Printf("Failed to write contents to pgpass file: %v\n", err)
} else {
fmt.Printf("You can authenticate to %s using 'pgpass' method: log in using only <%s> as username\n", connectionInfo.dbName, email)
}
}

return runProxy(ctx, projectID, connectionName, address, make(chan int, 1))
},
}

Expand Down
7 changes: 0 additions & 7 deletions cmd/root/postgres/psql.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,13 +84,6 @@ var psqlCmd = &cobra.Command{
"--dbname", connectionInfo.dbName,
}

pgpass := []byte(fmt.Sprintf("localhost:5432:%s:%s:%s", connectionInfo.dbName, email, token))
if err := os.WriteFile("~/.pgpass", pgpass, 0600); err != nil {
log.Println("Failed to write contents to pgpass file")
} else {
log.Printf("You can authenticate using 'pgpass' method: log in using only <%s> as username\n", email)
}

cmd := exec.CommandContext(ctx, psqlPath, arguments...)
cmd.Env = append(cmd.Env, fmt.Sprintf("PGPASSWORD=%s", token))

Expand Down

0 comments on commit 018c96e

Please sign in to comment.