Commits

Rich Manalang [Atlassian] committed a2a73a8

* Refactored sinatra app
* Make json-rpc call to get fullName and profile url of blog post author

  • Participants
  • Parent commits 6815d70

Comments (0)

Files changed (2)

   @uri = (url.port == 80 or url.port == 443) ? 
     "#{url.scheme}://#{url.host}" : "#{url.scheme}://#{url.host}:#{url.port}"
   if params["key"]
-    registration = Registration.find_or_initialize_by_client_key(params["key"])
-    registration.host_public_key = to_pub_key_pem(params["publicKey"])
-    registration.base_url = params["baseUrl"]
-    registration.description = params["description"]
-    registration.save
+    @registration = Registration.find_or_initialize_by_client_key(params["key"])
+    @registration.attributes = {
+      host_public_key: to_pub_key_pem(params["publicKey"]),
+      base_url: params["baseUrl"],
+      description: params["description"] 
+    }
+    @registration.save
   end
 
   content_type :xml
   erb :register
 end
 
-# OAuth check to make sure 
+# OAuth check to make sure requests are valid
 before "/protected/*" do
   response.header["X-Frame-Options"] = "GOFORIT"
   if session[:client_key].nil?
     halt(401, "Not authorized") unless valid
   else
     @client_key = session[:client_key]
+    @registration = Registration.find_by_client_key(@client_key)
   end
 end
 
+before "/protected/notify/*" do
+  halt "HipChat auth token not configured" if @registration.hipchat_auth_token.blank?
+end
+
 get '/protected/config' do
-  @registration = Registration.find_by_client_key(@client_key)
   erb :config
 end
 
 post '/protected/config' do
-  @registration = Registration.find_by_client_key(@client_key)
   @registration.hipchat_auth_token = params['hipChatAuthToken']
   @registration.save
   flash[:notice] = "Configuration saved."
 end
 
 post '/protected/notify/blog_created' do
-  json = MultiJson.decode(request.body.read)['blog']
-  msg = <<-eos
+  blog = MultiJson.decode(request.body.read)['blog']
+  user = MultiJson.decode(
+    signed_http_client.post(
+      "#{@registration.base_url}/rpc/json-rpc/confluenceservice-v2/getUser?user_id=admin",
+        MultiJson.encode(["#{blog['creatorName']}"]), {"Content-Type" => "application/json"} ).body
+    )
+  send_message <<-eos
     <b>
-      <a href='#{json['self']}'>#{json['title']}</a>
-    </b> - a new blog post by #{json['creatorName']}
+      <a href='#{blog['self']}'>#{blog['title']}</a>
+    </b> - a new blog post by 
+    <a href="#{user['url']}">#{user['fullname']}</a>
   eos
-  send_message msg
 end
 
-def send_message(msg)
-  uri = URI.parse("https://api.hipchat.com/v1/rooms/message?auth_token=#{ENV['HIPCHAT_TOKEN']}")
-  http = Net::HTTP.new(uri.host, uri.port)
-  http.set_debug_output($stderr)
-  http.use_ssl = true
-  http.verify_mode = OpenSSL::SSL::VERIFY_NONE
-
-  req = Net::HTTP::Post.new(uri.request_uri)
-  req.set_form_data({
-    "room_id" => ENV['HIPCHAT_ROOM'],
-    "message" => msg,
-    "notify" => "1",
-    "from" => "Confluence"
-  })
-  http.request(req)
-end
+helpers do
+  def send_message(msg)
+    uri = URI.parse("https://api.hipchat.com/v1/rooms/message?auth_token=#{@registration.hipchat_auth_token}")
+    http = Net::HTTP.new(uri.host, uri.port)
+    http.set_debug_output($stderr)
+    http.use_ssl = true
+    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
 
-def has_oauth_params(params)
-  params["oauth_version"] == "1.0" && 
-  params["oauth_signature_method"] == "RSA-SHA1" && 
-  params["oauth_signature"] && 
-  params["oauth_consumer_key"] &&
-  params["oauth_timestamp"] && 
-  params["oauth_nonce"] &&
-  params["user_id"]
-end
+    req = Net::HTTP::Post.new(uri.request_uri)
+    req.set_form_data({
+      "room_id" => ENV['HIPCHAT_ROOM'],
+      "message" => msg,
+      "notify" => "1",
+      "from" => "Confluence"
+    })
+    http.request(req)
+  end
 
