diff --git a/envsec/internal/envcli/auth.go b/envsec/internal/envcli/auth.go index ca51f474..9144d907 100644 --- a/envsec/internal/envcli/auth.go +++ b/envsec/internal/envcli/auth.go @@ -6,6 +6,7 @@ package envcli import ( "fmt" + "github.com/pkg/errors" "github.com/spf13/cobra" "go.jetpack.io/envsec/internal/envvar" "go.jetpack.io/pkg/sandbox/auth" @@ -101,10 +102,9 @@ func whoAmICmd() *cobra.Command { return err } - tok := client.GetSession() - if tok == nil { - fmt.Fprintln(cmd.OutOrStdout(), "Not logged in") - return nil + tok, ok := client.GetSession() + if !ok { + return errors.New("not logged in. Run `envsec auth login` to log in") } idClaims := tok.IDClaims() diff --git a/envsec/internal/envcli/flags.go b/envsec/internal/envcli/flags.go index d8c3bf5b..70075a09 100644 --- a/envsec/internal/envcli/flags.go +++ b/envsec/internal/envcli/flags.go @@ -81,6 +81,7 @@ type cmdConfig struct { func (f *configFlags) genConfig(ctx context.Context) (*cmdConfig, error) { var tok *session.Token + var ok bool var err error if f.orgID == "" { @@ -89,8 +90,8 @@ func (f *configFlags) genConfig(ctx context.Context) (*cmdConfig, error) { return nil, err } - tok = client.GetSession() - if tok == nil { + tok, ok = client.GetSession() + if !ok { return nil, errors.Errorf( "To use envsec you must log in (`envsec auth login`) or specify --project-id and --org-id", ) diff --git a/envsec/internal/envcli/init.go b/envsec/internal/envcli/init.go index 1acc90fb..68540d60 100644 --- a/envsec/internal/envcli/init.go +++ b/envsec/internal/envcli/init.go @@ -19,7 +19,10 @@ func initCmd() *cobra.Command { if err != nil { return err } - tok := client.GetSession() + tok, ok := client.GetSession() + if !ok { + return errors.New("not logged in, run `envsec auth login`") + } wd, err := os.Getwd() if err != nil { diff --git a/pkg/sandbox/auth/auth.go b/pkg/sandbox/auth/auth.go index a626aa5b..4b17b33a 100644 --- a/pkg/sandbox/auth/auth.go +++ b/pkg/sandbox/auth/auth.go @@ -55,9 +55,16 @@ func (c *Client) LogoutFlow() error { return c.RevokeSession() } -func (c *Client) GetSession() *session.Token { - // TODO: automatically refresh token as needed - return c.store.ReadToken(c.issuer, c.clientID) +// GetSession returns the current valid session token, if any. If token is expired, +// it will attempt to refresh it. If no token is found, or is unable to be refreshed, +// it will return nil and false. +// TODO: automatically refresh token as needed +func (c *Client) GetSession() (*session.Token, bool) { + tok := c.store.ReadToken(c.issuer, c.clientID) + if tok == nil || !tok.Valid() { + return nil, false + } + return tok, true } func (c *Client) RefreshSession() *session.Token {