package main
import (
"context"
"fmt"
"net"
"net/http"
"golang.org/x/oauth2"
)
var conf = &oauth2.Config{
ClientID: "lnk_…",
Endpoint: oauth2.Endpoint{
AuthURL: "https://routing.dari.dev/v1/link/authorize",
TokenURL: "https://routing.dari.dev/v1/link/token",
AuthStyle: oauth2.AuthStyleInParams,
},
}
// signIn opens Dari Link in the browser and returns the user's tokens.
func signIn(ctx context.Context) (*oauth2.Token, error) {
ln, err := net.Listen("tcp", "127.0.0.1:0") // any free port
if err != nil {
return nil, err
}
defer ln.Close()
conf.RedirectURL = fmt.Sprintf("http://%s/callback", ln.Addr())
state, verifier := oauth2.GenerateVerifier(), oauth2.GenerateVerifier()
codes := make(chan string, 1)
go http.Serve(ln, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("state") != state {
http.Error(w, "Sign-in failed. Run the command again.", http.StatusBadRequest)
codes <- ""
return
}
fmt.Fprintln(w, "Connected. You can close this tab.")
codes <- r.URL.Query().Get("code")
}))
fmt.Println("Open this link to connect your AI plan:")
fmt.Println(conf.AuthCodeURL(state, oauth2.S256ChallengeOption(verifier)))
code := <-codes
if code == "" {
return nil, fmt.Errorf("sign-in failed")
}
return conf.Exchange(ctx, code, oauth2.VerifierOption(verifier))
}