about summary refs log tree commit diff
path: root/app/controllers/api/v1
diff options
context:
space:
mode:
authorEugen Rochko <eugen@zeonfederated.com>2018-05-11 11:49:12 +0200
committerGitHub <noreply@github.com>2018-05-11 11:49:12 +0200
commitb4fb766b23f4b50b51a366f55b451770ece3153a (patch)
treef3089da3ee1d3d937525a227136a739a451caad9 /app/controllers/api/v1
parent9a794067f77d936783736574640b1238bb8e6b18 (diff)
Add REST API for Web Push Notifications subscriptions (#7445)
- POST /api/v1/push/subscription
- PUT /api/v1/push/subscription
- DELETE /api/v1/push/subscription
- New OAuth scope: "push" (required for the above methods)
Diffstat (limited to 'app/controllers/api/v1')
-rw-r--r--app/controllers/api/v1/push/subscriptions_controller.rb50
1 files changed, 50 insertions, 0 deletions
diff --git a/app/controllers/api/v1/push/subscriptions_controller.rb b/app/controllers/api/v1/push/subscriptions_controller.rb
new file mode 100644
index 000000000..5038cc03c
--- /dev/null
+++ b/app/controllers/api/v1/push/subscriptions_controller.rb
@@ -0,0 +1,50 @@
+# frozen_string_literal: true
+
+class Api::V1::Push::SubscriptionsController < Api::BaseController
+  before_action -> { doorkeeper_authorize! :push }
+  before_action :require_user!
+  before_action :set_web_push_subscription
+
+  def create
+    @web_subscription&.destroy!
+
+    @web_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
+    )
+
+    render json: @web_subscription, serializer: REST::WebPushSubscriptionSerializer
+  end
+
+  def update
+    raise ActiveRecord::RecordNotFound if @web_subscription.nil?
+
+    @web_subscription.update!(data: data_params)
+
+    render json: @web_subscription, serializer: REST::WebPushSubscriptionSerializer
+  end
+
+  def destroy
+    @web_subscription&.destroy!
+    render_empty
+  end
+
+  private
+
+  def set_web_push_subscription
+    @web_subscription = ::Web::PushSubscription.find_by(access_token_id: doorkeeper_token.id)
+  end
+
+  def subscription_params
+    params.require(:subscription).permit(:endpoint, keys: [:auth, :p256dh])
+  end
+
+  def data_params
+    return {} if params[:data].blank?
+    params.require(:data).permit(alerts: [:follow, :favourite, :reblog, :mention])
+  end
+end