|
| 1 | +// Helper functions for accessing the Spotify API. |
| 2 | +var https = require('https'); |
| 3 | +var Parse = require('parse/node').Parse; |
| 4 | + |
| 5 | +// Returns a promise that fulfills iff this user id is valid. |
| 6 | +function validateAuthData(authData) { |
| 7 | + return request('me', authData.access_token) |
| 8 | + .then((data) => { |
| 9 | + if (data && data.id == authData.id) { |
| 10 | + return; |
| 11 | + } |
| 12 | + throw new Parse.Error( |
| 13 | + Parse.Error.OBJECT_NOT_FOUND, |
| 14 | + 'Spotify auth is invalid for this user.'); |
| 15 | + }); |
| 16 | +} |
| 17 | + |
| 18 | +// Returns a promise that fulfills if this app id is valid. |
| 19 | +function validateAppId(appIds, authData) { |
| 20 | + var access_token = authData.access_token; |
| 21 | + if (!appIds.length) { |
| 22 | + throw new Parse.Error( |
| 23 | + Parse.Error.OBJECT_NOT_FOUND, |
| 24 | + 'Spotify auth is not configured.'); |
| 25 | + } |
| 26 | + return request('me', access_token) |
| 27 | + .then((data) => { |
| 28 | + if (data && appIds.indexOf(data.id) != -1) { |
| 29 | + return; |
| 30 | + } |
| 31 | + throw new Parse.Error( |
| 32 | + Parse.Error.OBJECT_NOT_FOUND, |
| 33 | + 'Spotify auth is invalid for this user.'); |
| 34 | + }); |
| 35 | +} |
| 36 | + |
| 37 | +// A promisey wrapper for Spotify API requests. |
| 38 | +function request(path, access_token) { |
| 39 | + return new Promise(function(resolve, reject) { |
| 40 | + https.get({ |
| 41 | + host: 'api.spotify.com', |
| 42 | + path: '/v1/' + path, |
| 43 | + headers: { |
| 44 | + 'Authorization': 'Bearer '+access_token |
| 45 | + } |
| 46 | + }, function(res) { |
| 47 | + var data = ''; |
| 48 | + res.on('data', function(chunk) { |
| 49 | + data += chunk; |
| 50 | + }); |
| 51 | + res.on('end', function() { |
| 52 | + data = JSON.parse(data); |
| 53 | + resolve(data); |
| 54 | + }); |
| 55 | + }).on('error', function(e) { |
| 56 | + reject('Failed to validate this access token with Spotify.'); |
| 57 | + }); |
| 58 | + }); |
| 59 | +} |
| 60 | + |
| 61 | +module.exports = { |
| 62 | + validateAppId: validateAppId, |
| 63 | + validateAuthData: validateAuthData |
| 64 | +}; |
0 commit comments