-
Notifications
You must be signed in to change notification settings - Fork 1
/
anilist_auth.go
99 lines (83 loc) 路 2.08 KB
/
anilist_auth.go
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
package libmangal
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
)
type AnilistLoginCredentials struct {
ID string
Secret string
Code string
}
// anilistStoreAccessCodeStoreKey is the key used to store Anilist access code.
// It's needed, since the KV interface always expects a key to be passed.
const anilistStoreAccessCodeStoreKey = "hi"
// Authorize will obtain Anilist token for API requests
func (a *Anilist) Authorize(
ctx context.Context,
credentials AnilistLoginCredentials,
) error {
a.options.Log("logging in to Anilist")
for _, t := range []struct {
name string
value string
}{
{"id", credentials.ID},
{"secret", credentials.Secret},
{"code", credentials.Code},
} {
if t.value == "" {
return AnilistError{fmt.Errorf("%s is empty", t.name)}
}
}
body, err := json.Marshal(map[string]string{
"client_id": credentials.ID,
"client_secret": credentials.Secret,
"code": credentials.Code,
"grant_type": "authorization_code",
"redirect_uri": "https://anilist.co/api/v2/oauth/pin",
})
if err != nil {
return err
}
if err != nil {
return AnilistError{err}
}
request, err := http.NewRequestWithContext(
ctx,
http.MethodPost,
"https://anilist.co/api/v2/oauth/token",
bytes.NewBuffer(body),
)
if err != nil {
return AnilistError{err}
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Accept", "application/json")
response, err := a.options.HTTPClient.Do(request)
if err != nil {
return AnilistError{err}
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return AnilistError{errors.New(response.Status)}
}
var authResponse struct {
AccessToken string `json:"access_token"`
}
err = json.NewDecoder(response.Body).Decode(&authResponse)
if err != nil {
return AnilistError{err}
}
if err := a.options.AccessTokenStore.Set(anilistStoreAccessCodeStoreKey, authResponse.AccessToken); err != nil {
return err
}
a.accessToken = authResponse.AccessToken
return nil
}
func (a *Anilist) IsAuthorized() bool {
return a.accessToken != ""
}