Module: Peel::ApiInclude

Defined in:
lib/peel/api_include.rb

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object


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
# File 'lib/peel/api_include.rb', line 5

def self.included(base)
  Peel.validate_secret_presence

  base.use Warden::Manager do |manager|
    manager.default_strategies :token
    manager.failure_app = lambda do |env|
      [401, {}, [{ error: 'Not authorized' }.to_json]]
    end
  end

  base.helpers do
    def warden
      env['warden']
    end
  end

  Warden::Strategies.add(:token) do
    def valid?
      request.env['HTTP_AUTHORIZATION'].present?
    end

    def authenticate!
      token = request.env['HTTP_AUTHORIZATION']
      user = Peel.authenticate_with_token(token)
      user.nil?  ? fail!('Unauthorized') : success!(user)
    end
  end
end