Skip to content

Commit 4ab13dc

Browse files
Harsh4902lbroudoux
andauthored
Feat: Initiate a microcksClient using ClientOpts in root, login and import commnad (#161)
* fixes #154 Feat: Add Login command to perform login and keep credentials in config file to perform further operations Signed-off-by: Harsh4902 <[email protected]> * Adds suport for token refreshing mechanism on token expiry Signed-off-by: Harsh4902 <[email protected]> * fixes #160 feat: Implements GlobalClientOpts in root, login and import commands Signed-off-by: Harsh4902 <[email protected]> --------- Signed-off-by: Harsh4902 <[email protected]> Co-authored-by: Laurent Broudoux <[email protected]>
1 parent b82077c commit 4ab13dc

File tree

4 files changed

+77
-80
lines changed

4 files changed

+77
-80
lines changed

cmd/cmd.go

Lines changed: 33 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -16,37 +16,44 @@
1616
package cmd
1717

1818
import (
19-
"fmt"
20-
"os"
21-
19+
"github.com/microcks/microcks-cli/pkg/config"
20+
"github.com/microcks/microcks-cli/pkg/connectors"
21+
"github.com/microcks/microcks-cli/pkg/errors"
2222
"github.com/spf13/cobra"
2323
)
2424

25-
var rootCmd = &cobra.Command{
26-
Use: "microcks",
27-
Short: "A CLI tool for Microcks",
28-
SilenceUsage: true,
29-
Run: func(cmd *cobra.Command, args []string) {
30-
cmd.HelpFunc()(cmd, args)
31-
},
32-
CompletionOptions: cobra.CompletionOptions{
33-
HiddenDefaultCmd: true,
34-
},
35-
}
25+
func NewCommad() *cobra.Command {
26+
27+
var clientOpts connectors.ClientOptions
3628

37-
func Execute() {
38-
if err := rootCmd.Execute(); err != nil {
39-
fmt.Fprintln(os.Stderr, err)
29+
command := &cobra.Command{
30+
Use: "microcks",
31+
Short: "A CLI tool for Microcks",
32+
SilenceUsage: true,
33+
Run: func(cmd *cobra.Command, args []string) {
34+
cmd.HelpFunc()(cmd, args)
35+
},
36+
CompletionOptions: cobra.CompletionOptions{
37+
HiddenDefaultCmd: true,
38+
},
4039
}
41-
}
4240

4341
func init() {
44-
rootCmd.AddCommand(NewImportCommand())
45-
rootCmd.AddCommand(NewVersionCommand())
46-
rootCmd.AddCommand(NewTestCommand())
47-
rootCmd.AddCommand(NewImportURLCommand())
48-
rootCmd.AddCommand(NewStartCommand())
49-
rootCmd.AddCommand(NewStopCommand())
50-
rootCmd.AddCommand(NewContextCommand())
51-
rootCmd.AddCommand(NewLoginCommand())
42+
command.AddCommand(NewImportCommand(&clientOpts))
43+
command.AddCommand(NewVersionCommand())
44+
command.AddCommand(NewTestCommand())
45+
command.AddCommand(NewImportURLCommand())
46+
command.AddCommand(NewStartCommand())
47+
command.AddCommand(NewStopCommand())
48+
command.AddCommand(NewContextCommand())
49+
command.AddCommand(NewLoginCommand(&clientOpts))
50+
51+
defaultLocalConfigPath, err := config.DefaultLocalConfigPath()
52+
errors.CheckError(err)
53+
command.PersistentFlags().StringVar(&clientOpts.ConfigPath, "config", defaultLocalConfigPath, "Path to Microcks config")
54+
command.PersistentFlags().StringVar(&clientOpts.Context, "microcks-context", "", "Name of the Microcks context to use")
55+
command.PersistentFlags().BoolVar(&clientOpts.Verbose, "verbose", false, "Produce dumps of HTTP exchanges")
56+
command.PersistentFlags().BoolVar(&clientOpts.InsecureTLS, "insecure-tls", false, "Whether to accept insecure HTTPS connection")
57+
command.PersistentFlags().StringVar(&clientOpts.CaCertPaths, "caCerts", "", "Comma separated paths of CRT files to add to Root CAs")
58+
return command
5259
}

cmd/import.go

Lines changed: 15 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -26,15 +26,7 @@ import (
2626
"github.com/spf13/cobra"
2727
)
2828

29-
func NewImportCommand() *cobra.Command {
30-
var (
31-
microcksURL string
32-
keycloakClientID string
33-
keycloakClientSecret string
34-
insecureTLS bool
35-
caCertPaths string
36-
verbose bool
37-
)
29+
func NewImportCommand(globalClientOpts *connectors.ClientOptions) *cobra.Command {
3830
var importCmd = &cobra.Command{
3931
Use: "import",
4032
Short: "import API artifacts on Microcks server",
@@ -48,40 +40,26 @@ func NewImportCommand() *cobra.Command {
4840

4941
specificationFiles := args[0]
5042

51-
// Collect optional HTTPS transport flags.
52-
if insecureTLS {
53-
config.InsecureTLS = true
54-
}
55-
if len(caCertPaths) > 0 {
56-
config.CaCertPaths = caCertPaths
57-
}
58-
if verbose {
59-
config.Verbose = true
60-
}
43+
config.InsecureTLS = globalClientOpts.InsecureTLS
44+
config.CaCertPaths = globalClientOpts.CaCertPaths
45+
config.Verbose = globalClientOpts.Verbose
6146

62-
// Now we seems to be good ...
63-
// First - retrieve the Keycloak URL from Microcks configuration.
64-
mc := connectors.NewMicrocksClient(microcksURL)
65-
keycloakURL, err := mc.GetKeycloakURL()
47+
localConfig, err := config.ReadLocalConfig(globalClientOpts.ConfigPath)
6648
if err != nil {
67-
fmt.Printf("Got error when invoking Microcks client retrieving config: %s", err)
68-
os.Exit(1)
49+
fmt.Println(err)
50+
return
6951
}
7052

71-
var oauthToken string = "unauthentifed-token"
72-
if keycloakURL != "null" {
73-
// If Keycloak is enabled, retrieve an OAuth token using Keycloak Client.
74-
kc := connectors.NewKeycloakClient(keycloakURL, keycloakClientID, keycloakClientSecret)
75-
76-
oauthToken, err = kc.ConnectAndGetToken()
77-
if err != nil {
78-
fmt.Printf("Got error when invoking Keycloack client: %s", err)
79-
os.Exit(1)
80-
}
53+
if localConfig == nil {
54+
fmt.Println("Please login to perform opertion...")
55+
return
8156
}
8257

83-
// Then - for each specificationFile, upload the artifact on Microcks Server.
84-
mc.SetOAuthToken(oauthToken)
58+
mc, err := connectors.NewClient(*globalClientOpts)
59+
if err != nil {
60+
fmt.Printf("error %v", err)
61+
return
62+
}
8563

8664
sepSpecificationFiles := strings.Split(specificationFiles, ",")
8765
for _, f := range sepSpecificationFiles {
@@ -108,17 +86,6 @@ func NewImportCommand() *cobra.Command {
10886

10987
},
11088
}
111-
importCmd.Flags().StringVar(&microcksURL, "microcksURL", "", "Microcks API URL")
112-
importCmd.Flags().StringVar(&keycloakClientID, "keycloakClientId", "", "Keycloak Realm Service Account ClientId")
113-
importCmd.Flags().StringVar(&keycloakClientSecret, "keycloakClientSecret", "", "Keycloak Realm Service Account ClientSecret")
114-
importCmd.Flags().BoolVar(&insecureTLS, "insecure", false, "Whether to accept insecure HTTPS connection")
115-
importCmd.Flags().StringVar(&caCertPaths, "caCerts", "", "Comma separated paths of CRT files to add to Root CAs")
116-
importCmd.Flags().BoolVar(&verbose, "verbose", false, "Produce dumps of HTTP exchanges")
117-
118-
//Marking flags 'required'
119-
importCmd.MarkFlagRequired("microcksURL")
120-
importCmd.MarkFlagRequired("keycloakClientId")
121-
importCmd.MarkFlagRequired("keycloakClientSecret")
12289

12390
return importCmd
12491
}

cmd/login.go

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ import (
2626
"golang.org/x/term"
2727
)
2828

29-
func NewLoginCommand() *cobra.Command {
29+
func NewLoginCommand(globalClientOpts *connectors.ClientOptions) *cobra.Command {
3030
var (
3131
ctxName string
3232
username string
@@ -82,6 +82,13 @@ microcks login http://localhost:8080 --sso --sso-launch-browser=false
8282
var authToken = ""
8383
var refreshToken = ""
8484

85+
//Initialze Auth struct
86+
authCfg := config.Auth{
87+
Server: server,
88+
ClientId: "",
89+
ClientSecret: "",
90+
}
91+
8592
configFile, err := config.DefaultLocalConfigPath()
8693
errors.CheckError(err)
8794
localConfig, err := config.ReadLocalConfig(configFile)
@@ -110,13 +117,16 @@ microcks login http://localhost:8080 --sso --sso-launch-browser=false
110117
}
111118
//Perform login and retrive tokens
112119
authToken, refreshToken = passwordLogin(keycloakUrl, clientID, clientSecret, username, password)
120+
authCfg.ClientId = clientID
121+
authCfg.ClientSecret = clientSecret
113122
} else {
114123
httpClient := mc.HttpClient()
115124
ctx = oidc.ClientContext(ctx, httpClient)
116125
kc := connectors.NewKeycloakClient(keycloakUrl, "", "")
117126
oauth2conf, err := kc.GetOIDCConfig()
118127
errors.CheckError(err)
119128
authToken, refreshToken = oauth2login(ctx, ssoProt, oauth2conf, ssoLaunchBrowser)
129+
authCfg.ClientId = "microcks-app-js"
120130
}
121131

122132
parser := jwt.NewParser(jwt.WithoutClaimsValidation())
@@ -137,6 +147,8 @@ microcks login http://localhost:8080 --sso --sso-launch-browser=false
137147
})
138148
}
139149

150+
localConfig.UpserAuth(authCfg)
151+
140152
localConfig.UpsertUser(config.User{
141153
Name: server,
142154
AuthToken: authToken,
@@ -203,6 +215,8 @@ func oauth2login(
203215
// Authorization redirect callback from OAuth2 auth flow.
204216
// Handles both implicit and authorization code flow
205217
callbackHandler := func(w http.ResponseWriter, r *http.Request) {
218+
log.Printf("Callback: %s\n", r.URL)
219+
206220
if formErr := r.FormValue("error"); formErr != "" {
207221
handleErr(w, fmt.Sprintf("%s: %s", formErr, r.FormValue("error_description")))
208222
return
@@ -262,6 +276,7 @@ func oauth2login(
262276
time.Sleep(1 * time.Second)
263277
ssoAuthFlow(url, ssoLaunchBrowser)
264278
go func() {
279+
log.Printf("Listen: %s\n", srv.Addr)
265280
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
266281
log.Fatalf("Temporary HTTP server failed: %s", err)
267282
}
@@ -270,21 +285,22 @@ func oauth2login(
270285
if errMsg != "" {
271286
log.Fatal(errMsg)
272287
}
273-
288+
fmt.Printf("Authentication successful\n")
274289
ctx, cancel := context.WithTimeout(ctx, 1*time.Second)
275290
defer cancel()
276291
_ = srv.Shutdown(ctx)
277-
292+
log.Printf("Token: %s\n", tokenString)
293+
log.Printf("Refresh Token: %s\n", refreshToken)
278294
return tokenString, refreshToken
279295
}
280296

281297
func ssoAuthFlow(url string, ssoLaunchBrowser bool) {
282298
if ssoLaunchBrowser {
283-
log.Printf("Opening system default browser for authentication\n")
299+
fmt.Printf("Opening system default browser for authentication\n")
284300
err := open.Start(url)
285301
errors.CheckError(err)
286302
} else {
287-
log.Printf("To authenticate, copy-and-paste the following URL into your preferred browser: %s\n", url)
303+
fmt.Printf("To authenticate, copy-and-paste the following URL into your preferred browser: %s\n", url)
288304
}
289305
}
290306

main.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,16 @@
11
package main
22

33
import (
4+
"fmt"
5+
"os"
6+
47
"github.com/microcks/microcks-cli/cmd"
58
)
69

710
func main() {
8-
cmd.Execute()
11+
command := cmd.NewCommad()
12+
if err := command.Execute(); err != nil {
13+
fmt.Fprintln(os.Stderr, err)
14+
os.Exit(1)
15+
}
916
}

0 commit comments

Comments
 (0)