Skip to content

Commit

Permalink
Allow greater control over caching (#68)
Browse files Browse the repository at this point in the history
* Improve the help message - add the flag documentation.

* Make the cache location a variable (exported to allow modification),
set to home dir by default during initialization.

* Add a flag to set the cache file location.

* Support empty cache location, to explicitly disable caching.

* add help message for disabling cache.
  • Loading branch information
zagrodzki authored and shinfan committed May 15, 2019
1 parent 26742a1 commit cf46f2e
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 36 deletions.
32 changes: 17 additions & 15 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@ import (
"flag"
"fmt"
"io/ioutil"
"os"
"strings"

"github.com/google/oauth2l/sgauth"
"github.com/google/oauth2l/util"
"os"
)

var (
Expand All @@ -30,9 +31,10 @@ var (
cmds = []string{"fetch", "header", "info", "test"}
)

func help() {
fmt.Println("Usage: oauth2l {fetch|header|info|test|reset} " +
"[--jwt] [--json] [--sso] [--ssocli] {scope|aud|email}")
func help(f *flag.FlagSet) {
fmt.Println("Usage: oauth2l fetch|header|info|test|reset [flags]... [scope|aud|email]...")
f.PrintDefaults()
os.Exit(0)
}

func readJSON(file string) (string, error) {
Expand Down Expand Up @@ -69,11 +71,6 @@ func parseScopes(scopes []string) string {
}

func main() {
if len(os.Args) < 2 {
help()
return
}

// Configure the CLI
flagSet := flag.NewFlagSet("fetch", flag.ExitOnError)
helpFlag := flagSet.Bool("help", false, "Print help message.")
Expand All @@ -85,11 +82,16 @@ func main() {
jwtFlag := flagSet.Bool("jwt", false, "Use JWT auth flow")
ssoFlag := flagSet.Bool("sso", false, "Use SSO auth flow")
ssocli := flagSet.String("ssocli", "", "Path to SSO CLI")
flagSet.StringVar(&util.CacheLocation, "cache", util.CacheLocation, "Path to the credential cache file. Disables caching if set to empty.")

if len(os.Args) < 2 {
help(flagSet)
}

flagSet.Parse(os.Args[2:])

if *helpFlag {
help()
return
help(flagSet)
}

// Get the command keyword from the first argument.
Expand Down Expand Up @@ -128,9 +130,9 @@ func main() {
parseScopes(flagSet.Args()[1:]))
} else {
// OAuth flow
if (len(flagSet.Args()) < 1) {
fmt.Println("Missing scope for OAuth 2.0")
help()
if len(flagSet.Args()) < 1 {
fmt.Println("Missing scope argument for OAuth 2.0")
help(flagSet)
return
}

Expand All @@ -157,6 +159,6 @@ func main() {
util.Reset()
} else {
// Unknown command, print usage.
help()
help(flagSet)
}
}
47 changes: 26 additions & 21 deletions util/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,19 @@
package util

import (
"log"
"io/ioutil"
"encoding/json"
"io/ioutil"
"log"
"os"
"github.com/google/oauth2l/sgauth"
"path/filepath"
)

const (
cacheFileName = ".oauth2l"
"github.com/google/oauth2l/sgauth"
)

const CacheFileName = ".oauth2l"

var CacheLocation string = filepath.Join(sgauth.GuessUnixHomeDir(), CacheFileName)

// The key struct that used to identify an auth token fetch operation.
type CacheKey struct {
// The JSON credentials content downloaded from Google Cloud Console.
Expand All @@ -40,6 +41,9 @@ type CacheKey struct {
}

func LookupCache(settings *sgauth.Settings) (*sgauth.Token, error) {
if CacheLocation == "" {
return nil, nil
}
var token sgauth.Token
var cache, err = loadCache()
if err != nil {
Expand All @@ -58,6 +62,9 @@ func LookupCache(settings *sgauth.Settings) (*sgauth.Token, error) {
}

func InsertCache(settings *sgauth.Settings, token *sgauth.Token) error {
if CacheLocation == "" {
return nil
}
var cache, err = loadCache()
if err != nil {
return err
Expand All @@ -75,33 +82,36 @@ func InsertCache(settings *sgauth.Settings, token *sgauth.Token) error {
if err != nil {
return err
}
return ioutil.WriteFile(cacheLocation(), data, 0666)
return ioutil.WriteFile(CacheLocation, data, 0666)
}

func ClearCache() error {
if _, err := os.Stat(cacheLocation()); os.IsNotExist(err) {
if CacheLocation == "" {
return nil
}
if _, err := os.Stat(CacheLocation); os.IsNotExist(err) {
// Noop if file does not exist.
return nil
}
return os.Remove(cacheLocation())
return os.Remove(CacheLocation)
}

func loadCache() (map[string][]byte, error) {
if _, err := os.Stat(cacheLocation()); os.IsNotExist(err) {
if _, err := os.Stat(CacheLocation); os.IsNotExist(err) {
// Create the cache file if not existing.
f, err := os.OpenFile(cacheLocation(), os.O_RDONLY|os.O_CREATE, 0666)
f, err := os.OpenFile(CacheLocation, os.O_RDONLY|os.O_CREATE, 0666)
if err != nil {
log.Fatal(err)
return nil, err
}
f.Close()
}
data, err := ioutil.ReadFile(cacheLocation())
data, err := ioutil.ReadFile(CacheLocation)
if err != nil {
log.Fatal(err)
return nil, err
}
m := map[string][]byte{}
m := make(map[string][]byte)
if len(data) > 0 {
err = json.Unmarshal(data, &m)
if err != nil {
Expand All @@ -112,16 +122,11 @@ func loadCache() (map[string][]byte, error) {
return m, nil
}

func cacheLocation() string {
return filepath.Join(sgauth.GuessUnixHomeDir(), cacheFileName)
}

func createKey(settings *sgauth.Settings) CacheKey {
return CacheKey{
CredentialsJSON: settings.CredentialsJSON,
Scope: settings.Scope,
Audience: settings.Audience,
APIKey: settings.APIKey,
Scope: settings.Scope,
Audience: settings.Audience,
APIKey: settings.APIKey,
}
}

0 comments on commit cf46f2e

Please sign in to comment.