aboutsummaryrefslogtreecommitdiff
path: root/maltoken.go
blob: d73ea7920e8e8dbef22ccec98c0a2e29aecd9623 (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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/*
maltoken - A go package for the MyAnimeList OAuth mechanism
Copyright © 2023 Vidhu Kant Sharma <vidhukant@vidhukant.com>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

package maltoken

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"html"
	"math/rand"
	"net/http"
	"net/url"
	"strings"
	"time"
)

var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
var SuccessHTML = "<p>Success! You may close this tab now.</p>"
var BadRequestHTML = "<p>Invalid request.</p>"
var ErrHTML = "<p>MyAnimeList responded with an error: %s</p>"

func codeChallenge() string {
	rand.Seed(time.Now().UnixNano())
	b := make([]rune, 128)
	for i := range b {
		b[i] = letterRunes[rand.Intn(len(letterRunes))]
	}
	return string(b)
}

func GetChallengeLink(clientId string) (string, string) {
	challenge := codeChallenge()
	return challenge, "https://myanimelist.net/v1/oauth2/authorize?response_type=code&client_id=" + clientId + "&code_challenge=" + challenge
}

func Listen(clientId, verifier string, port int) (map[string]interface{}, error) {
	var res map[string]interface{}
	var e error

	mux := http.NewServeMux()
	server := &http.Server{
		Addr: fmt.Sprintf(":%d", port),
		Handler: mux,
	}

	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		code, codeExists := r.URL.Query()["code"]
		if !codeExists {
			fmt.Fprintf(w, BadRequestHTML)
			return
		}

		resp, err := http.PostForm("https://myanimelist.net/v1/oauth2/token", url.Values {
			"client_id": {clientId},
			"code_verifier": {verifier},
			"grant_type": {"authorization_code"},
			"code": {code[0]},
		})
		if err != nil {
			// error while making post request
			e = err
			go server.Shutdown(context.Background())
			return
		}

		json.NewDecoder(resp.Body).Decode(&res)

		if res["error"] != nil {
			// MyAnimeList returned error
			errMsg := fmt.Sprintf("%v (%v)", res["message"], res["error"])
			e = errors.New(errMsg)

			if strings.Contains(ErrHTML, "%s") {
				fmt.Fprintf(w, ErrHTML, html.EscapeString(errMsg))
			} else {
				fmt.Fprintf(w, ErrHTML)
			}

			go server.Shutdown(context.Background())
			return
		}

		fmt.Fprintf(w, SuccessHTML)
		go server.Shutdown(context.Background())
	})

	err := server.ListenAndServe()
	if err != nil && err != http.ErrServerClosed {
		e = err
	}

	return res, e
}