-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_token.ts
57 lines (52 loc) · 1.36 KB
/
get_token.ts
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
export function getToken(code: string, port: string) {
const data = {
grant_type: 'authorization_code',
code: code,
redirect_uri: 'http://localhost:' + port + '/callback'
}
return fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
headers: {
'Authorization':
'Basic ' +
Buffer.from(
process.env.CLIENT_ID + ':' + process.env.SECRET
).toString('base64')
},
body: new URLSearchParams(data)
})
}
const state = {
token: '',
expires_in: 0
}
export async function refresh(token: string) {
const data = {
grant_type: 'refresh_token',
refresh_token: token
}
const {access_token, expires_in} = await fetch(
'https://accounts.spotify.com/api/token',
{
method: 'POST',
headers: {
'Authorization':
'Basic ' +
Buffer.from(
process.env.CLIENT_ID + ':' + process.env.SECRET
).toString('base64')
},
body: new URLSearchParams(data)
}
).then((res) => res.json())
state.token = access_token
state.expires_in = expires_in
/** just calls itself over and over, making sure we always have
* a token that's up-to-date
* */
setTimeout(() => refresh(access_token), expires_in * 1000)
}
export const provideToken = () => state.token
export const updateToken = (token: string) => {
state.token = token
}