Skip to content

Commit

Permalink
fix: validate token before save
Browse files Browse the repository at this point in the history
  • Loading branch information
s1ntaxe770r authored and andrew-s committed Jun 5, 2024
1 parent e573f21 commit 973d36d
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
37 changes: 36 additions & 1 deletion commands/auth/init.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
package auth

import (
"context"
"errors"
"fmt"
"os"
"os/user"
"path/filepath"
"regexp"

"github.com/qernal/cli-qernal/charm"
"github.com/qernal/cli-qernal/pkg/client"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"gopkg.in/yaml.v2"
Expand All @@ -33,6 +37,11 @@ var (
return err
}

err = ValidateToken(token)
if err != nil {
return charm.RenderError("token validation failed:", err)
}

return saveConfig(token)
},
}
Expand All @@ -41,10 +50,10 @@ var (
)

func GetQernalToken() (string, error) {

// 1. Check environment variable
if token := os.Getenv("QERNAL_TOKEN"); token != "" {
fmt.Println(charm.SuccessStyle.Render("configuring CLI using environment variable ✅"))

return token, nil
}

Expand Down Expand Up @@ -123,3 +132,29 @@ func validatePermissions(filePath string) error {
}
return nil
}

func ValidateToken(token string) error {

pattern := `^([^@]+)@([^@]+)$`

re := regexp.MustCompile(pattern)

// Check if the token matches the pattern
if !re.MatchString(token) {
return errors.New("invalid token format, expected format is clientid@clientsecret")
}

// Make request with token
ctx := context.Background()
qc, err := client.New(ctx, token)
if err != nil {
return fmt.Errorf("unable to create qernal client with token, %s", err.Error())
}
_, _, err = qc.OrganisationsAPI.OrganisationsList(ctx).Execute()

if err != nil {
return fmt.Errorf("token is invalid, HTTP request filed with: %s", err.Error())
}

return nil
}
2 changes: 1 addition & 1 deletion commands/secrets/encrypt.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ var EncryptCmd = &cobra.Command{

}

qc, err := client.New(ctx, string(token))
qc, err := client.New(ctx, token)

if err != nil {
return charm.RenderError("", err)
Expand Down

0 comments on commit 973d36d

Please sign in to comment.