about summary refs log tree commit diff
path: root/app/controllers/api/v1/admin/domain_allows_controller.rb
blob: 0658199f0fc16d99e57b44c29d8f7b8c5c0a2135 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# frozen_string_literal: true

class Api::V1::Admin::DomainAllowsController < Api::BaseController
  include Authorization
  include AccountableConcern

  LIMIT = 100

  before_action -> { authorize_if_got_token! :'admin:read', :'admin:read:domain_allows' }, only: [:index, :show]
  before_action -> { authorize_if_got_token! :'admin:write', :'admin:write:domain_allows' }, except: [:index, :show]
  before_action :set_domain_allows, only: :index
  before_action :set_domain_allow, only: [:show, :destroy]

  after_action :verify_authorized
  after_action :insert_pagination_headers, only: :index

  PAGINATION_PARAMS = %i(limit).freeze

  def create
    authorize :domain_allow, :create?

    @domain_allow = DomainAllow.find_by(resource_params)

    if @domain_allow.nil?
      @domain_allow = DomainAllow.create!(resource_params)
      log_action :create, @domain_allow
    end

    render json: @domain_allow, serializer: REST::Admin::DomainAllowSerializer
  end

  def index
    authorize :domain_allow, :index?
    render json: @domain_allows, each_serializer: REST::Admin::DomainAllowSerializer
  end

  def show
    authorize @domain_allow, :show?
    render json: @domain_allow, serializer: REST::Admin::DomainAllowSerializer
  end

  def destroy
    authorize @domain_allow, :destroy?
    UnallowDomainService.new.call(@domain_allow)
    log_action :destroy, @domain_allow
    render_empty
  end

  private

  def set_domain_allows
    @domain_allows = filtered_domain_allows.order(id: :desc).to_a_paginated_by_id(limit_param(LIMIT), params_slice(:max_id, :since_id, :min_id))
  end

  def set_domain_allow
    @domain_allow = DomainAllow.find(params[:id])
  end

  def filtered_domain_allows
    # TODO: no filtering yet
    DomainAllow.all
  end

  def insert_pagination_headers
    set_pagination_headers(next_path, prev_path)
  end

  def next_path
    api_v1_admin_domain_allows_url(pagination_params(max_id: pagination_max_id)) if records_continue?
  end

  def prev_path
    api_v1_admin_domain_allows_url(pagination_params(min_id: pagination_since_id)) unless @domain_allows.empty?
  end

  def pagination_max_id
    @domain_allows.last.id
  end

  def pagination_since_id
    @domain_allows.first.id
  end

  def records_continue?
    @domain_allows.size == limit_param(LIMIT)
  end

  def pagination_params(core_params)
    params.slice(*PAGINATION_PARAMS).permit(*PAGINATION_PARAMS).merge(core_params)
  end

  def resource_params
    params.permit(:domain)
  end
end