2023-02-27 10:18:19 -06:00
package cliui
import (
"context"
"fmt"
"io"
"time"
"github.com/briandowns/spinner"
2023-08-18 13:55:43 -05:00
"github.com/coder/coder/v2/codersdk"
2023-02-27 10:18:19 -06:00
)
2023-10-03 09:04:39 -05:00
type ExternalAuthOptions struct {
2023-09-29 14:13:20 -05:00
Fetch func ( context . Context ) ([] codersdk . TemplateVersionExternalAuth , error )
2023-02-27 10:18:19 -06:00
FetchInterval time . Duration
}
2023-10-03 09:04:39 -05:00
func ExternalAuth ( ctx context . Context , writer io . Writer , opts ExternalAuthOptions ) error {
2023-02-27 10:18:19 -06:00
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
}
2024-05-29 10:37:54 -07:00
if auth . Optional {
continue
}
2023-02-27 10:18:19 -06:00
2023-10-03 09:04:39 -05:00
_ , _ = fmt . Fprintf ( writer , "You must authenticate with %s to create a workspace with this template. Visit:\n\n\t%s\n\n" , auth . DisplayName , auth . AuthenticateURL )
2023-02-27 10:18:19 -06:00
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 ()
2023-10-03 09:04:39 -05:00
_ , _ = fmt . Fprintf ( writer , "Successfully authenticated with %s!\n\n" , auth . DisplayName )
2023-02-27 10:18:19 -06:00
}
return nil
}