You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

89 lines
2.4 KiB

  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 params_slice(*keys)
  42. params.slice(*keys).permit(*keys)
  43. end
  44. def current_resource_owner
  45. @current_user ||= User.find(doorkeeper_token.resource_owner_id) if doorkeeper_token
  46. end
  47. def current_user
  48. current_resource_owner || super
  49. rescue ActiveRecord::RecordNotFound
  50. nil
  51. end
  52. def require_user!
  53. if !current_user
  54. render json: { error: 'This method requires an authenticated user' }, status: 422
  55. elsif current_user.disabled?
  56. render json: { error: 'Your login is currently disabled' }, status: 403
  57. elsif !current_user.confirmed?
  58. render json: { error: 'Email confirmation is not completed' }, status: 403
  59. else
  60. set_user_activity
  61. end
  62. end
  63. def render_empty
  64. render json: {}, status: 200
  65. end
  66. def authorize_if_got_token!(*scopes)
  67. doorkeeper_authorize!(*scopes) if doorkeeper_token
  68. end
  69. end