summary refs log tree commit diff
path: root/oauth.go
blob: e3f4174675139288ec87046c2587b7dbd228ed92 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package main

import (
	"fmt"
	"net/http"
	"os/exec"
)

func openBrowser(url string) error {
	cmd := exec.Command("xdg-open", url)
	return cmd.Start()
}

func startServer(codeChannel chan string) {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		code := r.URL.Query().Get("code")
		if code != "" {
			codeChannel <- code

			fmt.Fprintf(w, "Authorization successful! You can now close this window.")
		} else {
			http.Error(w, "Authorization failed", http.StatusBadRequest)
		}
	})

	err := http.ListenAndServe(":3000", nil)
	if err != nil {
		fmt.Printf("Error starting server: %v\n", err)
	}
}

func GetOAuth() (string, error) {
	url := fmt.Sprintf("%s?%s&%s&%s&%s&%s",
		"https://id.twitch.tv/oauth2/authorize",
		"response_type=code",
		fmt.Sprintf("client_id=%s", clientSecrets.ClientID),
		"redirect_uri=http://localhost:3000",
		"scope=user%3Aread%3Afollows",
		"state=xsscheckbasic101",
	)

	err := openBrowser(url)
	if err != nil {
		return "", fmt.Errorf("failed to open browser: %v", err)
	}

	codeChannel := make(chan string)
	go startServer(codeChannel)

	code := <-codeChannel

	return code, nil
}