twitchapon

[Twi]tch [Cha]nnel [Po]ints Rewards Redemption Listener
git clone git://bsandro.tech/twitchapon
Log | Files | Refs | README | LICENSE

auth.go (1172B)


      1 package main
      2 
      3 import (
      4 	"encoding/json"
      5 	"errors"
      6 	"fmt"
      7 	"io"
      8 	"net/http"
      9 )
     10 
     11 type TAuth struct {
     12 	AccessToken  string   `json:"access_token"`
     13 	RefreshToken string   `json:"refresh_token"`
     14 	ExpiresIn    uint64   `json:"expires_in"`
     15 	Scope        []string `json:"scope"`
     16 	TokenType    string   `json:"token_type"`
     17 	Message      string   `json:"message"`
     18 }
     19 
     20 func (auth *TAuth) Init(auth_code string) error {
     21 	const auth_request_url string = "https://id.twitch.tv/oauth2/token?client_id=%s&client_secret=%s&grant_type=authorization_code&code=%s&redirect_uri=http://%s"
     22 	response, err := http.Post(fmt.Sprintf(auth_request_url, App.Config.ClientId, App.Config.ClientSecret, auth_code, App.Config.LocalServer), "", nil)
     23 	if err != nil {
     24 		return err
     25 	}
     26 	defer response.Body.Close()
     27 	body, err := io.ReadAll(response.Body)
     28 	if err != nil {
     29 		return err
     30 	}
     31 	if err := json.Unmarshal(body, auth); err != nil {
     32 		return err
     33 	}
     34 
     35 	if len(auth.AccessToken) == 0 {
     36 		if len(auth.Message) > 0 {
     37 			return errors.New(auth.Message)
     38 		} else {
     39 			return errors.New("Auth error")
     40 		}
     41 	}
     42 	return nil
     43 }
     44 
     45 func (auth *TAuth) IsInited() bool {
     46 	return auth != nil && len(auth.AccessToken) > 0
     47 }