arimelody.me/discord/discord.go

132 lines
4.2 KiB
Go
Raw Normal View History

package discord
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"strings"
)
const API_ENDPOINT = "https://discord.com/api/v10"
var CREDENTIALS_PROVIDED = true
var CLIENT_ID = func() string {
envvar := os.Getenv("DISCORD_CLIENT_ID")
if envvar == "" {
fmt.Printf("DISCORD_CLIENT_ID was not provided. Admin login will be unavailable.\n")
CREDENTIALS_PROVIDED = false
}
return envvar
}()
var CLIENT_SECRET = func() string {
envvar := os.Getenv("DISCORD_CLIENT_SECRET")
if envvar == "" {
fmt.Printf("DISCORD_CLIENT_SECRET was not provided. Admin login will be unavailable.\n")
CREDENTIALS_PROVIDED = false
}
return envvar
}()
var REDIRECT_URI = func() string {
envvar := os.Getenv("DISCORD_REDIRECT_URI")
if envvar == "" {
fmt.Printf("DISCORD_REDIRECT_URI was not provided. Admin login will be unavailable.\n")
CREDENTIALS_PROVIDED = false
}
return envvar
}()
var OAUTH_CALLBACK_URI = func() string {
envvar := os.Getenv("OAUTH_CALLBACK_URI")
if envvar == "" {
fmt.Printf("OAUTH_CALLBACK_URI was not provided. Admin login will be unavailable.\n")
CREDENTIALS_PROVIDED = false
}
return envvar
}()
type (
AccessTokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
Scope string `json:"scope"`
}
AuthInfoResponse struct {
Application struct {
Id string `json:"id"`
Name string `json:"name"`
Icon string `json:"icon"`
Description string `json:"description"`
Hook bool `json:"hook"`
BotPublic bool `json:"bot_public"`
BotRequireCodeGrant bool `json:"bot_require_code_grant"`
VerifyKey string `json:"verify_key"`
} `json:"application"`
Scopes []string `json:"scopes"`
Expires string `json:"expires"`
User DiscordUser `json:"user"`
}
DiscordUser struct {
Id string `json:"id"`
Username string `json:"username"`
Avatar string `json:"avatar"`
Discriminator string `json:"discriminator"`
GlobalName string `json:"global_name"`
PublicFlags int `json:"public_flags"`
}
)
func GetOAuthTokenFromCode(code string) (string, error) {
// let's get an oauth token!
req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("%s/oauth2/token", API_ENDPOINT),
strings.NewReader(url.Values{
"client_id": {CLIENT_ID},
"client_secret": {CLIENT_SECRET},
"grant_type": {"authorization_code"},
"code": {code},
"redirect_uri": {OAUTH_CALLBACK_URI},
}.Encode()))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err := http.DefaultClient.Do(req)
if err != nil {
return "", errors.New(fmt.Sprintf("Failed while contacting discord API: %s", err))
}
oauth := AccessTokenResponse{}
err = json.NewDecoder(res.Body).Decode(&oauth)
if err != nil {
return "", errors.New(fmt.Sprintf("Failed to parse OAuth response data from discord: %s\n", err))
}
res.Body.Close()
return oauth.AccessToken, nil
}
func GetDiscordUserFromAuth(token string) (DiscordUser, error) {
// let's get authorisation information!
req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/oauth2/@me", API_ENDPOINT), nil)
req.Header.Add("Authorization", "Bearer " + token)
res, err := http.DefaultClient.Do(req)
if err != nil {
return DiscordUser{}, errors.New(fmt.Sprintf("Failed to retrieve discord auth information: %s\n", err))
}
auth_info := AuthInfoResponse{}
err = json.NewDecoder(res.Body).Decode(&auth_info)
if err != nil {
return DiscordUser{}, errors.New(fmt.Sprintf("Failed to parse auth information from discord: %s\n", err))
}
defer res.Body.Close()
return auth_info.User, nil
}