Skip to content
Merged
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 .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ linters:
- path: internal\/tui\/*
linters:
- forbidigo
- path: internal\/account-api\/*
linters:
- forbidigo

formatters:
enable:
Expand Down
2 changes: 0 additions & 2 deletions cmd/account/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"github.com/spf13/cobra"

account_api "github.com/shopware/shopware-cli/internal/account-api"
"github.com/shopware/shopware-cli/internal/config"
)

var accountRootCmd = &cobra.Command{
Expand All @@ -13,7 +12,6 @@ var accountRootCmd = &cobra.Command{
}

type ServiceContainer struct {
Conf config.Config
AccountClient *account_api.Client
}

Expand Down
79 changes: 8 additions & 71 deletions cmd/account/account_login.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,59 +3,28 @@ package account
import (
"fmt"

"charm.land/huh/v2"
"github.com/spf13/cobra"

accountApi "github.com/shopware/shopware-cli/internal/account-api"
"github.com/shopware/shopware-cli/internal/system"
"github.com/shopware/shopware-cli/logging"
"github.com/shopware/shopware-cli/internal/tui"
)

var loginCmd = &cobra.Command{
Use: "login",
Short: "Login into your Shopware Account",
Long: "",
RunE: func(cmd *cobra.Command, _ []string) error {
email := services.Conf.GetAccountEmail()
password := services.Conf.GetAccountPassword()
newCredentials := false
tui.PrintBanner()

if len(email) == 0 || len(password) == 0 {
if !system.IsInteractionEnabled(cmd.Context()) {
return fmt.Errorf("credentials missing and interaction is disabled")
}

var err error
email, password, err = askUserForEmailAndPassword()
if err != nil {
return err
}

newCredentials = true

if err := services.Conf.SetAccountEmail(email); err != nil {
return err
}
if err := services.Conf.SetAccountPassword(password); err != nil {
return err
}
} else {
logging.FromContext(cmd.Context()).Infof("Using existing credentials. Use account:logout to logout")
}

_, err := accountApi.NewApi(cmd.Context(), accountApi.LoginRequest{Email: email, Password: password})
_, err := accountApi.NewApi(cmd.Context())
if err != nil {
return fmt.Errorf("login failed with error: %w", err)
}

if newCredentials {
err := services.Conf.Save()
if err != nil {
return fmt.Errorf("cannot save config: %w", err)
}
return err
}

logging.FromContext(cmd.Context()).Infof("Login successful. You can now use all account commands")
fmt.Println()
fmt.Println(tui.GreenText.Render(" Login successful!"))
fmt.Println(tui.DimText.Render(" To logout, run: shopware-cli account logout"))
fmt.Println()

return nil
},
Expand All @@ -64,35 +33,3 @@ var loginCmd = &cobra.Command{
func init() {
accountRootCmd.AddCommand(loginCmd)
}

func askUserForEmailAndPassword() (string, string, error) {
var email, password string

form := huh.NewForm(
huh.NewGroup(
huh.NewInput().
Title("Email").
Validate(emptyValidator).
Value(&email),
huh.NewInput().
Title("Password").
EchoMode(huh.EchoModePassword).
Validate(emptyValidator).
Value(&password),
),
)

if err := form.Run(); err != nil {
return "", "", fmt.Errorf("prompt failed %w", err)
}

return email, password, nil
}

func emptyValidator(s string) error {
if len(s) == 0 {
return fmt.Errorf("this cannot be empty")
}

return nil
}
7 changes: 0 additions & 7 deletions cmd/account/account_logout.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,6 @@ var logoutCmd = &cobra.Command{
return fmt.Errorf("cannot invalidate token cache: %w", err)
}

_ = services.Conf.SetAccountEmail("")
_ = services.Conf.SetAccountPassword("")

if err := services.Conf.Save(); err != nil {
return fmt.Errorf("cannot write config: %w", err)
}

logging.FromContext(cmd.Context()).Infof("You have been logged out")

return nil
Expand Down
20 changes: 2 additions & 18 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,11 @@ import (
"github.com/shopware/shopware-cli/cmd/extension"
"github.com/shopware/shopware-cli/cmd/project"
accountApi "github.com/shopware/shopware-cli/internal/account-api"
"github.com/shopware/shopware-cli/internal/config"
"github.com/shopware/shopware-cli/internal/system"
"github.com/shopware/shopware-cli/logging"
)

var (
cfgFile string
version = "dev"
)
var version = "dev"

var rootCmd = &cobra.Command{
Use: "shopware-cli",
Expand All @@ -47,38 +43,26 @@ func Execute(ctx context.Context) {
func init() {
rootCmd.SilenceErrors = true

cobra.OnInitialize(func() {
_ = config.InitConfig(cfgFile)
})

cobra.OnFinalize(func() {
_ = system.CloseCaches()
})

rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.shopware-cli.yaml)")
rootCmd.PersistentFlags().Bool("verbose", false, "show debug output")
rootCmd.PersistentFlags().BoolP("no-interaction", "n", false, "do not ask any interactive questions")

project.Register(rootCmd)
extension.Register(rootCmd)
account.Register(rootCmd, func(commandName string) (*account.ServiceContainer, error) {
err := config.InitConfig(cfgFile)
if err != nil {
return nil, err
}
conf := config.Config{}
if commandName == "login" || commandName == "logout" {
return &account.ServiceContainer{
Conf: conf,
AccountClient: nil,
}, nil
}
client, err := accountApi.NewApi(rootCmd.Context(), conf)
client, err := accountApi.NewApi(rootCmd.Context())
if err != nil {
return nil, err
}
return &account.ServiceContainer{
Conf: conf,
AccountClient: client,
}, nil
})
Expand Down
1 change: 0 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ require (
github.com/DATA-DOG/go-sqlmock v1.5.2
github.com/NYTimes/gziphandler v1.1.1
github.com/bep/godartsass/v2 v2.5.0
github.com/caarlos0/env/v9 v9.0.0
github.com/cespare/xxhash/v2 v2.3.0
github.com/evanw/esbuild v0.27.3
github.com/go-sql-driver/mysql v1.9.3
Expand Down
2 changes: 0 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,6 @@ github.com/bep/godartsass/v2 v2.5.0 h1:tKRvwVdyjCIr48qgtLa4gHEdtRkPF8H1OeEhJAEv7
github.com/bep/godartsass/v2 v2.5.0/go.mod h1:rjsi1YSXAl/UbsGL85RLDEjRKdIKUlMQHr6ChUNYOFU=
github.com/buger/jsonparser v1.1.1 h1:2PnMjfWD7wBILjqQbt530v576A/cAbQvEW9gGIpYMUs=
github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0=
github.com/caarlos0/env/v9 v9.0.0 h1:SI6JNsOA+y5gj9njpgybykATIylrRMklbs5ch6wO6pc=
github.com/caarlos0/env/v9 v9.0.0/go.mod h1:ye5mlCVMYh6tZ+vCgrs/B95sj88cg5Tlnc0XIzgZ020=
github.com/catppuccin/go v0.3.0 h1:d+0/YicIq+hSTo5oPuRi5kOpqkVA5tAsU6dNhvRu+aY=
github.com/catppuccin/go v0.3.0/go.mod h1:8IHJuMGaUUjQM82qBrGNBv7LFq6JI3NnQCF6MOlZjpc=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
Expand Down
71 changes: 40 additions & 31 deletions internal/account-api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ import (
"path/filepath"
"time"

"golang.org/x/oauth2"

"github.com/shopware/shopware-cli/internal/system"
"github.com/shopware/shopware-cli/logging"
)

Expand All @@ -20,30 +23,39 @@ func SetUserAgent(userAgent string) {
}

type Client struct {
Token token `json:"token"`
Token *oauth2.Token `json:"token,omitempty"`
LegacyToken *legacyToken `json:"legacyToken,omitempty"`
}

func (c *Client) NewAuthenticatedRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) {
logging.FromContext(ctx).Debugf("%s: %s", method, path)
r, err := http.NewRequestWithContext(ctx, method, path, body)
if err != nil {
return nil, err
}

r.Header.Set("content-type", "application/json")
r.Header.Set("accept", "application/json")
r.Header.Set("x-shopware-token", c.Token.Token)

if c.Token != nil {
c.Token.SetAuthHeader(r)
} else if c.LegacyToken != nil {
r.Header.Set("x-shopware-token", c.LegacyToken.Token)
}

r.Header.Set("user-agent", httpUserAgent)

return r, nil
}

func (*Client) doRequest(request *http.Request) ([]byte, error) {
start := time.Now()
resp, err := http.DefaultClient.Do(request)
if err != nil {
return nil, err
}

logging.FromContext(request.Context()).Debugf("%s: %s, took: %s", request.Method, request.URL.String(), time.Since(start))

data, err := io.ReadAll(resp.Body)
if err != nil {
_ = resp.Body.Close()
Expand All @@ -63,37 +75,40 @@ func (*Client) doRequest(request *http.Request) ([]byte, error) {
}

func (c *Client) isTokenValid() bool {
loc, err := time.LoadLocation(c.Token.Expire.Timezone)
if err != nil {
return false
if c.Token != nil {
return time.Until(c.Token.Expiry) > time.Minute
}

expire, err := time.ParseInLocation("2006-01-02 15:04:05.000000", c.Token.Expire.Date, loc)
if err != nil {
return false
if c.LegacyToken != nil {
loc, err := time.LoadLocation(c.LegacyToken.Expire.Timezone)
if err != nil {
return false
}

expire, err := time.ParseInLocation("2006-01-02 15:04:05.000000", c.LegacyToken.Expire.Date, loc)
if err != nil {
return false
}

return expire.UTC().Sub(time.Now().UTC()).Seconds() > 60
}

// When it will be expire in the next minute. Respond with false
return expire.UTC().Sub(time.Now().UTC()).Seconds() > 60
return false
}

const CacheFileName = "shopware-api-client-token.json"

func getApiTokenCacheFilePath() (string, error) {
cacheDir, err := os.UserCacheDir()
if err != nil {
return "", err
func getCacheFileName() string {
if isStaging() {
return "shopware-api-token-staging.json"
}
return "shopware-api-token.json"
}

shopwareCacheDir := filepath.Join(cacheDir, "shopware-cli")
return filepath.Join(shopwareCacheDir, CacheFileName), nil
func getApiTokenCacheFilePath() string {
return filepath.Join(system.GetShopwareCliCacheDir(), getCacheFileName())
}

func createApiFromTokenCache(ctx context.Context) (*Client, error) {
tokenFilePath, err := getApiTokenCacheFilePath()
if err != nil {
return nil, err
}
tokenFilePath := getApiTokenCacheFilePath()

if _, err := os.Stat(tokenFilePath); os.IsNotExist(err) {
return nil, err
Expand All @@ -120,10 +135,7 @@ func createApiFromTokenCache(ctx context.Context) (*Client, error) {
}

func saveApiTokenToTokenCache(client *Client) error {
tokenFilePath, err := getApiTokenCacheFilePath()
if err != nil {
return err
}
tokenFilePath := getApiTokenCacheFilePath()

content, err := json.Marshal(client)
if err != nil {
Expand All @@ -147,10 +159,7 @@ func saveApiTokenToTokenCache(client *Client) error {
}

func InvalidateTokenCache() error {
tokenFilePath, err := getApiTokenCacheFilePath()
if err != nil {
return err
}
tokenFilePath := getApiTokenCacheFilePath()

if _, err := os.Stat(tokenFilePath); os.IsNotExist(err) {
return nil
Expand Down
Loading
Loading