module Api module V1 class InvitationsController < BaseController skip_before_action :authenticate_request!, only: :show def show invitation = find_pending_invitation unless invitation return render json: { valid: false, error: "Invito non valido o scaduto" }, status: :not_found end render json: invitation_json(invitation).merge(valid: true) end def accept invitation = find_pending_invitation return render json: { error: "Invito non valido o scaduto" }, status: :not_found unless invitation email = invitation.email if current_user.email.downcase != email.downcase return render json: { error: "Questo invito รจ per #{email}. Accedi con quell'indirizzo email.", invited_email: email }, status: :unprocessable_entity end invitation.accept!(current_user) render json: invitation_json(invitation).merge(message: accept_message(invitation)) end private def find_pending_invitation token = params[:token].to_s return nil if token.blank? digest = Digest::SHA256.hexdigest(token) TeamInvitation.pending.find_by(token_digest: digest) || TournamentBroadcastInvitation.pending.find_by(token_digest: digest) end def invitation_json(invitation) if invitation.is_a?(TournamentBroadcastInvitation) tournament = invitation.tournament { email: invitation.email, tournament_id: tournament.id, tournament_name: tournament.name, club_name: tournament.club.name, team_id: tournament.broadcast_team_id, team_name: tournament.name, staff_kind: "transmission", expires_at: invitation.expires_at } else { email: invitation.email, team_id: invitation.team_id, team_name: invitation.team.name, club_name: invitation.team.club.name, staff_kind: invitation.staff_kind, expires_at: invitation.expires_at } end end def accept_message(invitation) if invitation.is_a?(TournamentBroadcastInvitation) "Sei incaricato delle dirette per #{invitation.tournament.name}." else "Sei entrato in #{invitation.team.name} come responsabile trasmissione." end end end end end