base_controller.rb 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. # frozen_string_literal: true
  2. class Api::BaseController < ApplicationController
  3. DEFAULT_STATUSES_LIMIT = 20
  4. DEFAULT_ACCOUNTS_LIMIT = 40
  5. include RateLimitHeaders
  6. skip_before_action :store_current_location
  7. protect_from_forgery with: :null_session
  8. rescue_from ActiveRecord::RecordInvalid, Mastodon::ValidationError do |e|
  9. render json: { error: e.to_s }, status: 422
  10. end
  11. rescue_from ActiveRecord::RecordNotFound do
  12. render json: { error: 'Record not found' }, status: 404
  13. end
  14. rescue_from HTTP::Error, Mastodon::UnexpectedResponseError do
  15. render json: { error: 'Remote data could not be fetched' }, status: 503
  16. end
  17. rescue_from OpenSSL::SSL::SSLError do
  18. render json: { error: 'Remote SSL certificate could not be verified' }, status: 503
  19. end
  20. rescue_from Mastodon::NotPermittedError do
  21. render json: { error: 'This action is not allowed' }, status: 403
  22. end
  23. def doorkeeper_unauthorized_render_options(error: nil)
  24. { json: { error: (error.try(:description) || 'Not authorized') } }
  25. end
  26. def doorkeeper_forbidden_render_options(*)
  27. { json: { error: 'This action is outside the authorized scopes' } }
  28. end
  29. protected
  30. def set_pagination_headers(next_path = nil, prev_path = nil)
  31. links = []
  32. links << [next_path, [%w(rel next)]] if next_path
  33. links << [prev_path, [%w(rel prev)]] if prev_path
  34. response.headers['Link'] = LinkHeader.new(links) unless links.empty?
  35. end
  36. def limit_param(default_limit)
  37. return default_limit unless params[:limit]
  38. [params[:limit].to_i.abs, default_limit * 2].min
  39. end
  40. def truthy_param?(key)
  41. ActiveModel::Type::Boolean.new.cast(params[key])
  42. end
  43. def current_resource_owner
  44. @current_user ||= User.find(doorkeeper_token.resource_owner_id) if doorkeeper_token
  45. end
  46. def current_user
  47. current_resource_owner || super
  48. rescue ActiveRecord::RecordNotFound
  49. nil
  50. end
  51. def require_user!
  52. if current_user && !current_user.disabled?
  53. set_user_activity
  54. elsif current_user
  55. render json: { error: 'Your login is currently disabled' }, status: 403
  56. else
  57. render json: { error: 'This method requires an authenticated user' }, status: 422
  58. end
  59. end
  60. def render_empty
  61. render json: {}, status: 200
  62. end
  63. def authorize_if_got_token!(*scopes)
  64. doorkeeper_authorize!(*scopes) if doorkeeper_token
  65. end
  66. end