1
0

subscriptions_controller.rb 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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_web_push_subscription
  6. def create
  7. @web_subscription&.destroy!
  8. @web_subscription = ::Web::PushSubscription.create!(
  9. endpoint: subscription_params[:endpoint],
  10. key_p256dh: subscription_params[:keys][:p256dh],
  11. key_auth: subscription_params[:keys][:auth],
  12. data: data_params,
  13. user_id: current_user.id,
  14. access_token_id: doorkeeper_token.id
  15. )
  16. render json: @web_subscription, serializer: REST::WebPushSubscriptionSerializer
  17. end
  18. def show
  19. raise ActiveRecord::RecordNotFound if @web_subscription.nil?
  20. render json: @web_subscription, serializer: REST::WebPushSubscriptionSerializer
  21. end
  22. def update
  23. raise ActiveRecord::RecordNotFound if @web_subscription.nil?
  24. @web_subscription.update!(data: data_params)
  25. render json: @web_subscription, serializer: REST::WebPushSubscriptionSerializer
  26. end
  27. def destroy
  28. @web_subscription&.destroy!
  29. render_empty
  30. end
  31. private
  32. def set_web_push_subscription
  33. @web_subscription = ::Web::PushSubscription.find_by(access_token_id: doorkeeper_token.id)
  34. end
  35. def subscription_params
  36. params.require(:subscription).permit(:endpoint, keys: [:auth, :p256dh])
  37. end
  38. def data_params
  39. return {} if params[:data].blank?
  40. params.require(:data).permit(alerts: [:follow, :favourite, :reblog, :mention])
  41. end
  42. end