about summary refs log tree commit diff
path: root/spec/controllers/api/base_controller_spec.rb
blob: c286b8cbfc3d895891bf1747f814034c706d3942 (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
# frozen_string_literal: true

require 'rails_helper'

class FakeService; end

describe Api::BaseController do
  controller do
    def success
      head 200
    end

    def error
      FakeService.new
    end
  end

  describe 'forgery protection' do
    before do
      routes.draw { post 'success' => 'api/base#success' }
    end

    it 'does not protect from forgery' do
      ActionController::Base.allow_forgery_protection = true
      post 'success'
      expect(response).to have_http_status(200)
    end
  end

  describe 'non-functional accounts handling' do
    let(:user)  { Fabricate(:user) }
    let(:token) { Fabricate(:accessible_access_token, resource_owner_id: user.id, scopes: 'read') }

    controller do
      before_action :require_user!
    end

    before do
      routes.draw { post 'success' => 'api/base#success' }
      allow(controller).to receive(:doorkeeper_token) { token }
    end

    it 'returns http forbidden for unconfirmed accounts' do
      user.update(confirmed_at: nil)
      post 'success'
      expect(response).to have_http_status(403)
    end

    it 'returns http forbidden for pending accounts' do
      user.update(approved: false)
      post 'success'
      expect(response).to have_http_status(403)
    end

    it 'returns http forbidden for disabled accounts' do
      user.update(disabled: true)
      post 'success'
      expect(response).to have_http_status(403)
    end

    it 'returns http forbidden for suspended accounts' do
      user.account.suspend!
      post 'success'
      expect(response).to have_http_status(403)
    end
  end

  describe 'error handling' do
    ERRORS_WITH_CODES = {
      ActiveRecord::RecordInvalid => 422,
      Mastodon::ValidationError => 422,
      ActiveRecord::RecordNotFound => 404,
      Mastodon::UnexpectedResponseError => 503,
      HTTP::Error => 503,
      OpenSSL::SSL::SSLError => 503,
      Mastodon::NotPermittedError => 403,
    }

    before do
      routes.draw { get 'error' => 'api/base#error' }
    end

    ERRORS_WITH_CODES.each do |error, code|
      it "Handles error class of #{error}" do
        expect(FakeService).to receive(:new).and_raise(error)

        get 'error'
        expect(response).to have_http_status(code)
      end
    end
  end
end