ip_blocks_controller.rb 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. # frozen_string_literal: true
  2. class Api::V1::Admin::IpBlocksController < Api::BaseController
  3. include Authorization
  4. include AccountableConcern
  5. LIMIT = 100
  6. before_action -> { authorize_if_got_token! :'admin:read', :'admin:read:ip_blocks' }, only: [:index, :show]
  7. before_action -> { authorize_if_got_token! :'admin:write', :'admin:write:ip_blocks' }, except: [:index, :show]
  8. before_action :set_ip_blocks, only: :index
  9. before_action :set_ip_block, only: [:show, :update, :destroy]
  10. after_action :verify_authorized
  11. after_action :insert_pagination_headers, only: :index
  12. PAGINATION_PARAMS = %i(
  13. limit
  14. ).freeze
  15. def create
  16. authorize :ip_block, :create?
  17. @ip_block = IpBlock.create!(resource_params)
  18. log_action :create, @ip_block
  19. render json: @ip_block, serializer: REST::Admin::IpBlockSerializer
  20. end
  21. def index
  22. authorize :ip_block, :index?
  23. render json: @ip_blocks, each_serializer: REST::Admin::IpBlockSerializer
  24. end
  25. def show
  26. authorize @ip_block, :show?
  27. render json: @ip_block, serializer: REST::Admin::IpBlockSerializer
  28. end
  29. def update
  30. authorize @ip_block, :update?
  31. @ip_block.update(resource_params)
  32. log_action :update, @ip_block
  33. render json: @ip_block, serializer: REST::Admin::IpBlockSerializer
  34. end
  35. def destroy
  36. authorize @ip_block, :destroy?
  37. @ip_block.destroy!
  38. log_action :destroy, @ip_block
  39. render json: @ip_block, serializer: REST::Admin::IpBlockSerializer
  40. end
  41. private
  42. def set_ip_blocks
  43. @ip_blocks = IpBlock.order(id: :desc).to_a_paginated_by_id(limit_param(LIMIT), params_slice(:max_id, :since_id, :min_id))
  44. end
  45. def set_ip_block
  46. @ip_block = IpBlock.find(params[:id])
  47. end
  48. def resource_params
  49. params.permit(:ip, :severity, :comment, :expires_in)
  50. end
  51. def insert_pagination_headers
  52. set_pagination_headers(next_path, prev_path)
  53. end
  54. def next_path
  55. api_v1_admin_ip_blocks_url(pagination_params(max_id: pagination_max_id)) if records_continue?
  56. end
  57. def prev_path
  58. api_v1_admin_ip_blocks_url(pagination_params(min_id: pagination_since_id)) unless @ip_blocks.empty?
  59. end
  60. def pagination_max_id
  61. @ip_blocks.last.id
  62. end
  63. def pagination_since_id
  64. @ip_blocks.first.id
  65. end
  66. def records_continue?
  67. @ip_blocks.size == limit_param(LIMIT)
  68. end
  69. def pagination_params(core_params)
  70. params.slice(*PAGINATION_PARAMS).permit(*PAGINATION_PARAMS).merge(core_params)
  71. end
  72. end