class SpotifyController < ApplicationController before_action :authenticate_user! def index # If already connected, redirect to dashboard redirect_to statistics_path if current_user.logins.exists?(platform: "spotify") end def connect # If user already has a login, redirect to statistics dashboard return redirect_to statistics_path if current_user.logins.exists?(platform: "spotify") client_id = ENV["SPOTIFY_CLIENT_ID"] redirect_uri = SpotifyClient::SPOTIFY_REDIRECT_URI scope = SpotifyClient::SCOPE state = SecureRandom.hex(16) session[:spotify_auth_state] = state auth_url = "https://accounts.spotify.com/authorize?" + { client_id: client_id, response_type: "code", redirect_uri: redirect_uri, scope: scope, state: state }.to_query redirect_to auth_url, allow_other_host: true end def callback if params[:state] != session.delete(:spotify_auth_state) return redirect_to spotify_path, alert: "Invalid state parameter. Please try again." end if params[:code].present? if handle_spotify_callback(params[:code]) redirect_to statistics_path, notice: "Spotify authorization successful." else redirect_to spotify_path, alert: "Spotify authorization failed. Please try again." end else redirect_to spotify_path, alert: "Spotify authorization failed." end end private def handle_spotify_callback(code) begin token_response = SpotifyClient.new(current_user).token_response_from_code(code) Login.find_or_create_for_response!(current_user, token_response) LoadUserActivitiesJob.perform_later(current_user) true rescue RestClient::Exception, JSON::ParserError => e Rails.logger.error("Spotify callback error: #{e.class} - #{e.message}") false rescue StandardError => e Rails.logger.error("Unexpected Spotify callback error: #{e.class} - #{e.message}") false end end end