Skip to content
Open

login #657

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[submodule "proto"]
path = proto
url = https://github.com/cdalar/onctl-proto
2 changes: 2 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ all: build

# Build the binary
build:
git submodule update --init --recursive --remote
buf generate
export CGO_ENABLED=0
$(GO_CMD) mod tidy
$(GO_CMD) build -ldflags="-w -s -X 'github.com/cdalar/onctl/cmd.Version=`git rev-parse HEAD | cut -c1-7`' \
Expand Down
56 changes: 56 additions & 0 deletions cmd/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package cmd

import (
"encoding/json"
"errors"
"fmt"
"io"
"log"
Expand All @@ -20,8 +21,11 @@ import (
"github.com/cdalar/onctl/internal/files"
"github.com/cdalar/onctl/internal/tools"
"github.com/gofrs/uuid/v5"
"github.com/golang-jwt/jwt/v4"
"github.com/manifoldco/promptui"
homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/viper"
"gopkg.in/yaml.v2"
"k8s.io/apimachinery/pkg/util/duration"
)

Expand Down Expand Up @@ -337,3 +341,55 @@ func ProcessDownloadSlice(downloadSlice []string, remote tools.Remote) {
wg.Wait() // Wait for all goroutines to finish
}
}

type CredentialsConfig struct {
AccessToken string `yaml:"access_token"`
}

var ErrTokenExpired = errors.New("access token is expired")

// function to get access token from home directory and validate expiration
func getAccessToken() (string, error) {
home, err := homedir.Dir()
if err != nil {
return "", fmt.Errorf("problem finding home directory: %v", err)
}

configFile := home + "/.onctl/credentials"
content, err := os.ReadFile(configFile)
if err != nil {
return "", fmt.Errorf("problem reading credentials file: %v", err)
}

var creds CredentialsConfig
err = yaml.Unmarshal(content, &creds)
if err != nil {
return "", fmt.Errorf("problem unmarshalling credentials file: %v", err)
}

token := creds.AccessToken

// Parse the JWT token without verifying the signature
parsedToken, _, err := jwt.NewParser().ParseUnverified(token, jwt.MapClaims{})
if err != nil {
return "", fmt.Errorf("problem parsing JWT token: %v", err)
}

// Extract claims and check expiration
claims, ok := parsedToken.Claims.(jwt.MapClaims)
if !ok {
return "", errors.New("invalid JWT claims format")
}

exp, ok := claims["exp"].(float64)
if !ok {
return "", errors.New("expiration claim not found in JWT")
}

// Check if the token is expired
if time.Unix(int64(exp), 0).Before(time.Now()) {
return "", ErrTokenExpired
}

return token, nil
}
121 changes: 121 additions & 0 deletions cmd/login.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
package cmd

import (
"fmt"
"log"
"net/http"
"os"

homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
)

var accessKeyToken string

func init() {
loginCmd.PersistentFlags().StringVar(&accessKeyToken, "token", "", "access token")
}

func createConfigDirIfNotExist() (string, error) {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
log.Fatal("Problem on home directory")
}

okDir := home + "/.onctl"
_, err = os.Stat(okDir)
if os.IsNotExist(err) {
errDir := os.MkdirAll(okDir, 0700)
if errDir != nil {
log.Fatal(err)
return "", err
}
}
return okDir, nil
}

func saveAccessKeyToken(token string) error {

okDir, err := createConfigDirIfNotExist()
if err != nil {
return err
}
configFile := okDir + "/credentials"

// Prepare YAML content
content := fmt.Sprintf("access_token: %q\n", token)

// Write to file with 0600 permissions
file, err := os.OpenFile(configFile, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0600)
if err != nil {
fmt.Println("Problem writing credentials")
return err
}
defer file.Close()

_, err = file.WriteString(content)
if err != nil {
log.Println(err)
return err
}
return nil
}

// Listen for the token on localhost
func waitForTokenOnLocalhost(port string) (string, error) {
var token string
server := &http.Server{Addr: ":" + port}
done := make(chan struct{})

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
token = r.URL.Query().Get("token")
if token != "" {
w.Write([]byte("Login successful! You can close this window."))
close(done)
} else {
w.Write([]byte("No token found."))
}
})

go func() {
_ = server.ListenAndServe()
}()

<-done
server.Close()
return token, nil
}

var loginCmd = &cobra.Command{
Use: "login",
Short: "Login to onctl.io",
Long: `Command line tool to login onctl.io`,
Run: func(cmd *cobra.Command, args []string) {
port := "54123" // choose a free port
// domain := "https://api.onctl.io" // domain for login
domain := "http://localhost:8081" // domain for login
if accessKeyToken != "" {
err := saveAccessKeyToken(accessKeyToken)
if err != nil {
log.Println(err)
}
fmt.Println("Token set")
os.Exit(0)
}
// Add redirect_uri to the login URL
url := domain + "/login"
fmt.Println("Please login through the browser " + url)
openbrowser(url)
token, err := waitForTokenOnLocalhost(port)
if err != nil {
log.Println(err)
}
if token != "" {
saveAccessKeyToken(token)
fmt.Println("Logged in!")
} else {
fmt.Println("Failed to get token.")
}
},
}
3 changes: 3 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,4 +108,7 @@ func init() {
rootCmd.AddCommand(destroyCmd)
rootCmd.AddCommand(sshCmd)
rootCmd.AddCommand(initCmd)
rootCmd.AddCommand(runCmd)
rootCmd.AddCommand(loginCmd)
rootCmd.PersistentFlags().StringVarP(&cloudProvider, "cloud", "c", "", "Cloud Provider to use (aws, hetzner, azure, gcp)")
}
Loading
Loading