spotify web setup is done
This commit is contained in:
@@ -1,4 +1,16 @@
|
||||
class ApplicationController < ActionController::Base
|
||||
# Only allow modern browsers supporting webp images, web push, badges, import maps, CSS nesting, and CSS :has.
|
||||
allow_browser versions: :modern
|
||||
|
||||
before_action :check_spotify_login
|
||||
|
||||
private
|
||||
|
||||
def check_spotify_login
|
||||
if user_signed_in? && current_user.logins.where(platform: "spotify").none?
|
||||
unless request.path == spotify_connect_path || request.path == spotify_path || request.path == spotify_callback_path || devise_controller?
|
||||
redirect_to spotify_path
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
57
app/controllers/spotify_controller.rb
Normal file
57
app/controllers/spotify_controller.rb
Normal file
@@ -0,0 +1,57 @@
|
||||
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)
|
||||
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
|
||||
Reference in New Issue
Block a user