Files
coder/cli/cliui/gitauth.go
Kyle Carberry 7f226d4f90 feat: add support for coder_git_auth data source (#6334)
* Add git auth providers schema

* Pipe git auth providers to the schema

* Add git auth providers to the API

* Add gitauth endpoint to query authenticated state

* Add endpoint to query git state

* Use BroadcastChannel to automatically authenticate with Git

* Add error validation for submitting the create workspace form

* Fix panic on template dry-run

* Add tests for the template version Git auth endpoint

* Show error if no gitauth is configured

* Add gitauth to cliui

* Fix unused method receiver

* Fix linting errors

* Fix dbauthz querier test

* Fix make gen

* Add JavaScript test for git auth

* Fix bad error message

* Fix provisionerd test race

See https://github.com/coder/coder/actions/runs/4277960646/jobs/7447232814

* Fix requested changes

* Add comment to CreateWorkspacePageView
2023-02-27 10:18:19 -06:00

73 lines
1.6 KiB
Go

package cliui
import (
"context"
"fmt"
"io"
"time"
"github.com/briandowns/spinner"
"github.com/coder/coder/codersdk"
)
type GitAuthOptions struct {
Fetch func(context.Context) ([]codersdk.TemplateVersionGitAuth, error)
FetchInterval time.Duration
}
func GitAuth(ctx context.Context, writer io.Writer, opts GitAuthOptions) error {
if opts.FetchInterval == 0 {
opts.FetchInterval = 500 * time.Millisecond
}
gitAuth, err := opts.Fetch(ctx)
if err != nil {
return err
}
spin := spinner.New(spinner.CharSets[78], 100*time.Millisecond, spinner.WithColor("fgHiGreen"))
spin.Writer = writer
spin.ForceOutput = true
spin.Suffix = " Waiting for Git authentication..."
defer spin.Stop()
ticker := time.NewTicker(opts.FetchInterval)
defer ticker.Stop()
for _, auth := range gitAuth {
if auth.Authenticated {
return nil
}
_, _ = fmt.Fprintf(writer, "You must authenticate with %s to create a workspace with this template. Visit:\n\n\t%s\n\n", auth.Type.Pretty(), auth.AuthenticateURL)
ticker.Reset(opts.FetchInterval)
spin.Start()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-ticker.C:
}
gitAuth, err := opts.Fetch(ctx)
if err != nil {
return err
}
var authed bool
for _, a := range gitAuth {
if !a.Authenticated || a.ID != auth.ID {
continue
}
authed = true
break
}
// The user authenticated with the provider!
if authed {
break
}
}
spin.Stop()
_, _ = fmt.Fprintf(writer, "Successfully authenticated with %s!\n\n", auth.Type.Pretty())
}
return nil
}