-
Notifications
You must be signed in to change notification settings - Fork 69
refactor: login cmd #1268
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
Merged
+314
−152
Merged
refactor: login cmd #1268
Changes from all commits
Commits
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -6,10 +6,6 @@ import ( | |
| "fmt" | ||
| "io" | ||
| "os" | ||
| "os/exec" | ||
| "runtime" | ||
| "strings" | ||
| "time" | ||
|
|
||
| "github.com/sourcegraph/src-cli/internal/api" | ||
| "github.com/sourcegraph/src-cli/internal/cmderrors" | ||
|
|
@@ -69,13 +65,13 @@ Examples: | |
| client := cfg.apiClient(apiFlags, io.Discard) | ||
|
|
||
| return loginCmd(context.Background(), loginParams{ | ||
| cfg: cfg, | ||
| client: client, | ||
| endpoint: endpoint, | ||
| out: os.Stdout, | ||
| useOAuth: *useOAuth, | ||
| apiFlags: apiFlags, | ||
| deviceFlowClient: oauth.NewClient(oauth.DefaultClientID), | ||
| cfg: cfg, | ||
| client: client, | ||
| endpoint: endpoint, | ||
| out: os.Stdout, | ||
| useOAuth: *useOAuth, | ||
| apiFlags: apiFlags, | ||
| oauthClient: oauth.NewClient(oauth.DefaultClientID), | ||
| }) | ||
| } | ||
|
|
||
|
|
@@ -87,161 +83,80 @@ Examples: | |
| } | ||
|
|
||
| type loginParams struct { | ||
| cfg *config | ||
| client api.Client | ||
| endpoint string | ||
| out io.Writer | ||
| useOAuth bool | ||
| apiFlags *api.Flags | ||
| deviceFlowClient oauth.Client | ||
| cfg *config | ||
| client api.Client | ||
| endpoint string | ||
| out io.Writer | ||
| useOAuth bool | ||
| apiFlags *api.Flags | ||
| oauthClient oauth.Client | ||
| } | ||
|
|
||
| func loginCmd(ctx context.Context, p loginParams) error { | ||
| endpointArg := cleanEndpoint(p.endpoint) | ||
| cfg := p.cfg | ||
| client := p.client | ||
| out := p.out | ||
|
|
||
| printProblem := func(problem string) { | ||
| fmt.Fprintf(out, "❌ Problem: %s\n", problem) | ||
| } | ||
|
|
||
| createAccessTokenMessage := fmt.Sprintf("\n"+`🛠 To fix: Create an access token by going to %s/user/settings/tokens, then set the following environment variables in your terminal: | ||
| type loginFlow func(context.Context, loginParams) error | ||
|
|
||
| export SRC_ENDPOINT=%s | ||
| export SRC_ACCESS_TOKEN=(your access token) | ||
| type loginFlowKind int | ||
|
|
||
| To verify that it's working, run the login command again. | ||
|
|
||
| Alternatively, you can try logging in using OAuth by running: src login --oauth %s | ||
| `, endpointArg, endpointArg, endpointArg) | ||
| const ( | ||
| loginFlowOAuth loginFlowKind = iota | ||
| loginFlowMissingAuth | ||
| loginFlowEndpointConflict | ||
| loginFlowValidate | ||
| ) | ||
|
|
||
| if cfg.ConfigFilePath != "" { | ||
| fmt.Fprintln(out) | ||
| fmt.Fprintf(out, "⚠️ Warning: Configuring src with a JSON file is deprecated. Please migrate to using the env vars SRC_ENDPOINT, SRC_ACCESS_TOKEN, and SRC_PROXY instead, and then remove %s. See https://github.com/sourcegraph/src-cli#readme for more information.\n", cfg.ConfigFilePath) | ||
| } | ||
| var loadStoredOAuthToken = oauth.LoadToken | ||
|
|
||
| noToken := cfg.AccessToken == "" | ||
| endpointConflict := endpointArg != cfg.Endpoint | ||
| if !p.useOAuth && (noToken || endpointConflict) { | ||
| fmt.Fprintln(out) | ||
| switch { | ||
| case noToken: | ||
| printProblem("No access token is configured.") | ||
| case endpointConflict: | ||
| printProblem(fmt.Sprintf("The configured endpoint is %s, not %s.", cfg.Endpoint, endpointArg)) | ||
| } | ||
| fmt.Fprintln(out, createAccessTokenMessage) | ||
| return cmderrors.ExitCode1 | ||
| func loginCmd(ctx context.Context, p loginParams) error { | ||
| if p.cfg.ConfigFilePath != "" { | ||
| fmt.Fprintln(p.out) | ||
| fmt.Fprintf(p.out, "⚠️ Warning: Configuring src with a JSON file is deprecated. Please migrate to using the env vars SRC_ENDPOINT, SRC_ACCESS_TOKEN, and SRC_PROXY instead, and then remove %s. See https://github.com/sourcegraph/src-cli#readme for more information.\n", p.cfg.ConfigFilePath) | ||
| } | ||
|
|
||
| if p.useOAuth { | ||
|
Contributor
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. moved to |
||
| token, err := runOAuthDeviceFlow(ctx, endpointArg, out, p.deviceFlowClient) | ||
| if err != nil { | ||
| printProblem(fmt.Sprintf("OAuth Device flow authentication failed: %s", err)) | ||
| fmt.Fprintln(out, createAccessTokenMessage) | ||
| return cmderrors.ExitCode1 | ||
| } | ||
|
|
||
| if err := oauth.StoreToken(ctx, token); err != nil { | ||
| fmt.Fprintln(out) | ||
| fmt.Fprintf(out, "⚠️ Warning: Failed to store token in keyring store: %q. Continuing with this session only.\n", err) | ||
| } | ||
| _, flow := selectLoginFlow(ctx, p) | ||
| return flow(ctx, p) | ||
| } | ||
|
|
||
| client = api.NewClient(api.ClientOpts{ | ||
| Endpoint: cfg.Endpoint, | ||
| AdditionalHeaders: cfg.AdditionalHeaders, | ||
| Flags: p.apiFlags, | ||
| Out: out, | ||
| ProxyURL: cfg.ProxyURL, | ||
| ProxyPath: cfg.ProxyPath, | ||
| OAuthToken: token, | ||
| }) | ||
| } | ||
| // selectLoginFlow decides what login flow to run based on flags and config. | ||
| func selectLoginFlow(ctx context.Context, p loginParams) (loginFlowKind, loginFlow) { | ||
| endpointArg := cleanEndpoint(p.endpoint) | ||
|
|
||
| // See if the user is already authenticated. | ||
| query := `query CurrentUser { currentUser { username } }` | ||
|
Contributor
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. moved to |
||
| var result struct { | ||
| CurrentUser *struct{ Username string } | ||
| } | ||
| if _, err := client.NewRequest(query, nil).Do(ctx, &result); err != nil { | ||
| if strings.HasPrefix(err.Error(), "error: 401 Unauthorized") || strings.HasPrefix(err.Error(), "error: 403 Forbidden") { | ||
| printProblem("Invalid access token.") | ||
| } else { | ||
| printProblem(fmt.Sprintf("Error communicating with %s: %s", endpointArg, err)) | ||
| } | ||
| fmt.Fprintln(out, createAccessTokenMessage) | ||
| fmt.Fprintln(out, " (If you need to supply custom HTTP request headers, see information about SRC_HEADER_* and SRC_HEADERS env vars at https://github.com/sourcegraph/src-cli/blob/main/AUTH_PROXY.md)") | ||
| return cmderrors.ExitCode1 | ||
| if p.useOAuth { | ||
| return loginFlowOAuth, runOAuthLogin | ||
| } | ||
|
|
||
| if result.CurrentUser == nil { | ||
| // This should never happen; we verified there is an access token, so there should always be | ||
| // a user. | ||
| printProblem(fmt.Sprintf("Unable to determine user on %s.", endpointArg)) | ||
| return cmderrors.ExitCode1 | ||
| if !hasEffectiveAuth(ctx, p.cfg, endpointArg) { | ||
| return loginFlowMissingAuth, runMissingAuthLogin | ||
| } | ||
| fmt.Fprintln(out) | ||
| fmt.Fprintf(out, "✔️ Authenticated as %s on %s\n", result.CurrentUser.Username, endpointArg) | ||
|
|
||
| if p.useOAuth { | ||
| fmt.Fprintln(out) | ||
| fmt.Fprintf(out, "Authenticated with OAuth credentials") | ||
| if endpointArg != p.cfg.Endpoint { | ||
| return loginFlowEndpointConflict, runEndpointConflictLogin | ||
| } | ||
|
|
||
| fmt.Fprintln(out) | ||
| return nil | ||
| return loginFlowValidate, runValidatedLogin | ||
| } | ||
|
|
||
| func runOAuthDeviceFlow(ctx context.Context, endpoint string, out io.Writer, client oauth.Client) (*oauth.Token, error) { | ||
| authResp, err := client.Start(ctx, endpoint, nil) | ||
| if err != nil { | ||
| return nil, err | ||
| // hasEffectiveAuth determines whether we have auth credentials to continue. It first checks for a resolved Access Token in | ||
| // config, then it checks for a stored OAuth token. | ||
| func hasEffectiveAuth(ctx context.Context, cfg *config, resolvedEndpoint string) bool { | ||
| if cfg.AccessToken != "" { | ||
| return true | ||
| } | ||
|
|
||
| authURL := authResp.VerificationURIComplete | ||
| msg := fmt.Sprintf("If your browser did not open automatically, visit %s.", authURL) | ||
| if authURL == "" { | ||
| authURL = authResp.VerificationURI | ||
| msg = fmt.Sprintf("If your browser did not open automatically, visit %s and enter the user code %s", authURL, authResp.DeviceCode) | ||
| if _, err := loadStoredOAuthToken(ctx, resolvedEndpoint); err == nil { | ||
| return true | ||
| } | ||
| _ = openInBrowser(authURL) | ||
| fmt.Fprintln(out) | ||
| fmt.Fprint(out, msg) | ||
|
|
||
| fmt.Fprintln(out) | ||
| fmt.Fprint(out, "Waiting for authorization...") | ||
| defer fmt.Fprintf(out, "DONE\n\n") | ||
| return false | ||
| } | ||
|
|
||
| interval := time.Duration(authResp.Interval) * time.Second | ||
| if interval <= 0 { | ||
| interval = 5 * time.Second | ||
| } | ||
| func printLoginProblem(out io.Writer, problem string) { | ||
| fmt.Fprintf(out, "❌ Problem: %s\n", problem) | ||
| } | ||
|
|
||
| resp, err := client.Poll(ctx, endpoint, authResp.DeviceCode, interval, authResp.ExpiresIn) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| func loginAccessTokenMessage(endpoint string) string { | ||
| return fmt.Sprintf("\n"+`🛠 To fix: Create an access token by going to %s/user/settings/tokens, then set the following environment variables in your terminal: | ||
|
|
||
| token := resp.Token(endpoint) | ||
| token.ClientID = client.ClientID() | ||
| return token, nil | ||
| } | ||
| export SRC_ENDPOINT=%s | ||
| export SRC_ACCESS_TOKEN=(your access token) | ||
|
|
||
| func openInBrowser(url string) error { | ||
| if url == "" { | ||
| return nil | ||
| } | ||
| To verify that it's working, run the login command again. | ||
|
|
||
| var cmd *exec.Cmd | ||
| switch runtime.GOOS { | ||
| case "darwin": | ||
| cmd = exec.Command("open", url) | ||
| case "windows": | ||
| // "start" is a cmd.exe built-in; the empty string is the window title. | ||
| cmd = exec.Command("cmd", "/c", "start", "", url) | ||
| default: | ||
| cmd = exec.Command("xdg-open", url) | ||
| } | ||
| return cmd.Run() | ||
| Alternatively, you can try logging in using OAuth by running: src login --oauth %s | ||
| `, endpoint, endpoint, endpoint) | ||
| } | ||
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,108 @@ | ||
| package main | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "io" | ||
| "os/exec" | ||
| "runtime" | ||
| "time" | ||
|
|
||
| "github.com/sourcegraph/src-cli/internal/api" | ||
| "github.com/sourcegraph/src-cli/internal/cmderrors" | ||
| "github.com/sourcegraph/src-cli/internal/oauth" | ||
| ) | ||
|
|
||
| func runOAuthLogin(ctx context.Context, p loginParams) error { | ||
| endpointArg := cleanEndpoint(p.endpoint) | ||
| client, err := oauthLoginClient(ctx, p, endpointArg) | ||
| if err != nil { | ||
| printLoginProblem(p.out, fmt.Sprintf("OAuth Device flow authentication failed: %s", err)) | ||
| fmt.Fprintln(p.out, loginAccessTokenMessage(endpointArg)) | ||
| return cmderrors.ExitCode1 | ||
| } | ||
|
|
||
| if err := validateCurrentUser(ctx, client, p.out, endpointArg); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| fmt.Fprintln(p.out) | ||
| fmt.Fprint(p.out, "✔︎ Authenticated with OAuth credentials") | ||
| fmt.Fprintln(p.out) | ||
| return nil | ||
| } | ||
|
|
||
| func oauthLoginClient(ctx context.Context, p loginParams, endpoint string) (api.Client, error) { | ||
| token, err := runOAuthDeviceFlow(ctx, endpoint, p.out, p.oauthClient) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| if err := oauth.StoreToken(ctx, token); err != nil { | ||
| fmt.Fprintln(p.out) | ||
| fmt.Fprintf(p.out, "⚠️ Warning: Failed to store token in keyring store: %q. Continuing with this session only.\n", err) | ||
| } | ||
|
|
||
| return api.NewClient(api.ClientOpts{ | ||
| Endpoint: p.cfg.Endpoint, | ||
| AdditionalHeaders: p.cfg.AdditionalHeaders, | ||
| Flags: p.apiFlags, | ||
| Out: p.out, | ||
| ProxyURL: p.cfg.ProxyURL, | ||
| ProxyPath: p.cfg.ProxyPath, | ||
| OAuthToken: token, | ||
| }), nil | ||
| } | ||
|
|
||
| func runOAuthDeviceFlow(ctx context.Context, endpoint string, out io.Writer, client oauth.Client) (*oauth.Token, error) { | ||
| authResp, err := client.Start(ctx, endpoint, nil) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| authURL := authResp.VerificationURIComplete | ||
| msg := fmt.Sprintf("If your browser did not open automatically, visit %s.", authURL) | ||
| if authURL == "" { | ||
| authURL = authResp.VerificationURI | ||
| msg = fmt.Sprintf("If your browser did not open automatically, visit %s and enter the user code %s", authURL, authResp.DeviceCode) | ||
| } | ||
| _ = openInBrowser(authURL) | ||
| fmt.Fprintln(out) | ||
| fmt.Fprint(out, msg) | ||
|
|
||
| fmt.Fprintln(out) | ||
| fmt.Fprint(out, "Waiting for authorization... ") | ||
| defer fmt.Fprintf(out, "DONE\n\n") | ||
|
|
||
| interval := time.Duration(authResp.Interval) * time.Second | ||
| if interval <= 0 { | ||
| interval = 5 * time.Second | ||
| } | ||
|
|
||
| resp, err := client.Poll(ctx, endpoint, authResp.DeviceCode, interval, authResp.ExpiresIn) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| token := resp.Token(endpoint) | ||
| token.ClientID = client.ClientID() | ||
| return token, nil | ||
| } | ||
|
|
||
| func openInBrowser(url string) error { | ||
| if url == "" { | ||
| return nil | ||
| } | ||
|
|
||
| var cmd *exec.Cmd | ||
| switch runtime.GOOS { | ||
| case "darwin": | ||
| cmd = exec.Command("open", url) | ||
| case "windows": | ||
| // "start" is a cmd.exe built-in; the empty string is the window title. | ||
| cmd = exec.Command("cmd", "/c", "start", "", url) | ||
| default: | ||
| cmd = exec.Command("xdg-open", url) | ||
| } | ||
| return cmd.Run() | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
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.
This branch was moved to
login_validate.go->runMissingAuthLogin