| 198 | } |
| 199 | |
| 200 | func loginRun(opts *LoginOptions) error { |
| 201 | cfg, err := opts.Config() |
| 202 | if err != nil { |
| 203 | return err |
| 204 | } |
| 205 | authCfg := cfg.Authentication() |
| 206 | copyToClipboard := shared.ShouldCopyToClipboard(cfg, opts.Clipboard) |
| 207 | |
| 208 | hostname := opts.Hostname |
| 209 | if opts.Interactive && hostname == "" { |
| 210 | var err error |
| 211 | hostname, err = promptForHostname(opts) |
| 212 | if err != nil { |
| 213 | return err |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | // The go-gh Config object currently does not support case-insensitive lookups for host names, |
| 218 | // so normalize the host name case here before performing any lookups with it or persisting it. |
| 219 | // https://github.com/cli/go-gh/pull/105 |
| 220 | hostname = strings.ToLower(hostname) |
| 221 | |
| 222 | if src, writeable := shared.AuthTokenWriteable(authCfg, hostname); !writeable { |
| 223 | fmt.Fprintf(opts.IO.ErrOut, "The value of the %s environment variable is being used for authentication.\n", src) |
| 224 | fmt.Fprint(opts.IO.ErrOut, "To have GitHub CLI store credentials instead, first clear the value from the environment.\n") |
| 225 | return cmdutil.SilentError |
| 226 | } |
| 227 | |
| 228 | plainHTTPClient, err := opts.PlainHttpClient() |
| 229 | if err != nil { |
| 230 | return err |
| 231 | } |
| 232 | |
| 233 | httpClient, err := opts.HttpClient() |
| 234 | if err != nil { |
| 235 | return err |
| 236 | } |
| 237 | |
| 238 | if opts.Token != "" { |
| 239 | if err := shared.HasMinimumScopes(httpClient, hostname, opts.Token); err != nil { |
| 240 | return fmt.Errorf("error validating token: %w", err) |
| 241 | } |
| 242 | username, err := shared.GetCurrentLogin(httpClient, hostname, opts.Token) |
| 243 | if err != nil { |
| 244 | return fmt.Errorf("error retrieving current user: %w", err) |
| 245 | } |
| 246 | |
| 247 | // Adding a user key ensures that a nonempty host section gets written to the config file. |
| 248 | _, loginErr := authCfg.Login(hostname, username, opts.Token, opts.GitProtocol, !opts.InsecureStorage) |
| 249 | return loginErr |
| 250 | } |
| 251 | |
| 252 | // Nudge users towards expiring tokens unless they have already expressed a preference, either with the flag or |
| 253 | // the config. Enterprise Server hosts are skipped because they may not support expiring tokens. |
| 254 | if opts.IO.IsStderrTTY() && opts.Expiring == nil && !ghauth.IsEnterprise(hostname) && !shared.ShouldUseExpiring(cfg, nil, hostname) { |
| 255 | cs := opts.IO.ColorScheme() |
| 256 | fmt.Fprintf(opts.IO.ErrOut, "%s Did you know that expiring tokens can be requested with %s? Read more at %s\n", |
| 257 | cs.WarningIcon(), cs.Bold("--expiring"), "https://gh.io/gh-expiring-tokens") |