| 1 | // |
| 2 | // Copyright (c) SAS Institute Inc. |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | // |
| 16 | |
| 17 | package remotecmd |
| 18 | |
| 19 | import ( |
| 20 | "errors" |
| 21 | "fmt" |
| 22 | "net/http" |
| 23 | "os" |
| 24 | |
| 25 | "github.com/sassoftware/relic/v7/cmdline/shared" |
| 26 | "github.com/sassoftware/relic/v7/config" |
| 27 | |
| 28 | "github.com/spf13/cobra" |
| 29 | ) |
| 30 | |
| 31 | var LoginCmd = &cobra.Command{ |
| 32 | Use: "login", |
| 33 | Short: "Interactively login to the server with single sign-on", |
| 34 | RunE: loginCmd, |
| 35 | } |
| 36 | |
| 37 | func init() { |
| 38 | RemoteCmd.AddCommand(LoginCmd) |
| 39 | LoginCmd.Flags().StringVarP(&argRemoteURL, "url", "u", "", "URL of remote server to register to") |
| 40 | LoginCmd.Flags().BoolVarP(&argForce, "force", "f", false, "Overwrite existing configuration file") |
| 41 | } |
| 42 | |
| 43 | func loginCmd(cmd *cobra.Command, args []string) error { |
| 44 | if argRemoteURL == "" { |
| 45 | return errors.New("--url is required") |
| 46 | } |
| 47 | if shared.ArgConfig == "" { |
| 48 | shared.ArgConfig = config.DefaultConfig() |
| 49 | if shared.ArgConfig == "" { |
| 50 | return errors.New("unable to determine default config location") |
| 51 | } |
| 52 | } |
| 53 | if fileExists(shared.ArgConfig) && !argForce { |
| 54 | fmt.Fprintf(os.Stderr, "Config file %s already exists\n", shared.ArgConfig) |
| 55 | return nil |
| 56 | } |
| 57 | shared.CurrentConfig = &config.Config{Remote: &config.RemoteConfig{ |
| 58 | DirectoryURL: argRemoteURL, |
| 59 | Interactive: true, |
| 60 | }} |
| 61 | // prove auth is working |
| 62 | if _, err := CallRemote("/list_keys", http.MethodGet, nil, nil); err != nil { |
| 63 | return shared.Fail(err) |
| 64 | } |
| 65 | if err := writeConfigObject(shared.ArgConfig, shared.CurrentConfig, false); err != nil { |
| 66 | return shared.Fail(err) |
| 67 | } |
| 68 | return nil |
| 69 | } |