-
Notifications
You must be signed in to change notification settings - Fork 5
/
demo.mjs
153 lines (130 loc) · 3.83 KB
/
demo.mjs
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
import crypto from 'crypto';
import express from 'express';
import fetch from 'node-fetch';
import querystring from 'querystring';
import cookieParser from 'cookie-parser';
import dotenv from 'dotenv';
dotenv.config();
const PORT = process.env.PORT || 8989;
const CLIENT_ID = process.env.CLIENT_ID;
const CLIENT_SECRET = process.env.CLIENT_SECRET;
const REDIRECT_URI = `http://localhost:${PORT}/callback/`;
if (!CLIENT_ID) {
console.error('Missing CLIENT_ID');
process.exit(1);
} else if (!CLIENT_SECRET) {
console.error('Missing CLIENT_SECRET');
process.exit(1);
}
function login(_req, res) {
const buf = Buffer.alloc(16);
const randomBytes = crypto.randomFillSync(buf).toString('hex');
// your application requests authorization
const scope = [
'playlist-read-collaborative',
'playlist-read-private',
'streaming',
'user-read-email',
'user-read-private',
'user-library-read',
'user-library-modify',
'user-read-playback-state',
'user-modify-playback-state'
];
const query = querystring.stringify({
response_type: 'code',
client_id: CLIENT_ID,
scope: scope.join('%20'),
redirect_uri: REDIRECT_URI,
state: randomBytes
});
res.redirect(`https://accounts.spotify.com/authorize?${query}`);
}
async function callback(req, res) {
const code = req.query.code || null;
const authToken = Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString('base64');
const response = await fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
headers: {
'Authorization': `Basic ${authToken}`,
'Content-Type': 'application/x-www-form-urlencoded'
},
body: querystring.stringify({
code: code,
redirect_uri: REDIRECT_URI,
grant_type: 'authorization_code'
})
});
if (response.status !== 200) {
console.log(`Bad response: ${response.statusText}`);
res.type('json').send(JSON.stringify({
'type': 'error',
'error': 'Error while authorizing Spotify'
}));
return;
}
const { access_token } = await response.json();
res
.cookie('access_token', access_token, { signed: true })
.redirect(`http://localhost:${PORT}/`);
}
async function refresh(req, res) {
const refresh_token = req.query.refresh_token;
const authToken = Buffer.from(`${CLIENT_ID}:${CLIENT_SECRET}`).toString('base64');
const response = await fetch('https://accounts.spotify.com/api/token', {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
headers: {
'Authorization': `Basic ${authToken}`
},
body: JSON.stringify({
grant_type: 'refresh_token',
refresh_token: refresh_token
})
});
const obj = await response.json();
res.type('json').send(JSON.stringify({
'type': 'success',
'data': obj.access_token
}));
}
async function test(req, res) {
const accessToken = req.signedCookies.access_token;
if (accessToken) {
const response = await fetch('https://api.spotify.com/v1/me', {
headers: {
'Authorization': `Bearer ${accessToken}`
}
});
if (response.status === 200) {
res.type('json').send(JSON.stringify({
'type': 'success',
'data': accessToken
}));
} else {
res.type('json').send(JSON.stringify({
'type': 'error',
'data': 'Invalid or expired token'
}));
}
} else {
res.type('json').send(JSON.stringify({
'type': 'error',
'data': 'Invalid token'
}));
}
}
////////////////////////////////////////////////////////////////////////////////
const app = express();
app.use(express.static('public'));
app.use(express.static('dist'));
app.use(cookieParser([ 'secret1' ]));
app.get('/test', test);
app.get('/login', login);
app.get('/callback', callback);
app.get('/refresh_token', refresh);
console.log(`http://localhost:${PORT}/`);
app.listen(PORT);