-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
181 lines (143 loc) · 4.6 KB
/
index.js
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
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const querystring = require('querystring');
const cookieParser = require('cookie-parser');
const axios = require('axios');
const uniqid = require('uniqid');
const PORT = process.env.PORT || null;
const client_id = process.env.SPOTIFY_CLIENT_ID;
const client_secret = process.env.SPOTIFY_CLIENT_SECRET;
const spotifyAuthUrl = 'https://accounts.spotify.com/authorize';
const spotifyTokenUrl = 'https://accounts.spotify.com/api/token';
const defaultScope = [
// See: https://developer.spotify.com/documentation/general/guides/scopes/
'playlist-read-collaborative',
'playlist-read-private',
'user-library-read',
'user-modify-playback-state',
'user-read-currently-playing',
'user-read-email',
'user-read-playback-state',
'user-read-private',
];
const defaultReturnUrl = '/result';
const validReturnUrls = process.env.VALID_RETURN_URLS ? process.env.VALID_RETURN_URLS.split(',') : [];
function appUrl(url, req) {
return `${req.protocol}://${req.get('host')}${url}`;
}
function redirectUri(req) {
return appUrl('/callback', req);
}
function requestParams(req) {
const scope = (req.query.scope ? req.query.scope.split(',') : undefined) || defaultScope;
const returnUrl = req.query.returnUrl || appUrl(defaultReturnUrl, req);
return {
scope,
returnUrl,
};
}
function validReturnUrl(returnUrl, req) {
if (returnUrl === appUrl(defaultReturnUrl, req)) return true;
if (validReturnUrls.indexOf(returnUrl) > -1) return true;
return false;
}
function result(res, returnUrl = defaultReturnUrl, params = {}) {
return res.redirect(`${returnUrl}?${querystring.stringify(params)}`);
}
const app = express();
app.enable('trust proxy'); // for Heroku
app.use(cors()).use(cookieParser());
app.get('/debug', function(req, res) {
const state = uniqid();
const redirect_uri = redirectUri(req);
const { scope, returnUrl } = requestParams(req);
const authQuery = {
response_type: 'code',
scope: scope.join(' '),
client_id,
redirect_uri,
state,
};
const authUrl = `${spotifyAuthUrl}?${querystring.stringify(authQuery)}`;
return res.send({
PORT,
redirect_uri,
returnUrl,
scope,
authQuery,
authUrl,
});
});
app.get('/login', function(req, res) {
const state = uniqid();
const redirect_uri = redirectUri(req);
const { scope, returnUrl } = requestParams(req);
// check if valid return URI
if (!validReturnUrl(returnUrl, req)) {
res.status(403).send('Invalid return URI');
return;
}
res.cookie('spotify-auth-state', state);
res.cookie('spotify-auth-return-uri', returnUrl);
const authQuery = {
response_type: 'code',
scope: scope.join(' '),
client_id,
redirect_uri,
state,
};
const authUrl = `${spotifyAuthUrl}?${querystring.stringify(authQuery)}`;
return res.redirect(authUrl);
});
app.get('/callback', function(req, res) {
const code = req.query.code || null;
const state = req.query.state || null;
const storedState = req.cookies ? req.cookies['spotify-auth-state'] : null;
const returnUrl = req.cookies ? req.cookies['spotify-auth-return-uri'] : defaultReturnUrl;
res.clearCookie('spotify-auth-state');
res.clearCookie('spotify-auth-return-uri');
if (state === null || state !== storedState) {
result(res, returnUrl, { error: 'state_mismatch' });
return;
}
const postData = {
code,
redirect_uri: redirectUri(req),
grant_type: 'authorization_code',
};
const postConfig = {
headers: { 'Authorization': 'Basic ' + (new Buffer.from(client_id + ':' + client_secret).toString('base64')) },
};
axios.post(spotifyTokenUrl, querystring.stringify(postData), postConfig)
.then(response => {
result(res, returnUrl, response.data);
})
.catch(error => {
result(res, returnUrl, { error: `Status ${error.response.status}: ${error.response.statusText}` });
});
});
app.get('/refresh', function(req, res) {
const refresh_token = req.query.refresh_token;
const postData = {
refresh_token,
redirect_uri: redirectUri(req),
grant_type: 'refresh_token',
};
const postConfig = {
headers: { 'Authorization': 'Basic ' + (new Buffer.from(client_id + ':' + client_secret).toString('base64')) },
};
axios.post(spotifyTokenUrl, querystring.stringify(postData), postConfig)
.then(response => {
res.send(response.data);
})
.catch(error => {
res.status(error.response.status).send(error);
});
});
app.get(defaultReturnUrl, function(req, res) {
res.send(req.query);
});
app.listen(PORT, () =>
console.log(`Spotify Auth - listening on: ${PORT}`)
);