Skip to content

Commit

Permalink
Allow JavaScriptAgent to get and set user credentials
Browse files Browse the repository at this point in the history
  • Loading branch information
dsander committed Sep 13, 2015
1 parent 06b022f commit 6266e3e
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
18 changes: 18 additions & 0 deletions app/models/agents/java_script_agent.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ class JavaScriptAgent < Agent
* `this.memory()`
* `this.memory(key)`
* `this.memory(keyToSet, valueToSet)`
* `this.credential(name)`
* `this.credential(name, valueToSet)`
* `this.options()`
* `this.options(key)`
* `this.log(message)`
Expand Down Expand Up @@ -120,6 +122,8 @@ def execute_js(js_function, incoming_events = [])
end
context["escapeHtml"] = lambda { |a, x| CGI.escapeHTML(x) }
context["unescapeHtml"] = lambda { |a, x| CGI.unescapeHTML(x) }
context['getCredential'] = lambda { |a, k| credential(k); }
context['setCredential'] = lambda { |a, k, v| set_credential(k, v) }

if (options['language'] || '').downcase == 'coffeescript'
context.eval(CoffeeScript.compile code)
Expand All @@ -142,6 +146,12 @@ def credential_referenced_by_code
(interpolated['code'] || '').strip =~ /\Acredential:(.*)\Z/ && $1
end

def set_credential(name, value)
c = user.user_credentials.find_or_initialize_by(credential_name: name)
c.credential_value = value
c.save!
end

def setup_javascript
<<-JS
function Agent() {};
Expand All @@ -164,6 +174,14 @@ def setup_javascript
}
}
Agent.credential = function(name, value) {
if (typeof(value) !== "undefined") {
setCredential(name, value);
} else {
return getCredential(name);
}
}
Agent.options = function(key) {
if (typeof(key) !== "undefined") {
return JSON.parse(getOptions())[key];
Expand Down
28 changes: 28 additions & 0 deletions spec/models/agents/java_script_agent_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -264,5 +264,33 @@
expect(AgentLog.last.message).to eq("hello from coffeescript")
end
end

describe "user credentials" do
it "can access an existing credential" do
@agent.send(:set_credential, 'test', 'hello')
@agent.options['code'] = 'Agent.check = function() { this.log(this.credential("test")); };'
@agent.save!
@agent.check
expect(AgentLog.last.message).to eq("hello")
end

it "will create a new credential" do
@agent.options['code'] = 'Agent.check = function() { this.credential("test","1234"); };'
@agent.save!
expect {
@agent.check
}.to change(UserCredential, :count).by(1)
end

it "updates an existing credential" do
@agent.send(:set_credential, 'test', 1234)
@agent.options['code'] = 'Agent.check = function() { this.credential("test","12345"); };'
@agent.save!
expect {
@agent.check
}.to change(UserCredential, :count).by(0)
expect(@agent.user.user_credentials.last.credential_value).to eq('12345')
end
end
end
end

0 comments on commit 6266e3e

Please sign in to comment.