last day (15 days later) » 

8:28 PM
0
Q: Auth code failing when requiring data from another js file. But works when inside same file - why?

Marcooz2007I have an app which requires credentials from Spotify. I am using a template (https://github.com/firebase/functions-samples/tree/master/spotify-auth) to sign in via Spotify but I am changing it so that the spotify client id and client secret credentials are retrieved from the Firestore database. ...

 
What's the console output and error message?
 
The error message is { [WebapiError: Bad Request] name: 'WebapiError', message: 'Bad Request', statusCode: 400 }
This is despite the auth code actually working on Postman. So I am really unsure what's causing the Bad Request. The only thing that has changed from the original version is using 'spotify.then(Spotify...' instead of just having 'Spotify.authorizationCodeGrant(req.query.code, (error, data) => { if (error) { throw error; }'
 
But I mean you have a lot of console messages which might help us trace the logic. Are the client ID and secret actually logged correctly? Just eye-balling the code, let client_id = JSON.stringify(snapshot.data().client_id); looks suspicious. It's been a while since I used firebase but I'd expect to use snapshot.val() or possibly snapshot.toJSON(). firebase.google.com/docs/reference/js/…
 
Just added a picture (with hidden secrets) to the question. They are both logged correctly - in postman I use the same as them (in 64bit encoding) and they work fine. I'll try changing the let client_id to both of your suggestions now
Ah, I remember why I put it as snapshot.data().client_id now. It's because for firestore (not realtime firebase) that's what you have to write to access the values. Putting val() doesn't seem to work
 
Weird. Why do the ID/secret need to be stringified? Also, is there a reason you're requiring SpotifyWebApi in the index? And what happens if you log out Spotify.getAccessToken() from the index?
 
8:28 PM
I'm glad someone agrees! They apparently don't need to be stringified. And I have taken SpotifyWebApi out of index as you're right its not doing any good there... As for what logging the Spotify.getAccessToken, I get "undefined" as the result
 
wait, Spotify.getAccessToken() is undefined from the index? Despite logging out the correct values before?
oh, sorry, I meant Spotify.getClientId()
 
thanks for chatting, you're helping me keep the faith! I had already tried to log the client id and secret ids in the token function in my last code which I scrapped to start from scratch. They seemed to log fine, will double check now
Yes, just checked - it logs both the secret and id then the next log is the 'Unhandled rejection' followed by the 'Bad Request'. I assume the Unhandled rejection is the same as the bad request but I'm not entirely sure on that one
 
8:49 PM
have you tried putting a catch after spotify.then()? just to confirm or possibly get more info? (it really does look like the creds are coming back OK...)
 
try {
spotify.then(Spotify =>{
console.log('This is the access token: ' + Spotify.getAccessToken());
console.log('This is the client id: ' + Spotify.getClientId());
console.log('This is the client secret: ' + Spotify.getClientSecret());
Spotify.authorizationCodeGrant(req.query.code, (error, data) => {
if (error) {
throw error;
}
console.log('Received Access Token:', data.body['access_token']);
Spotify.setAccessToken(data.body['access_token']);

Spotify.getMe(async (error, userResults) => {
if (error) {
is this what you had in mind? or did were you thinking of a different catch area?
It hasn't had any effect I'm afraid
And yes, I agree that it is being sent the right client id and secret - I have no idea why it is still having invalid auth code problems
It's a real mystery!
 
Spotify.then(
// ...    stuff
).catch(err => {
      console.log('Spotify auth failed!', err)
    })
I meant more like that -- chaining .catch on the promise rather than an actual catch block
I'm dying to know wtf is causing it now
 
9:06 PM
Ah I see, yes you and I both!
exports.token = functions.https.onRequest((req, res) => {
try {

cookieParser()(req, res, () => {
console.log('Received verification state:', req.cookies.state);
console.log('Received state:', req.query.state);
if (!req.cookies.state) {
throw new Error('State cookie not set or expired. Maybe you took too long to authorize. Please try again.');
} else if (req.cookies.state !== req.query.state) {
throw new Error('State validation failed');
}
console.log('Received auth code:', req.query.code);
const spotify = require('./spotify');
will see what the above outputs^
That doesn't look clear at all, is there a way to send pictures on here?
might be clearer
The catch that I put in had no effect on the console.log but I think maybe that's because the code crashes before it reads it
 
yeah your catch may be in the wrong place? no idea, think you can use code formatting somehow though
"fixed font"
 
exports.token = functions.https.onRequest((req, res) => {
  try {

    cookieParser()(req, res, () => {
      console.log('Received verification state:', req.cookies.state);
      console.log('Received state:', req.query.state);
      if (!req.cookies.state) {
        throw new Error('State cookie not set or expired. Maybe you took too long to authorize. Please try again.');
      } else if (req.cookies.state !== req.query.state) {
        throw new Error('State validation failed');
      }
      console.log('Received auth code:', req.query.code);
good spot! Ok where would you move the catch to? Tbh I've never used a catch without a try so I am confused where it should go
 
I think that's right, actually -- so no 'spotify auth failed' message? That should mean the error isn't in your then function
I feel like catching the promise rejection would be a good step
 
nope, no spotify auth message
how does one do that?
Spotify.authorizationCodeGrant(req.query.code, (error, data) => {
          if (error) {
            throw error;
          }
this error here is the one which is logged
 
so if you log something in that if (error) block it logs out?
Spotify.authorizationCodeGrant(req.query.code, (error, data) => {
          if (error) {
            console.log('foo')
            throw error;
          }
 
9:20 PM
yes that's right
I tried that earlier but ill try again now
I also tried using the web api node's version of the authorisation grant but had the same problem there
// The code that's returned as a query parameter to the redirect URI
var code = 'MQCbtKe23z7YzzS44KzZzZgjQa621hgSzHN';

// Retrieve an access token and a refresh token
spotifyApi.authorizationCodeGrant(code).then(
  function(data) {
    console.log('The token expires in ' + data.body['expires_in']);
    console.log('The access token is ' + data.body['access_token']);
    console.log('The refresh token is ' + data.body['refresh_token']);

    // Set the access token on the API object to use it in later calls
 
1
Q: spotify-web-api-node: authorizationCodeGrant() give a 400 - Bad Request

user7383906I use the npm module spotify-web-api-node to use the Spotify Web API without having a ton of code to write. I followed the example given here to get an Authorization Code from Spotify. Then, I use this code to get an Access Token and a Refresh Token from Spotify and perform all the actions I wan...

I really hope it's this
 
I haven't changed my redirect uri from the original version (where it worked)
but I feel like it might be something to do with this
I just don't know what
since it's the exact same as the Spotify app's redirect uri
 
redirectUri should be redirect_uri maybe?
 
oo that's a good idea
In that example you just linked none of them have the underscore
the client id secret and redirect
I'll fiddle around with them
Illegal redirect_uri
is what I get when putting redirect_uri
 
haha ... should the others be camelcase as well then? definitely seems weird to have both
 
9:33 PM
yeah trying that now
ahh we're back to bad request
although interestingly
oh wait
no, nothing interesting new to report lol
thought it was a different error section but its still the same bit
could it be anything to do with the popup.html not being able to access something it could access when the spotify credentials were in the same class?
<!doctype html>
<!--
  Copyright 2016 Google Inc. All rights reserved.
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at
      apache.org/licenses/LICENSE-2.0
  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
that's the popup.html code^
It seems to get the auth code so maybe its getting it wrong. Although that doesn't match up with the auth code actually working in postman
 
can't imagine it's the client's fault (but at this point...) -- could it be some weird character/added quote mark/whitespace in the firestore values or something?
 
ah yes I thought that too
 
please find the cause and answer your question, I need closure
 
I even thought I'd cracked it when I noticed I had to delete one space to use it in postman
haha
I need to be able to hand in my project lol
 
sod your project, give me my closure!
 
9:45 PM
but yeah when I used a regex function to remove the whitespace I found that everything on the firebase logs has that one extra space
 
best of luck! and have a good night
 
hahah I'll try my best
thanks for the help!
 
10:25 PM
what happens if you remove regexIdAndSecret and pass the values directly? I have a feeling you're actually using RegExp match values which when logged out appear to be strings
 
10:52 PM
I've just set it up as within the same class and its not working there now
But there's now an error message on the authorizationCodeGrant method
var SpotifyWebApi = require('spotify-web-api-node');
var credentials = {
    clientId: '1a313450afc74bd4a4ed6c83b1561781',
    clientSecret: '25f9d28005f84d88a593f9c586b2ef89',
    redirectUri: 'https://moodmagictherapy2-rhjhig.firebaseapp.com/popup.html'
};

var spotifyApi = new SpotifyWebApi(credentials);
/**
 * Exchanges a given Spotify auth code passed in the 'code' URL query parameter for a Firebase auth token.
 * The request also needs to specify a 'state' query parameter which will be checked against the 'state' cookie.
Says its an unresolved function so maybe that's it?
not sure how its unresolved though
I'll try your suggestion too
(although now I've gone back to the code as it was before, that error message no longer exists)
Just tried it, no luck I'm afraid :(
Reaching the end of my mental ability with this lol
Will keep trying... if any ideas spring to mind let me know
Also its probably worth mentioning that I only want other Spotify account holders to be able to use my Google app (which works with Spotify's api). I find it hard to believe that every user who wants to use my app has to make an app on spotify to get their client id and client secret but that's why Im trying to make sure that they can do this and store it on fire cloud. BUT if you happen to know how to get around this, that too would save this project! haha
 

last day (15 days later) »