mirror of
https://git.sr.ht/~phw/scotty
synced 2025-04-25 05:47:57 +02:00
WIP: Authenticate
This commit is contained in:
parent
3d3685d8bc
commit
94704f9cd0
5 changed files with 126 additions and 20 deletions
18
cmd/auth.go
18
cmd/auth.go
|
@ -25,11 +25,11 @@ import (
|
|||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/cli/browser"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
"go.uploadedlobster.com/scotty/backends"
|
||||
"go.uploadedlobster.com/scotty/storage"
|
||||
"golang.org/x/oauth2"
|
||||
"golang.org/x/oauth2/spotify"
|
||||
|
@ -42,34 +42,30 @@ var authCmd = &cobra.Command{
|
|||
Long: `For backends requiring authentication this command can be used to authenticate.`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
serviceName, serviceConfig := getConfigFromFlag(cmd, "service")
|
||||
fmt.Print("HERE\n")
|
||||
backend := serviceConfig.GetString("backend")
|
||||
|
||||
callbackHost, _ := strings.CutSuffix(viper.GetString("oauth-host"), "/")
|
||||
if callbackHost == "" {
|
||||
callbackHost = "127.0.0.1:2369"
|
||||
}
|
||||
callbackPath := "/callback/" + backend
|
||||
redirectURL, err := backends.BuildRedirectURL(viper.GetViper(), backend)
|
||||
cobra.CheckErr(err)
|
||||
|
||||
ctx := context.Background()
|
||||
conf := &oauth2.Config{
|
||||
ClientID: serviceConfig.GetString("client-id"),
|
||||
ClientSecret: serviceConfig.GetString("client-secret"),
|
||||
Scopes: []string{"user-read-recently-played"},
|
||||
RedirectURL: "http://" + callbackHost + callbackPath,
|
||||
RedirectURL: redirectURL.String(),
|
||||
Endpoint: spotify.Endpoint,
|
||||
}
|
||||
|
||||
responseChan := make(chan string)
|
||||
|
||||
// Start an HTTP server to listen for the response
|
||||
http.HandleFunc(callbackPath, func(w http.ResponseWriter, r *http.Request) {
|
||||
http.HandleFunc(redirectURL.Path, func(w http.ResponseWriter, r *http.Request) {
|
||||
code := r.URL.Query().Get("code")
|
||||
fmt.Fprint(w, "Token received, you can close this window now.")
|
||||
responseChan <- code
|
||||
})
|
||||
|
||||
go http.ListenAndServe(callbackHost, nil)
|
||||
go http.ListenAndServe(redirectURL.Host, nil)
|
||||
|
||||
// use PKCE to protect against CSRF attacks
|
||||
// https://www.ietf.org/archive/id/draft-ietf-oauth-security-topics-22.html#name-countermeasures-6
|
||||
|
@ -80,7 +76,7 @@ var authCmd = &cobra.Command{
|
|||
url := conf.AuthCodeURL("state", oauth2.AccessTypeOffline, oauth2.S256ChallengeOption(verifier))
|
||||
fmt.Printf("Visit the URL for the auth dialog: %v\n", url)
|
||||
|
||||
err := browser.OpenURL(url)
|
||||
err = browser.OpenURL(url)
|
||||
cobra.CheckErr(err)
|
||||
|
||||
code := <-responseChan
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue