1

Trying to authenticate is seeing what user is currently logged in. I tried authenticating with a different spotify account but I still get mine. Not sure why. I am getting the token info after the user authenticates and get who the current user is but it always results in the same user even if I try to authenticate with a different one.

from flask import Flask, jsonify, redirect, request, session
from flask_cors import CORS, cross_origin
from flask_session import Session
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import os
from dotenv import load_dotenv
import time
import redis

# load environment variables
load_dotenv()

# run flask app and set up cors
app = Flask(__name__)
# generate random secret key
app.config['SECRET_KEY'] = os.urandom(24)
app.config['PERMANENT_SESSION_LIFETIME'] = 60 * 60 * 24 * 7
r = redis.Redis(host='localhost', port=6379, db=0)
CORS(app)

# sets up user credentials for spotify api
client_id = os.getenv("SPOTIFY_CLIENT_ID")
client_secret = os.getenv("SPOTIFY_CLIENT_SECRET")
redirect_uri = os.getenv("SPOTIFY_REDIRECT_URI")


# get all scopes
scopes = 'user-read-recently-played'

# authenticates user and sends react app to url
@app.route('/authenticate', methods=['GET'])
def authenticate_user():
    sp_oauth = spotipy.oauth2.SpotifyOAuth(client_id, client_secret, redirect_uri, scope=scopes, show_dialog=True)
    auth_url = sp_oauth.get_authorize_url()
    return jsonify({'url': auth_url})

# gets access token from spotify api
@app.route('/callback')
def callback():
    session.clear()
    sp_oauth = spotipy.oauth2.SpotifyOAuth(client_id, client_secret, redirect_uri, scope=scopes)
    code = request.args.get('code')
    token_info = sp_oauth.get_access_token(code)
    sp = spotipy.Spotify(auth=token_info['access_token'])
    user = sp.current_user()
    user_id = user['id']
    print(user_id)
    return redirect('http://localhost:3000/')

if __name__ == '__main__':
    app.run(host='localhost', port=5000, debug=True)

Abraham.
  • 69
  • 6
  • because you are logging in with the same user every time `client_id = os.getenv("SPOTIFY_CLIENT_ID") client_secret = os.getenv("SPOTIFY_CLIENT_SECRET") redirect_uri = os.getenv("SPOTIFY_REDIRECT_URI") ` – Ali Gökkaya Dec 23 '22 at 21:15
  • I'm not sure how to fix that though, how would I authenticate with a different user? – Abraham. Dec 24 '22 at 02:27
  • What @AliGökkaya says is not true. You can find working flask code here: [spotipy/app.js](https://github.com/spotipy-dev/spotipy/blob/master/examples/app.py) – Ximzend Dec 24 '22 at 17:14

0 Answers0