subscriptions_controller.rb 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # frozen_string_literal: true
  2. class Api::V1::Push::SubscriptionsController < Api::BaseController
  3. before_action -> { doorkeeper_authorize! :push }
  4. before_action :require_user!
  5. before_action :set_push_subscription
  6. before_action :check_push_subscription, only: [:show, :update]
  7. def show
  8. render json: @push_subscription, serializer: REST::WebPushSubscriptionSerializer
  9. end
  10. def create
  11. @push_subscription&.destroy!
  12. @push_subscription = Web::PushSubscription.create!(
  13. endpoint: subscription_params[:endpoint],
  14. key_p256dh: subscription_params[:keys][:p256dh],
  15. key_auth: subscription_params[:keys][:auth],
  16. data: data_params,
  17. user_id: current_user.id,
  18. access_token_id: doorkeeper_token.id
  19. )
  20. render json: @push_subscription, serializer: REST::WebPushSubscriptionSerializer
  21. end
  22. def update
  23. @push_subscription.update!(data: data_params)
  24. render json: @push_subscription, serializer: REST::WebPushSubscriptionSerializer
  25. end
  26. def destroy
  27. @push_subscription&.destroy!
  28. render_empty
  29. end
  30. private
  31. def set_push_subscription
  32. @push_subscription = Web::PushSubscription.find_by(access_token_id: doorkeeper_token.id)
  33. end
  34. def check_push_subscription
  35. not_found if @push_subscription.nil?
  36. end
  37. def subscription_params
  38. params.require(:subscription).permit(:endpoint, keys: [:auth, :p256dh])
  39. end
  40. def data_params
  41. return {} if params[:data].blank?
  42. params.require(:data).permit(:policy, alerts: Notification::TYPES)
  43. end
  44. end