-
Notifications
You must be signed in to change notification settings - Fork 17
feat(account): support configuring credentials with browser login #375
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
kangasta
wants to merge
4
commits into
main
Choose a base branch
from
feat/account-login
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
c410d10
feat(account): add login command for saving token to system keyring
kangasta 1646e59
chore(account): mark login command as experimental
kangasta 18ea14d
feat(account): support configuring credentials with browser login
kangasta ad22c5c
refactor(account): use fetch instead of redirects to save token
kangasta File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| package account | ||
|
|
||
| import ( | ||
| "bufio" | ||
| "fmt" | ||
| "strings" | ||
|
|
||
| "github.com/UpCloudLtd/progress/messages" | ||
| "github.com/UpCloudLtd/upcloud-cli/v3/internal/commands" | ||
| "github.com/UpCloudLtd/upcloud-cli/v3/internal/commands/account/tokenreceiver" | ||
| "github.com/UpCloudLtd/upcloud-cli/v3/internal/config" | ||
| "github.com/UpCloudLtd/upcloud-cli/v3/internal/output" | ||
| "github.com/spf13/pflag" | ||
| ) | ||
|
|
||
| // LoginCommand creates the "account login" command | ||
| func LoginCommand() commands.Command { | ||
| return &loginCommand{ | ||
| BaseCommand: commands.New( | ||
| "login", | ||
| "Configure an authentication token to the system keyring (EXPERIMENTAL) ", | ||
| "upctl account login --with-token", | ||
| ), | ||
| } | ||
| } | ||
|
|
||
| type loginCommand struct { | ||
| *commands.BaseCommand | ||
|
|
||
| withToken config.OptionalBoolean | ||
| } | ||
|
|
||
| // InitCommand implements Command.InitCommand | ||
| func (s *loginCommand) InitCommand() { | ||
| fs := &pflag.FlagSet{} | ||
| config.AddToggleFlag(fs, &s.withToken, "with-token", false, "Read token from standard input.") | ||
| s.AddFlags(fs) | ||
| } | ||
|
|
||
| // DoesNotUseServices implements commands.OfflineCommand as this command does not use services | ||
| func (s *loginCommand) DoesNotUseServices() {} | ||
|
|
||
| // ExecuteWithoutArguments implements commands.NoArgumentCommand | ||
| func (s *loginCommand) ExecuteWithoutArguments(exec commands.Executor) (output.Output, error) { | ||
| if s.withToken.Value() { | ||
| return s.executeWithToken(exec) | ||
| } | ||
|
|
||
| return s.execute(exec) | ||
| } | ||
|
|
||
| func (s *loginCommand) execute(exec commands.Executor) (output.Output, error) { | ||
| msg := "Waiting to receive token from browser." | ||
| exec.PushProgressStarted(msg) | ||
|
|
||
| receiver := tokenreceiver.New() | ||
| err := receiver.Start() | ||
| if err != nil { | ||
| return commands.HandleError(exec, msg, err) | ||
| } | ||
|
|
||
| err = receiver.OpenBrowser() | ||
| if err != nil { | ||
| url := receiver.GetLoginURL() | ||
| exec.PushProgressUpdate(messages.Update{ | ||
| Message: "Failed to open browser.", | ||
| Status: messages.MessageStatusError, | ||
| Details: fmt.Sprintf("Please open a browser and navigate to %s to continue with the login.", url), | ||
| }) | ||
| } | ||
|
|
||
| token, err := receiver.Wait(exec.Context()) | ||
| if err != nil { | ||
| return commands.HandleError(exec, msg, err) | ||
| } | ||
|
|
||
| exec.PushProgressUpdate(messages.Update{ | ||
| Key: msg, | ||
| Message: "Saving created token to the system keyring.", | ||
| }) | ||
|
|
||
| err = config.SaveTokenToKeyring(token) | ||
| if err != nil { | ||
| return commands.HandleError(exec, msg, fmt.Errorf("failed to save token to keyring: %w", err)) | ||
| } | ||
|
|
||
| exec.PushProgressSuccess(msg) | ||
kangasta marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| return output.None{}, nil | ||
|
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should maybe output the token if saving to keyring fails 🤔 |
||
| } | ||
|
|
||
| func (s *loginCommand) executeWithToken(exec commands.Executor) (output.Output, error) { | ||
| in := bufio.NewReader(s.Cobra().InOrStdin()) | ||
| token, err := in.ReadString('\n') | ||
| if err != nil { | ||
| return nil, fmt.Errorf("failed to read token from standard input: %w", err) | ||
| } | ||
|
|
||
| msg := "Saving provided token to the system keyring." | ||
| exec.PushProgressStarted(msg) | ||
| err = config.SaveTokenToKeyring(strings.TrimSpace(token)) | ||
| if err != nil { | ||
| return commands.HandleError(exec, msg, err) | ||
| } | ||
|
|
||
| exec.PushProgressSuccess(msg) | ||
|
|
||
| return output.None{}, nil | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| package tokenreceiver | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "net" | ||
| "net/http" | ||
| "time" | ||
|
|
||
| "github.com/cli/browser" | ||
| "github.com/rs/cors" | ||
| ) | ||
|
|
||
| type ReceiverServer struct { | ||
| server *http.Server | ||
| token string | ||
| port string | ||
| } | ||
|
|
||
| func New() *ReceiverServer { | ||
| return &ReceiverServer{} | ||
| } | ||
|
|
||
| func getPort(listener net.Listener) string { | ||
| _, port, _ := net.SplitHostPort(listener.Addr().String()) | ||
| return port | ||
| } | ||
|
|
||
| func getURL(target string) string { | ||
| return fmt.Sprintf("http://localhost:3000/account/upctl-login/%s", target) | ||
| } | ||
|
|
||
| func (s *ReceiverServer) GetLoginURL() string { | ||
| return getURL(s.port) | ||
| } | ||
|
|
||
| func (s *ReceiverServer) Start() error { | ||
| mux := http.NewServeMux() | ||
| mux.HandleFunc("GET /ping", func(w http.ResponseWriter, _ *http.Request) { | ||
| w.WriteHeader(http.StatusNoContent) | ||
| }) | ||
| mux.HandleFunc("POST /callback", func(w http.ResponseWriter, req *http.Request) { | ||
| token := req.URL.Query().Get("token") | ||
| if token == "" { | ||
| w.WriteHeader(http.StatusBadRequest) | ||
| return | ||
| } | ||
| s.token = token | ||
| w.WriteHeader(http.StatusNoContent) | ||
| }) | ||
|
|
||
| handler := cors.Default().Handler(mux) | ||
| listener, err := net.Listen("tcp", "127.0.0.1:0") | ||
| if err != nil { | ||
| return fmt.Errorf("failed to create receiver server: %w", err) | ||
| } | ||
|
|
||
| go func() { | ||
| defer listener.Close() | ||
| s.server = &http.Server{ | ||
| Handler: handler, | ||
| ReadHeaderTimeout: time.Second, | ||
| } | ||
| _ = s.server.Serve(listener) | ||
| }() | ||
| s.port = getPort(listener) | ||
| return nil | ||
| } | ||
|
|
||
| func (s *ReceiverServer) OpenBrowser() error { | ||
| return browser.OpenURL(s.GetLoginURL()) | ||
| } | ||
|
|
||
| func (s *ReceiverServer) Wait(ctx context.Context) (string, error) { | ||
| ticker := time.NewTicker(time.Second * 2) | ||
| defer ticker.Stop() | ||
|
|
||
| for { | ||
| select { | ||
| case <-ctx.Done(): | ||
| _ = s.server.Shutdown(context.TODO()) | ||
| return "", ctx.Err() | ||
| case <-ticker.C: | ||
| if s.token != "" { | ||
| _ = s.server.Shutdown(context.TODO()) | ||
| return s.token, nil | ||
| } | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Do we want to use config file as fallback? I guess the file should be generic to be able to use it also with e.g. Terraform provider 🤔