2018-05-11 11:49:12 +02:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class Api::V1::Push::SubscriptionsController < Api::BaseController
|
2024-05-06 14:41:14 +02:00
|
|
|
include Redisable
|
|
|
|
include Lockable
|
|
|
|
|
2018-05-11 11:49:12 +02:00
|
|
|
before_action -> { doorkeeper_authorize! :push }
|
|
|
|
before_action :require_user!
|
2024-05-06 14:41:14 +02:00
|
|
|
before_action :set_push_subscription, only: [:show, :update]
|
2021-04-15 05:00:25 +02:00
|
|
|
before_action :check_push_subscription, only: [:show, :update]
|
2018-05-11 11:49:12 +02:00
|
|
|
|
2023-04-30 06:46:39 +02:00
|
|
|
def show
|
|
|
|
render json: @push_subscription, serializer: REST::WebPushSubscriptionSerializer
|
|
|
|
end
|
|
|
|
|
2018-05-11 11:49:12 +02:00
|
|
|
def create
|
2024-05-06 14:41:14 +02:00
|
|
|
with_redis_lock("push_subscription:#{current_user.id}") do
|
|
|
|
destroy_web_push_subscriptions!
|
2018-05-11 11:49:12 +02:00
|
|
|
|
2024-05-06 14:41:14 +02:00
|
|
|
@push_subscription = Web::PushSubscription.create!(
|
|
|
|
endpoint: subscription_params[:endpoint],
|
|
|
|
key_p256dh: subscription_params[:keys][:p256dh],
|
|
|
|
key_auth: subscription_params[:keys][:auth],
|
|
|
|
data: data_params,
|
|
|
|
user_id: current_user.id,
|
|
|
|
access_token_id: doorkeeper_token.id
|
|
|
|
)
|
|
|
|
end
|
2018-05-11 11:49:12 +02:00
|
|
|
|
2021-04-15 05:00:25 +02:00
|
|
|
render json: @push_subscription, serializer: REST::WebPushSubscriptionSerializer
|
2018-05-11 11:49:12 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def update
|
2021-04-15 05:00:25 +02:00
|
|
|
@push_subscription.update!(data: data_params)
|
|
|
|
render json: @push_subscription, serializer: REST::WebPushSubscriptionSerializer
|
2018-05-11 11:49:12 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def destroy
|
2024-05-06 14:41:14 +02:00
|
|
|
destroy_web_push_subscriptions!
|
2018-05-11 11:49:12 +02:00
|
|
|
render_empty
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2024-05-06 14:41:14 +02:00
|
|
|
def destroy_web_push_subscriptions!
|
|
|
|
doorkeeper_token.web_push_subscriptions.destroy_all
|
|
|
|
end
|
|
|
|
|
2021-04-15 05:00:25 +02:00
|
|
|
def set_push_subscription
|
2024-05-06 14:41:14 +02:00
|
|
|
@push_subscription = doorkeeper_token.web_push_subscriptions.first
|
2018-05-11 11:49:12 +02:00
|
|
|
end
|
|
|
|
|
2021-04-15 05:00:25 +02:00
|
|
|
def check_push_subscription
|
|
|
|
not_found if @push_subscription.nil?
|
2020-05-03 16:30:36 +02:00
|
|
|
end
|
|
|
|
|
2018-05-11 11:49:12 +02:00
|
|
|
def subscription_params
|
|
|
|
params.require(:subscription).permit(:endpoint, keys: [:auth, :p256dh])
|
|
|
|
end
|
|
|
|
|
|
|
|
def data_params
|
|
|
|
return {} if params[:data].blank?
|
2020-05-03 16:30:36 +02:00
|
|
|
|
2022-06-23 01:44:27 +02:00
|
|
|
params.require(:data).permit(:policy, alerts: Notification::TYPES)
|
2018-05-11 11:49:12 +02:00
|
|
|
end
|
|
|
|
end
|