Skip to content

Commit

Permalink
Add ability to provide regexp instead of just substrings for exclude
Browse files Browse the repository at this point in the history
This is another go at eparreno#23,

Where we make it a little more flexible by allowing either the old
string version or a now newly introduced regxp.

This is fully backwards compatible.
  • Loading branch information
berkes committed Dec 1, 2021
1 parent 80e574f commit b31cb6a
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
19 changes: 14 additions & 5 deletions lib/rack/jwt/auth.rb
Original file line number Diff line number Diff line change
Expand Up @@ -152,22 +152,31 @@ def check_exclude_type!
end

@exclude.each do |x|
unless x.is_a?(String)
raise ArgumentError, 'each exclude Array element must be a String'
unless x.is_a?(String) || x.is_a?(Regexp)
raise ArgumentError, 'each exclude Array element must be a String or a Regexp'
end

if x.empty?
if x.to_s.empty?
raise ArgumentError, 'each exclude Array element must not be empty'
end

unless x.start_with?('/')
# Perhaps surprisingly, Regexp#inspect actually produces the more
# natural version of the string than #to_s.
as_s = x.is_a?(Regexp) ? x.inspect : x
unless as_s.start_with?('/')
raise ArgumentError, 'each exclude Array element must start with a /'
end
end
end

def path_matches_excluded_path?(env)
@exclude.any? { |ex| env['PATH_INFO'].start_with?(ex) }
@exclude.any? do |ex|
if ex.is_a?(Regexp)
ex.match?(env['PATH_INFO'])
else
env['PATH_INFO'].start_with?(ex)
end
end
end

def valid_auth_header?(env)
Expand Down
9 changes: 9 additions & 0 deletions spec/exclusion_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,15 @@
end
end

describe 'passes through matching regexp' do
let(:app) { Rack::JWT::Auth.new(inner_app, secret: secret, exclude: [/stati+/]) }

it 'returns a 200' do
get('/static')
expect(last_response.status).to eq 200
end
end

describe 'passes through matching exact path with trailing slash' do
let(:app) { Rack::JWT::Auth.new(inner_app, secret: secret, exclude: ['/static']) }

Expand Down

0 comments on commit b31cb6a

Please sign in to comment.