push_subscriptions_controller.rb 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # frozen_string_literal: true
  2. class Api::Web::PushSubscriptionsController < Api::Web::BaseController
  3. before_action :require_user!
  4. before_action :set_push_subscription, only: :update
  5. before_action :destroy_previous_subscriptions, only: :create, if: :prior_subscriptions?
  6. after_action :update_session_with_subscription, only: :create
  7. def create
  8. @push_subscription = ::Web::PushSubscription.create!(web_push_subscription_params)
  9. render json: @push_subscription, serializer: REST::WebPushSubscriptionSerializer
  10. end
  11. def update
  12. @push_subscription.update!(data: data_params)
  13. render json: @push_subscription, serializer: REST::WebPushSubscriptionSerializer
  14. end
  15. private
  16. def active_session
  17. @active_session ||= current_session
  18. end
  19. def destroy_previous_subscriptions
  20. active_session.web_push_subscription.destroy!
  21. active_session.update!(web_push_subscription: nil)
  22. end
  23. def prior_subscriptions?
  24. active_session.web_push_subscription.present?
  25. end
  26. def subscription_data
  27. default_subscription_data.tap do |data|
  28. data.deep_merge!(data_params) if params[:data]
  29. end
  30. end
  31. def default_subscription_data
  32. {
  33. policy: 'all',
  34. alerts: Notification::TYPES.index_with { alerts_enabled },
  35. }
  36. end
  37. def alerts_enabled
  38. # Mobile devices do not support regular notifications, so we enable push notifications by default
  39. active_session.detection.device.mobile? || active_session.detection.device.tablet?
  40. end
  41. def update_session_with_subscription
  42. active_session.update!(web_push_subscription: @push_subscription)
  43. end
  44. def set_push_subscription
  45. @push_subscription = ::Web::PushSubscription.find(params[:id])
  46. end
  47. def subscription_params
  48. @subscription_params ||= params.require(:subscription).permit(:endpoint, keys: [:auth, :p256dh])
  49. end
  50. def web_push_subscription_params
  51. {
  52. access_token_id: active_session.access_token_id,
  53. data: subscription_data,
  54. endpoint: subscription_params[:endpoint],
  55. key_auth: subscription_params[:keys][:auth],
  56. key_p256dh: subscription_params[:keys][:p256dh],
  57. user_id: active_session.user_id,
  58. }
  59. end
  60. def data_params
  61. @data_params ||= params.require(:data).permit(:policy, alerts: Notification::TYPES)
  62. end
  63. end