base_controller.rb 2.3 KB

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