Browse Source

change cli option to ask for auth token, save/load it from file in home directory

Alan Shreve 12 years ago
parent
commit
33b6e0c0a3
3 changed files with 65 additions and 6 deletions
  1. 49 0
      src/ngrok/client/auth.go
  2. 13 5
      src/ngrok/client/cli.go
  3. 3 1
      src/ngrok/client/main.go

+ 49 - 0
src/ngrok/client/auth.go

@@ -0,0 +1,49 @@
+package client
+
+import (
+	"io/ioutil"
+	"ngrok/log"
+	"os"
+	"os/user"
+	"path"
+)
+
+/*
+   Functions for reading and writing the auth token from the user's
+   home directory.
+*/
+var (
+	currentAuthToken string
+	authTokenFile    string
+)
+
+func init() {
+	user, err := user.Current()
+	if err != nil {
+		log.Warn("Failed to get user's home directory: %s", err.Error())
+		return
+	}
+
+	authTokenFile = path.Join(user.HomeDir, ".ngrok")
+	tokenBytes, err := ioutil.ReadFile(authTokenFile)
+
+	if err == nil {
+		currentAuthToken = string(tokenBytes)
+	}
+}
+
+func SaveAuthToken(token string) {
+	if token == "" || token == currentAuthToken || authTokenFile == "" {
+		return
+	}
+
+	perms := os.FileMode(0644)
+	err := ioutil.WriteFile(authTokenFile, []byte(token), perms)
+	if err != nil {
+		log.Warn("Failed to write auth token to file %s: %v", authTokenFile, err.Error())
+	}
+}
+
+func LoadAuthToken() string {
+	return currentAuthToken
+}

+ 13 - 5
src/ngrok/client/cli.go

@@ -25,7 +25,7 @@ type Options struct {
 	historySize int
 	webport     int
 	logto       string
-	user        string
+	authtoken   string
 }
 
 func fail(msg string, args ...interface{}) {
@@ -92,11 +92,19 @@ func parseProtocol(proto string) string {
 	panic("unreachable")
 }
 
+func parseAuthToken(token string) string {
+	if token != "" {
+		return token
+	} else {
+		return LoadAuthToken()
+	}
+}
+
 func parseArgs() *Options {
-	user := flag.String(
-		"email",
+	authtoken := flag.String(
+		"authtoken",
 		"",
-		"Email address of your premium ngrok.com account")
+		"Authentication token for identifying a premium ngrok.com account")
 
 	server := flag.String(
 		"server",
@@ -148,6 +156,6 @@ func parseArgs() *Options {
 		protocol:  parseProtocol(*protocol),
 		webport:   *webport,
 		logto:     *logto,
-		user:      *user,
+		authtoken: parseAuthToken(*authtoken),
 	}
 }

+ 3 - 1
src/ngrok/client/main.go

@@ -197,7 +197,7 @@ func control(s *State, ctl *ui.Controller) {
 		ClientId:  s.id,
 		Version:   version.Proto,
 		MmVersion: version.MajorMinor(),
-		User:      s.opts.user,
+		User:      s.opts.authtoken,
 	})
 
 	if err != nil {
@@ -223,6 +223,8 @@ func control(s *State, ctl *ui.Controller) {
 	s.serverVersion = regAck.MmVersion
 	ctl.Update(s)
 
+	SaveAuthToken(s.opts.authtoken)
+
 	// start the heartbeat
 	lastPong := time.Now().UnixNano()
 	go heartbeat(&lastPong, conn)