61 lines
1.8 KiB
Ruby
61 lines
1.8 KiB
Ruby
# frozen_string_literal: true
|
|
|
|
# El controlador desde el que descienden todos los controladores
|
|
class ApplicationController < ActionController::API
|
|
# authenticate! obtiene la pirata a partir de los datos de
|
|
# autenticacion y la pone en este atributo
|
|
attr_reader :current_pirata
|
|
|
|
# Vamos a usar HTTP Basic Auth
|
|
include ActionController::HttpAuthentication::Basic::ControllerMethods
|
|
|
|
private
|
|
|
|
def todas_menos_yo
|
|
Pirata.todas_menos(current_pirata)
|
|
end
|
|
|
|
def todas_menos_yo_ids
|
|
todas_menos_yo.pluck(:id)
|
|
end
|
|
|
|
# Enviar notificaciones
|
|
#
|
|
# Necesita que el controlador defina
|
|
#
|
|
# #get_subject(:symbol)
|
|
# #get_message(:symbol)
|
|
# #get_endpoint(:symbol)
|
|
#
|
|
# @param :subject [Symbol|String] Título del mensaje para I18n
|
|
# @param :urgency [Symbol] Nivel de urgencia
|
|
def notify(subject:, urgency: :normal, ttl: 7.days)
|
|
payload = { subject: get_subject(subject),
|
|
message: get_message(subject),
|
|
endpoint: get_endpoint(subject) }
|
|
|
|
WebpushJob.perform_later(piratas: todas_menos_yo_ids,
|
|
ttl: ttl.to_i,
|
|
urgency: urgency.to_s,
|
|
payload: WebpushPayload.new(payload).to_json)
|
|
|
|
TelegramJob.perform_later(piratas: todas_menos_yo_ids,
|
|
payload: payload.to_json)
|
|
end
|
|
|
|
# Autenticar a la pirata usando HTTP Basic Auth
|
|
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication
|
|
def authenticate!
|
|
@current_pirata ||= authenticate_with_http_basic do |email, password|
|
|
pirata = Pirata.find_by_email(email)
|
|
|
|
if pirata&.authenticate(password)
|
|
session[:pirata_id] = pirata.id
|
|
pirata
|
|
end
|
|
end
|
|
|
|
# Si no la encuentra, no nos deja hacer nada
|
|
render(json: {}, status: :forbidden) unless current_pirata
|
|
end
|
|
end
|