Skip to content

Commit

Permalink
REC-57: open browser automatically
Browse files Browse the repository at this point in the history
When calling `engflow_auth login $cluster`, the browser will now automatically open to the correct url with the necessary query params appended.
  • Loading branch information
phoenixuprising committed Oct 17, 2024
1 parent cc6b9ca commit f8a2a44
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 4 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ This repository provides `engflow_auth`, a [Bazel credential helper](https://blo
## Use
1. Run `engflow_auth login [CLUSTER URL]` to obtain a credential. This prints a URL to visit in your browser.
1. Run `engflow_auth login [CLUSTER URL]` to obtain a credential. This opens a URL in your browser.
1. Visit the URL to complete the process, logging in if necessary. `engflow_auth` will download and store a credential in on your system's encrypted keyring.

This process needs to be repeated after the credential expires, typically every 90 days.
Expand Down
2 changes: 1 addition & 1 deletion cmd/engflow_auth/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ const (
)

type appState struct {
// These vars are initialized by `build()` iff they are not pre-populated;
// These vars are initialized by `build()` if they are not pre-populated;
// they should be pre-populated in tests and left nil otherwise.
userConfigDir string
browserOpener browser.Opener
Expand Down
31 changes: 29 additions & 2 deletions internal/browser/browser.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import (
"fmt"
"net/url"
"os"
"os/exec"
"runtime"
)

type Opener interface {
Expand All @@ -26,11 +28,36 @@ type Opener interface {

type StderrPrint struct{}

func openURL(url string) error {
var err error
switch runtime.GOOS {
case "darwin": // macOS
err = exec.Command("open", url).Start()
case "linux":
providers := []string{"xdg-open", "x-www-browser", "www-browser"}

// There are multiple possible providers to open a browser on linux
// One of them is xdg-open, another is x-www-browser, then there's www-browser, etc.
// Look for one that exists and run it
for _, provider := range providers {
if _, err := exec.LookPath(provider); err == nil {
err = exec.Command(provider, url).Start()
}
}
case "windows":
err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
default:
err = fmt.Errorf("unsupported platform")
}
return err
}

func (p *StderrPrint) Open(u *url.URL) error {
fmt.Fprintf(
os.Stderr,
"Please open the following URL in your web browser to authenticate:\n\n\t%s\n\n",
os.Stdout,
"Opening the following URL in your web browser to authenticate:\n\n\t%s\n\n",
u,
)
openURL(u.String())
return nil
}

0 comments on commit f8a2a44

Please sign in to comment.