-
Notifications
You must be signed in to change notification settings - Fork 13
/
auth.go
116 lines (98 loc) · 2.57 KB
/
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package radiko
import (
"context"
"encoding/base64"
"errors"
"fmt"
"io/ioutil"
"strconv"
"strings"
)
// AuthorizeToken returns an enables auth_token and error,
// and sets auth_token in Client.
// Is is a alias function that wraps Auth1 and Auth2.
func (c *Client) AuthorizeToken(ctx context.Context) (string, error) {
authToken, length, offset, err := c.Auth1(ctx)
if err != nil {
return "", err
}
b := radikoAuthkeyValue[offset : offset+length]
partialKey := base64.StdEncoding.EncodeToString([]byte(b))
slc, err := c.Auth2(ctx, authToken, partialKey)
if err != nil {
return "", err
}
if err := verifyAuth2Response(slc); err != nil {
return "", err
}
c.setAuthTokenHeader(authToken)
return authToken, nil
}
// Auth1 returns authToken, keyLength, keyOffset and error.
func (c *Client) Auth1(ctx context.Context) (string, int64, int64, error) {
apiEndpoint := apiPath(apiV2, "auth1")
req, err := c.newRequest(ctx, "GET", apiEndpoint, &Params{
header: map[string]string{
radikoAppHeader: radikoApp,
radikoAppVersionHeader: radikoAppVersion,
radikoUserHeader: radikoUser,
radikoDeviceHeader: radikoDevice,
},
})
if err != nil {
return "", 0, 0, err
}
resp, err := c.Do(req)
if err != nil {
return "", 0, 0, err
}
defer resp.Body.Close()
authToken := resp.Header.Get(radikoAuthTokenHeader)
keyLength := resp.Header.Get(radikoKeyLentghHeader)
keyOffset := resp.Header.Get(radikoKeyOffsetHeader)
length, err := strconv.ParseInt(keyLength, 10, 64)
if err != nil {
return "", 0, 0, err
}
offset, err := strconv.ParseInt(keyOffset, 10, 64)
if err != nil {
return "", 0, 0, err
}
return authToken, length, offset, err
}
// Auth2 enables the given authToken.
func (c *Client) Auth2(ctx context.Context, authToken, partialKey string) ([]string, error) {
apiEndpoint := apiPath(apiV2, "auth2")
req, err := c.newRequest(ctx, "GET", apiEndpoint, &Params{
header: map[string]string{
radikoUserHeader: radikoUser,
radikoDeviceHeader: radikoDevice,
radikoAuthTokenHeader: authToken,
radikoPartialKeyHeader: partialKey,
},
})
if err != nil {
return nil, err
}
resp, err := c.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
s := strings.Split(string(b), ",")
return s, nil
}
func verifyAuth2Response(slc []string) error {
if len(slc) == 0 {
return errors.New("missing token")
}
s := strings.TrimSpace(slc[0])
if !strings.HasPrefix(s, "JP") {
return fmt.Errorf("invalid token: %s", s)
}
return nil
}