This repository has been archived by the owner on Jul 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
130 lines (109 loc) · 3.91 KB
/
main.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
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
import { Application, Router } from "https://deno.land/x/[email protected]/mod.ts";
import * as queryString from "https://deno.land/x/[email protected]/mod.js";
import { load } from "https://deno.land/[email protected]/dotenv/mod.ts";
import { Base64 } from "https://deno.land/x/[email protected]/mod.ts";
if (!Deno.env.get('SPOTIFY_CLIENT_ID')) {
const env = await load();
for (const k in env) {
Deno.env.set(k, env[k]);
}
}
const SPOTIFY_CLIENT_ID = Deno.env.get('SPOTIFY_CLIENT_ID');
const SPOTIFY_CLIENT_SECRET = Deno.env.get('SPOTIFY_CLIENT_SECRET');
const randomString = (length: number) =>
[...Array(length)].map(() => Math.random().toString(36)[2]).join('');
const callbackMap = new Map<string, string>();
const router = new Router();
router.get('/', ({ response }) => {
response.headers.set('Access-Control-Allow-Origin', '*');
response.body = 'Hello, use GET /login to get your access token :)'
});
router.get('/login', ({ request, response }) => {
response.headers.set('Access-Control-Allow-Origin', '*');
const state = randomString(16);
const redirectUri = request.url.searchParams.get('redirect_uri');
const scope = (request.url.searchParams.get('scope') || '').split(' ');
// if (scope.length == 0) {
// scope.push('user-read-private');
// scope.push('user-read-email');
// }
callbackMap.set(state, redirectUri || '');
response.redirect('https://accounts.spotify.com/authorize?' + queryString.stringify({
response_type: 'code',
client_id: SPOTIFY_CLIENT_ID,
scope: scope.join(' '),
redirect_uri: request.url.origin + '/callback',
state: state
}));
});
router.get('/callback', async ({ request, response }) => {
response.headers.set('Access-Control-Allow-Origin', '*');
const code = request.url.searchParams.get('code');
const state = request.url.searchParams.get('state');
if (code && state && callbackMap.has(state)) {
const redirectUri = callbackMap.get(state);
callbackMap.delete(state);
const resp = await fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
body: new URLSearchParams({
code: code,
redirect_uri: request.url.origin + '/callback',
grant_type: 'authorization_code'
}),
headers: {
'Authorization': `Basic ${(Base64.fromString(`${SPOTIFY_CLIENT_ID}:${SPOTIFY_CLIENT_SECRET}`).toString())}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
});
if (resp.ok) {
const data = await resp.json();
if (!redirectUri) {
response.body = data;
} else {
response.redirect(queryString.stringifyUrl({
url: redirectUri!,
query: {
data: Base64.fromString(JSON.stringify(data)).toString()
}
}));
}
} else {
response.body = 'Failed to get access token.'
}
} else {
response.body = 'Invalid state.'
}
});
router.get('/refresh', async ({ request, response }) => {
response.headers.set('Access-Control-Allow-Origin', '*');
const refreshToken = request.url.searchParams.get('refresh_token');
if (refreshToken) {
const resp = await fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
body: new URLSearchParams({
refresh_token: refreshToken,
grant_type: 'refresh_token',
client_id: SPOTIFY_CLIENT_ID!
}),
headers: {
'Authorization': `Basic ${(Base64.fromString(`${SPOTIFY_CLIENT_ID}:${SPOTIFY_CLIENT_SECRET}`).toString())}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
});
if (resp.ok) {
response.body = await resp.text();
} else {
response.body = 'Failed to refresh access token.'
}
} else {
response.body = 'Invalid refresh token.'
}
});
const app = new Application();
app.use(router.routes());
app.use(router.allowedMethods());
app.addEventListener(
"listen",
(e) => console.log("Listening on http://localhost:8080"),
);
await app.listen({ port: 8080 });