Having trouble storing Spotify API authentication token

82 views Asked by At

I'm creating a social media web app using Django REST Framework with react on the frontend and postgreSQL and I'm having trouble thinking of a way to store the user's Spotify authentication token. The problem is that the token gets stored in this spotify_callback view below and I have no way of associating the user with the token.

class spotify_callback(APIView):
    # permission_classes = (IsAuthenticated,)
    def get(self, request, format=None):
        code = request.GET.get('code')

        response = post('https://accounts.spotify.com/api/token', data={
            'grant_type': 'authorization_code',
            'code': code,
            'redirect_uri': REDIRECT_URI,
            'client_id': CLIENT_ID,
            'client_secret': CLIENT_SECRET
        }).json()

        access_token = response.get('access_token')
        token_type = response.get('token_type')
        refresh_token = response.get('refresh_token')
        expires_in = response.get('expires_in')
        error = response.get('error')

        update_or_create_user_tokens(
            self.request.user, access_token, token_type, expires_in, refresh_token)

        return redirect('http://localhost:3000/')

The source I pulled the Spotify authentication flow from didn't have any user authentication in their app, so they were able to make use of request.session. However, from my understanding, I can't use sessions because of user authentication so I've been using

permission_classes = (IsAuthenticated,)
...
self.request.user

to get the email of the user making the requests. So here is where I'm having trouble. Because this request is made by the spotify API after the user enters their valid spotify credentials and not a user, I can't use the two lines above so there's no way to track which user the token belongs to.

I tried using Django sessions for a while before I came to the conclusion that I couldn't use them with authenticated users. I also tried the permission classes like I said and it doesn't work because it's not an authenticated user making the request.

0

There are 0 answers