1
0
mirror of https://github.com/mgerb/go-discord-bot synced 2026-01-10 09:02:49 +00:00

wip - more oauth work

This commit is contained in:
2018-02-18 16:36:29 -06:00
parent 33c6e8e3fc
commit 79b4fecd3c
6 changed files with 157 additions and 71 deletions

View File

@@ -1,31 +1,20 @@
package handlers
import (
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"strings"
"fmt"
"github.com/gin-gonic/gin"
"github.com/mgerb/go-discord-bot/server/config"
"github.com/mgerb/go-discord-bot/server/webserver/discord"
log "github.com/sirupsen/logrus"
)
const discordApi = "https://discordapp.com/api/v6/oauth2/token"
const cashGuildID = "101198129352691712"
type oauthReq struct {
Code string `json:"code"`
}
type oauthResp 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"`
}
// Oauth -
func Oauth(c *gin.Context) {
var json oauthReq
@@ -38,7 +27,7 @@ func Oauth(c *gin.Context) {
return
}
oauth, err := postReq(json.Code)
oauth, err := discord.Oauth(json.Code)
if err != nil {
log.Error(err)
@@ -46,49 +35,16 @@ func Oauth(c *gin.Context) {
return
}
user, err := discord.GetUserInfo(oauth.AccessToken)
if err != nil {
log.Error(err)
c.JSON(500, err)
return
}
// TODO: generate jwt for user
fmt.Println(user)
c.JSON(200, oauth)
}
func postReq(code string) (oauthResp, error) {
form := url.Values{}
form.Set("client_id", config.Config.ClientId)
form.Set("client_secret", config.Config.ClientSecret)
form.Set("grant_type", "authorization_code")
form.Set("code", code)
form.Set("redirect_uri", config.Config.RedirectUri)
req, err := http.NewRequest("POST", discordApi, strings.NewReader(form.Encode()))
if err != nil {
return oauthResp{}, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
c := &http.Client{}
resp, err := c.Do(req)
if err != nil {
return oauthResp{}, err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return oauthResp{}, err
}
var oauth oauthResp
err = json.Unmarshal(data, &oauth)
if err != nil {
return oauthResp{}, err
}
return oauth, nil
}