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 create
  8. @push_subscription&.destroy!
  9. @push_subscription = Web::PushSubscription.create!(
  10. endpoint: subscription_params[:endpoint],
  11. key_p256dh: subscription_params[:keys][:p256dh],
  12. key_auth: subscription_params[:keys][:auth],
  13. data: data_params,
  14. user_id: current_user.id,
  15. access_token_id: doorkeeper_token.id
  16. )
  17. render json: @push_subscription, serializer: REST::WebPushSubscriptionSerializer
  18. end
  19. def show
  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