-# Self-signing HTTP client for use when making a call back into
-# Confluence
-def oauth
-  reg = Registration.find_by_client_key(params['oauth_consumer_key'])
-  @consumer = OAuth::Consumer.new(
-    reg.client_key,
-    OpenSSL::PKey::RSA.new(ENV["LOCAL_PRIVATE_KEY"]),
-    :site => reg.base_url,
-    :signature_method => 'RSA-SHA1',
-    :request_token_path => "",
-    :authorize_path => "",
-    :access_token_path => ""
-  )
-  @consumer.http.set_debug_output($stderr)
-  OAuth::AccessToken.new(@consumer)
-end
+  def has_oauth_params(params)
+    params["oauth_version"] == "1.0" && 
+    params["oauth_signature_method"] == "RSA-SHA1" && 
+    params["oauth_signature"] && 
+    params["oauth_consumer_key"] &&
+    params["oauth_timestamp"] && 
+    params["oauth_nonce"] &&
+    params["user_id"]
+  end
 
-# added this to convert the pubKey I get back from
-# the registration process to a valid PEM that Ruby's 
-# OpenSSL lib can understand... lame!
-def to_pub_key_pem(str)
-  str = CGI.unescape(str).gsub(" ","+")
-  len = str.length
-  start = 0
-  arry = []
-  while len > 0 do
-    arry.push(str.slice(start,64))
-    start += 64
-    len = len - 64
+  # Self-signing HTTP client for use when making a call back into
+  # Confluence
+  def signed_http_client
+    @consumer = OAuth::Consumer.new(
+      "hipchat-demo",
+      OpenSSL::PKey::RSA.new(ENV["LOCAL_PRIVATE_KEY"]),
+      :site => @registration.base_url,
+      :signature_method => 'RSA-SHA1',
+      :request_token_path => "",
+      :authorize_path => "",
+      :access_token_path => ""
+    )
+    @consumer.http.set_debug_output($stderr)
+    OAuth::AccessToken.new(@consumer)
   end
-  arry.unshift("-----BEGIN PUBLIC KEY-----")
-  arry.push("-----END PUBLIC KEY-----")
-  arry.join("\n")
-end
 
-# A helper to convert the HTTP_AUTHORIZATION header to hash for easy access.
-# Only used in webhooks where the OAuth sig are delivered in a header.
-def hashify_oauth_headers(str)
-  return if str == nil
-  Hash[str.split(",").map{|i|
-    j = i.split("=")
-    [ j[0].strip.gsub(/OAuth\ /,'').to_sym, CGI.unescape(j[1].gsub(/\"/,'')) ]
-    }
-  ]
+  # added this to convert the pubKey I get back from
+  # the registration process to a valid PEM that Ruby's 
+  # OpenSSL lib can understand... lame!
+  def to_pub_key_pem(str)
+    str = CGI.unescape(str).gsub(" ","+")
+    len = str.length
+    start = 0
+    arry = []
+    while len > 0 do
+      arry.push(str.slice(start,64))
+      start += 64
+      len = len - 64
+    end
+    arry.unshift("-----BEGIN PUBLIC KEY-----")
+    arry.push("-----END PUBLIC KEY-----")
+    arry.join("\n")
+  end
+
+  # A helper to convert the HTTP_AUTHORIZATION header to hash for easy access.
+  # Only used in webhooks where the OAuth sig are delivered in a header.
+  def hashify_oauth_headers(str)
+    return if str == nil
+    Hash[str.split(",").map{|i|
+      j = i.split("=")
+      [ j[0].strip.gsub(/OAuth\ /,'').to_sym, CGI.unescape(j[1].gsub(/\"/,'')) ]
+      }
+    ]
+  end
 end

File views/register.erb

   <oauth>
     <public-key><%= ENV['LOCAL_PUBLIC_KEY'] %></public-key>
   </oauth>
+
+  <permissions>
+    <permission scope="read_users_and_groups" />
+  </permissions>
+
   <web-hook event="blog_created" url="/protected/notify/blog_created"/>
   <admin-page key="hipchat-config" name="HipChat Configuration" url="/protected/config" section="system.admin/configuration" weight="1000"/>
 </remote-app>