Guest User

code

a guest
Jul 8th, 2022
422
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.39 KB | None | 0 0
  1. const { request } = require('express');
  2. const express = require('express');
  3. const client_id = "id";
  4. const client_secret = "secret";
  5. const redirect_uri = "http://localhost:3000/callback";
  6.  
  7. const app = express();
  8.  
  9. app.get('/login', (req, res) => {
  10. const scope = 'user-read-private user-read-email';
  11. const state = Math.random().toString(36).slice(2,18);
  12.  
  13. const auth_query_parameters = new URLSearchParams({
  14. response_type: "code",
  15. client_id: client_id,
  16. scope: scope,
  17. redirect_uri: redirect_uri,
  18. state: state
  19. });
  20.  
  21. res.redirect('http://accounts.spotify.com/authorize?' +
  22. auth_query_parameters.toString());
  23. });
  24.  
  25. app.get('/callback', (req, res) => {
  26. const code = req.query.code || null;
  27. const state = req.query.state || null;
  28.  
  29. const state_mismatch = new URLSearchParams({
  30. error: 'state_mismatch'
  31. });
  32.  
  33. if (state == null) {
  34. res.redirect('/#' +
  35. state_mismatch.toString());
  36. }
  37. else {
  38. const authOptions = {
  39. url: 'https://accounts.spotify.com/api/token',
  40. form: {
  41. code: code,
  42. redirect_uri: redirect_uri,
  43. grant_type: 'authorization_code'
  44. },
  45. headers: {
  46. 'Authorization': 'Basic ' + (Buffer.from(client_id + ':' + client_secret).toString('base64')),
  47. 'Content-Type': "application/x-www-form-urlencoded"
  48. },
  49. json: true
  50. };
  51. }
  52. });
  53.  
  54. app.listen(3000);
Add Comment
Please, Sign In to add comment