tierlist/backend/main.go

96 lines
2.3 KiB
Go
Raw Permalink Normal View History

2020-12-11 10:16:49 +00:00
package main
import (
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
"time"
"github.com/gin-gonic/contrib/sessions"
"github.com/gin-gonic/gin"
"backend/config"
)
type Web struct {
config *config.Config
hc *http.Client
}
func main() {
cfgPath := flag.String("config", "config.toml", "Path to the config file (defaults to config.toml)")
flag.Parse()
cfg, err := config.ReadConfig(*cfgPath)
if err != nil {
log.Fatal(err)
}
hc := &http.Client{
Timeout: 10 * time.Second,
}
web := &Web{
config: &cfg,
hc: hc,
}
r := gin.Default()
r.Use(gin.Recovery())
r.Use(sessions.Sessions("mysession", sessions.NewCookieStore([]byte(web.config.SessionSecret))))
r.GET("/login", web.loginHandler)
r.GET("/login/callback", web.loginCallbackHandler)
r.Run("127.0.0.1:1235")
}
func (web *Web) loginHandler(c *gin.Context) {
url := url.URL{
Scheme: "https",
Host: "osu.ppy.sh",
Path: "/oauth/authorize",
}
q := url.Query()
q.Set("client_id", web.config.Oauth.ClientId)
q.Set("redirect_uri", web.config.BaseUrl+"/login/callback")
q.Set("response_type", "code")
q.Set("scope", "identify public")
q.Set("state", "urmom")
url.RawQuery = q.Encode()
fmt.Println("redirecting to", url.String())
c.Redirect(http.StatusTemporaryRedirect, url.String())
}
func (web *Web) loginCallbackHandler(c *gin.Context) {
receivedCode := c.Query("code")
bodyQuery := url.Values{}
bodyQuery.Set("client_id", web.config.Oauth.ClientId)
bodyQuery.Set("client_secret", web.config.Oauth.ClientSecret)
bodyQuery.Set("code", receivedCode)
bodyQuery.Set("grant_type", "authorization_code")
bodyQuery.Set("redirect_uri", web.config.BaseUrl+"/login/callback")
body := strings.NewReader(bodyQuery.Encode())
resp, _ := web.hc.Post("https://osu.ppy.sh/oauth/token", "application/x-www-form-urlencoded", body)
respBody, _ := ioutil.ReadAll(resp.Body)
type OsuToken struct {
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
}
var token OsuToken
_ = json.Unmarshal(respBody, &token)
fmt.Println("TOKEN", token)
session := sessions.Default(c)
session.Set("access_token", token.AccessToken)
session.Save()
c.Redirect(http.StatusTemporaryRedirect, "/")
}