Skip to content

Commit

Permalink
allow credentials to provide the code
Browse files Browse the repository at this point in the history
  • Loading branch information
cantino committed Feb 10, 2014
1 parent d52f8e7 commit 62b60d1
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 4 deletions.
23 changes: 20 additions & 3 deletions app/models/agents/java_script_agent.rb
Expand Up @@ -21,11 +21,15 @@ class JavaScriptAgent < Agent
* `this.options(key)`
* `this.log(message)`
* `this.error(message)`
MD

def validate_options
errors.add(:base, "The 'code' option is required") unless options['code'].present?
cred_name = credential_referenced_by_code
if cred_name
errors.add(:base, "The credential '#{cred_name}' referenced by code cannot be found") unless credential(cred_name).present?
else
errors.add(:base, "The 'code' option is required") unless options['code'].present?
end
end

def working?
Expand Down Expand Up @@ -99,10 +103,23 @@ def execute_js(js_function, incoming_events = [])
end
end

context.eval(options['code'])
context.eval(code)
context.eval("Agent.#{js_function}();")
end

def code
cred = credential_referenced_by_code
if cred
credential(cred) || 'Agent.check = function() { this.error("Unable to find credential"); };'
else
options['code']
end
end

def credential_referenced_by_code
options['code'] =~ /\Acredential:(.*)\Z/ && $1
end

def setup_javascript
<<-JS
function Agent() {};
Expand Down
30 changes: 29 additions & 1 deletion spec/models/agents/java_script_agent_spec.rb
Expand Up @@ -22,6 +22,14 @@
@agent.options.delete('code')
@agent.should_not be_valid
end

it "accepts a credential, but it must exist" do
@agent.should be_valid
@agent.options['code'] = 'credential:foo'
@agent.should_not be_valid
users(:jane).user_credentials.create! :credential_name => "foo", :credential_value => "bar"
@agent.reload.should be_valid
end
end

describe "#working?" do
Expand Down Expand Up @@ -55,7 +63,7 @@
describe "executing code" do
it "works by default" do
@agent.options = @agent.default_options
@agent.options['make_event'] = true;
@agent.options['make_event'] = true
@agent.save!

lambda {
Expand All @@ -66,6 +74,26 @@
}.should change { Event.count }.by(2)
end


describe "using credentials as code" do
before do
@agent.user.user_credentials.create :credential_name => 'code-foo', :credential_value => 'Agent.check = function() { this.log("ran it"); };'
@agent.options['code'] = 'credential:code-foo'
@agent.save!
end

it "accepts credentials" do
@agent.check
AgentLog.last.message.should == "ran it"
end

it "logs an error when the credential goes away" do
@agent.user.user_credentials.delete_all
@agent.reload.check
AgentLog.last.message.should == "Unable to find credential"
end
end

describe "error handling" do
it "should log an error when V8 has issues" do
@agent.options['code'] = 'syntax error!'
Expand Down

0 comments on commit 62b60d1

Please sign in to comment.