Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion lib/mantle-api-ruby.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class MantleClient
# @raise [ArgumentError] If api_key is used in Rails frontend
def initialize(app_id:, api_key: nil, customer_api_token: nil, api_url: 'https://appapi.heymantle.com/v1')
raise ArgumentError, 'MantleClient app_id is required' unless app_id
raise ArgumentError, 'MantleClient apiKey should never be used in the browser' if defined?(Rails) && api_key
raise ArgumentError, 'MantleClient apiKey should never be used in the browser' if used_in_frontend? && api_key
raise ArgumentError, 'MantleClient one of apiKey or customerApiToken is required' unless api_key || customer_api_token

@app_id = app_id
Expand Down Expand Up @@ -273,4 +273,13 @@ def usage_metric_report(id: nil, customer_id: nil, period: 'daily', start_date:

mantle_request(path: path, method: 'GET')
end

private

# Check if the code is running in an ERB template
#
# @return [Boolean] True if running in an ERB template, false otherwise
def used_in_frontend?
caller.any? { |line| line.include?('erb') || line.include?('template') }
end
end
7 changes: 7 additions & 0 deletions spec/client_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,13 @@
MantleClient.new(app_id: app_id)
}.to raise_error(ArgumentError, 'MantleClient one of apiKey or customerApiToken is required')
end

it 'raises error when api_key is used in Rails frontend' do
allow_any_instance_of(MantleClient).to receive(:used_in_frontend?).and_return(true)
expect {
MantleClient.new(app_id: app_id, api_key: api_key)
}.to raise_error(ArgumentError, 'MantleClient apiKey should never be used in the browser')
end
end

describe '#mantle_request' do
Expand Down