Files
MatchLiveTv/backend/app/controllers/api/v1/youtube_controller.rb
Emiliano Frascaro 994c1e3c09 Integrazione YouTube Live: OAuth squadra, canale piattaforma Light e UI.
Collegamento da Dettagli squadra e admin per il refresh token Match Live TV; API e app mobile allineate ai piani Light/Full.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-02 19:36:56 +02:00

72 lines
2.5 KiB
Ruby

module Api
module V1
class YoutubeController < BaseController
include ActionController::Cookies
skip_before_action :authenticate_request!, only: :callback
def authorize
team = current_user.manageable_teams.find(params[:team_id])
team.entitlements.assert_can_connect_youtube!
state = Youtube::OauthState.for_team(team_id: team.id, user_id: current_user.id)
url = Youtube::OauthUrl.build(state: state, redirect_uri: ENV.fetch("YOUTUBE_REDIRECT_URI"))
render json: { authorization_url: url }
end
def callback
return redirect_to_oauth_error("Codice OAuth mancante") if params[:code].blank?
ctx = Youtube::OauthState.verify!(params[:state])
tokens = Youtube::OauthExchange.call(params[:code])
if ctx[:kind] == :platform
unless platform_oauth_authorized?(ctx[:admin_id])
return redirect_to "#{admin_base_url}/login", alert: "Sessione admin richiesta", allow_other_host: true
end
return render_platform_token(tokens)
end
user = User.find(ctx[:user_id])
team = user.manageable_teams.find(ctx[:team_id])
cred = team.youtube_credential || team.build_youtube_credential
cred.update!(
access_token: tokens[:access_token],
refresh_token: tokens[:refresh_token] || cred.refresh_token,
expires_at: Time.current + tokens[:expires_in].seconds,
channel_id: tokens[:channel_id],
channel_title: tokens[:channel_title]
)
redirect_to "#{public_base_url}/teams/#{team.id}/dettagli?youtube=connected", allow_other_host: true
rescue ArgumentError, Youtube::BroadcastService::Error => e
redirect_to_oauth_error(e.message)
end
private
def public_base_url
MatchLiveTv.app_public_url.chomp("/")
end
def redirect_to_oauth_error(message)
redirect_to "#{public_base_url}/prezzi?youtube_error=#{ERB::Util.url_encode(message)}",
allow_other_host: true
end
def render_platform_token(tokens)
@refresh_token = tokens[:refresh_token]
@channel_title = tokens[:channel_title]
render "admin/youtube/platform_token", layout: "admin"
end
def platform_oauth_authorized?(admin_id)
session[:admin_account_id].present? && session[:admin_account_id].to_s == admin_id.to_s
end
def admin_base_url
"#{public_base_url}/admin"
end
end
end
end