public
Last active

Ember.js application with elasticsearch persistence and Goliath based proxy [http://www.elasticsearch.org/tutorials/2012/08/22/javascript-web-applications-and-elasticsearch.html]

  • Download Gist
.gitignore
1 2
.DS_Store
tmp/
Gemfile
Ruby
1 2 3 4 5
source :rubygems
 
gem 'goliath'
gem 'em-http-request'
gem 'oj'
Procfile
1
web: bundle exec ruby proxy.rb --stdout --verbose --environment production -p $PORT
index.html
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247
<!DOCTYPE html>
<html>
<head>
<title>Notes (Ember.js &amp; elasticsearch)</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 
<!-- *************** TWITTER @ANYWHERE LOGIN ************************************************ -->
 
<!-- Use the `Consumer Key` from OAuth settings -->
<script src="http://platform.twitter.com/anywhere.js?id=RolSFIW282BJrF4xGXyXDw&amp;v=1" type="text/javascript"></script>
 
<link href='http://fonts.googleapis.com/css?family=Londrina+Shadow' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Waiting+for+the+Sunrise' rel='stylesheet' type='text/css'>
 
<!-- *************** STYLES ***************************************************************** -->
 
<style>
body
{ color: #222; background-color: #f5f5f5; font-family: 'Helvetica Neue', Helvetica, sans-serif; padding: 2em 4em; }
#invitation
{ font-size: 2em; font-weight: 300; margin-right: 1em; }
#post_note
{ font: normal 300 2em/100% 'Helvetica Neue', Helvetica, sans-serif;
margin: 0 0 0.5em 0; padding: 0.25em 0.5em 0.2em 0.5em; width: 95%;
outline: none; border: none; border-bottom: 2px solid #cc3145;
box-shadow: rgba(0, 0, 0, 0.1) 0px 1px 3px;
border-top-left-radius: 0.1em; border-top-right-radius: 0.1em; }
#user
{ font-family: 'Londrina Shadow', cursive; font-size: 28px; }
#user img
{ width: 30px; height: 30px; border-radius: 15px; position: relative; top: 6px; }
#user a.sign_out
{ cursor: pointer; float: right; }
#user a.sign_out:hover
{ font-weight: bold; border-bottom: 1px solid #444; }
#login
{ padding-top: 1em; margin-top: 1em; border-top: 1px solid rgba(0,0,0,0.1); height: 23px; }
#notes
{ margin: 0 0 0 -0.5em; }
.note
{ color: rgba(0,0,0,0.9);
font-family: 'Waiting for the Sunrise', cursive;
font-size: 26px;
background-color: #fff86b;
margin: 0.5em 0.5em 0.5em 0.5em;
padding: 0.5em 0.75em;
border-radius: 0.5em;
display: inline-block;
box-shadow: rgba(0,0,0,0.6) 0px 1px 2px; }
.note p
{ color: rgba(0,0,0,0.6); font-size: 80%; margin: 0; padding: 0.25em 0; }
.note p strong
{ color: rgba(0,0,0,0.75); }
.note p .time_ago
{ color: rgba(0,0,0,0.7); }
.note blockquote
{ margin: 0; font-weight: bold; }
#source
{ color: #c1c1c1; font-size: 12px; margin: 3em 0 0 0; }
#source a
{ color: #c0c0c0; text-decoration: none; }
#source a:hover
{ color: #a3a3a3; text-decoration: underline; }
</style>
</head>
<body>
 
<!-- *************** VIEWS ****************************************************************** -->
 
<div id="user">
<script type="text/x-handlebars">
{{#with App.current_user}}
<img {{bindAttr src="App.current_user.profile_image_url"}}>
Welcome, {{App.current_user.screen_name}}!
{{/with}}
{{#if App.current_user}}
<a {{action sign_out target="App" href=true}} {{bindAttr class=":sign_out"}}>Sign Out</a>
{{else}}
<p id="invitation">Please login with Twitter</p>
{{/if}}
</script>
</p>
 
<script type="text/x-handlebars">
{{#if App.current_user}}
{{view App.PostNote id="post_note" placeholder="Leave a note..."}}
{{/if}}
</script>
 
<script type="text/x-handlebars">
{{#if App.current_user}}
<div id="notes">
{{#each App.notes}}
<div class="note">
<p><strong>@{{screen_name}}</strong> left a note <span class="time_ago">{{time_ago created_at}}</span>...</p>
<blockquote>{{message}}</blockquote>
</div>
{{/each}}
</div>
{{/if}}
</script>
 
<!-- Twitter login button -->
<div id="login"></div>
 
<p id="source"><code>Source: <a href="http://gist.github.com/3369662">http://gist.github.com/3369662</a></code></p>
 
<!-- *************** LIBRARIES ************************************************************** -->
 
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="https://raw.github.com/timrwood/moment/1.7.0/min/moment.min.js"></script>
<script src="http://cloud.github.com/downloads/wycats/handlebars.js/handlebars-1.0.0.beta.6.js"></script>
<script src="http://cloud.github.com/downloads/emberjs/ember.js/ember-1.0.pre.min.js"></script>
<script src="ember-data.min.js"></script>
<script src="https://raw.github.com/karmi/ember-data-elasticsearch/master/ember-data/lib/adapters/elasticsearch_adapter.js"></script>
 
<!-- *************** APPLICATION ************************************************************ -->
 
<script>
 
// ========================
// Supporting code, patches
// ========================
 
// Handlerbars helper for Moment.js
//
Handlebars.registerHelper('time_ago', function(property, options) {
var value = Ember.Handlebars.getPath(this, property, options);
return value ? new Handlebars.SafeString(moment(value).fromNow()) : '';
});
 
// Redefine the adapter's `find()` method to load last 100 notes
//
DS.ElasticSearchAdapter.reopen({
findAll: function(store, type) {
var url = [this.url, type.url, '_search'].join('/');
var payload = {size: 100, sort: { created_at: 'desc' }};
 
this.http.post(url, payload, function(data, textStatus, xhr) {
store.loadMany(type, data['hits']['hits'].map( function(i) {
return Ember.Object.create(i['_source']).reopen({id: i._id, version: i._version})
} ));
});
}
});
 
// ========================
// The Ember.js application
// ========================
 
var App = Ember.Application.create({
current_user: null,
elasticsearch_url: window.location.protocol + "//" + window.location.host,
 
// Sign out of Twittter
//
sign_out: function() { window.twttr.anywhere.signOut() },
 
// Application intitializer
//
ready: function() {
var self = this;
 
window.twttr.anywhere(function (T) {
 
// Hook up Twitter login button
T("#login").connectButton({size: 'medium'});
T("#notes").hovercards();
 
// Set `current_user` if already logged in
//
if ( T.isConnected() ) {
console.log("Logged in as:", T.currentUser.screenName, T.currentUser)
self.set("current_user", T.currentUser.attributes)
App.notes.set("content", App.Note.find());
}
 
// Listeners for login/logout events
//
T.bind("authComplete", function (e, user) {
console.log("Authenticated as:", user.screenName, user)
self.set("current_user", user.attributes);
App.notes.set("content", App.Note.find());
})
T.bind("signOut", function (e) {
self.set("current_user", null);
});
});
return this._super();
}
});
 
// Create store in elasticsearch
//
App.store = DS.Store.create({
revision: 4,
adapter: DS.ElasticSearchAdapter.create({url: App.elasticsearch_url})
});
 
// The `Note` model
//
App.Note = DS.Model.extend({
screen_name: DS.attr('string'),
message: DS.attr('string'),
created_at: DS.attr('string')
});
App.Note.reopenClass({
url: 'notes/note'
});
 
// The `notes` collection
//
App.notes = Ember.ArrayController.create({
// Show last notes first
//
sortProperties: ['created_at'],
sortAscending: false,
 
// Hook up Ember/Handlebars binding for views
//
content: [],
 
// Create new note in collection and storage
//
createNote: function(value) {
var note = App.Note.createRecord({ screen_name: App.current_user.screen_name,
message: value,
created_at: (new Date().toJSON()) });
App.store.commit();
}
});
 
// Note input form
//
App.PostNote = Ember.TextField.extend({
insertNewline: function(event) {
var value = this.get('value');
 
if (value) {
App.notes.createNote(value);
this.set('value', '');
}
}
});
</script>
</body>
</html>
proxy.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
#!/usr/bin/env ruby
 
# A Goliath-based [https://github.com/postrank-labs/goliath] web server and proxy.
#
# Serves a simple JavaScript application on root (see `index.html`).
#
# It validates backend requests with Twitter @Anywhere login:
#
# <https://dev.twitter.com/docs/anywhere/welcome#login-signup>
#
# Run the server with:
#
# $ PROXY_BASE_URL=http://localhost:9200 TWITTER_CONSUMER_SECRET=<REPLACE_ME> ruby proxy.rb --stdout --verbose
#
# On Heroku, configure backend URL and the Twitter consumer secret with environment variables:
#
# $ heroku config:add PROXY_BASE_URL=http://user:password@elasticsearch.myserver.com
# $ heroku config:add TWITTER_CONSUMER_SECRET=<REPLACE_ME>
#
require 'goliath'
require 'em-synchrony/em-http'
require 'oj'
require 'digest/sha1'
require 'uri'
 
class TwitterAuthProxy < Goliath::API
use Goliath::Rack::DefaultMimeType
use Goliath::Rack::JSONP
use Goliath::Rack::Params
 
PROXY_BASE_URL = ENV['PROXY_BASE_URL'] || "http://localhost:9200"
TWITTER_CONSUMER_SECRET = ENV['TWITTER_CONSUMER_SECRET'] || "INVALID"
HTML_APP = File.read File.expand_path('../index.html', __FILE__)
EMBER_DATA = File.read File.expand_path('../ember-data.min.js', __FILE__)
HEADERS = {}
 
# Get HTTP Auth credentials from URI
HTTP_AUTH_HEADER = (userinfo = URI.parse(PROXY_BASE_URL).userinfo) ? { authorization: userinfo.split(':') } : {}
 
def on_headers(env, headers)
# Store request headers
#
env.logger.debug 'Received headers: ' + headers.inspect
env['headers'] = headers
end
 
def response(env)
# 1. Serve the HTML application on root
#
html_app = Goliath.env?(:production) ? HTML_APP : File.read(File.expand_path('../index.html', __FILE__))
return [ 200, {}, html_app ] if env['REQUEST_PATH'] == '/'
return [ 200, {}, EMBER_DATA ] if env['REQUEST_PATH'] == '/ember-data.min.js'
 
# - Handle favicons
#
return [ 200, {}, "" ] if env['REQUEST_PATH'] == '/favicon.ico'
 
# 2. Make the game harder for script kiddies
#
if %w| put delete |.include?(env['REQUEST_METHOD'].downcase)
logger.info "Incorrect request."
return [ 401, {'Content-Type' => 'application/json'}, '{"error":"What are you trying to do?"}' ]
end
 
# 3. Return 401 Forbidden unless logged in via Twitter
#
unless valid_cookie?(env['HTTP_COOKIE'])
logger.info "Invalid Twitter @Anywhere Identity: #{env['HTTP_COOKIE']}"
return [ 401, {'Content-Type' => 'application/json'}, '{"error":"Please login with Twitter."}' ]
end
 
# - Get URL and JSON payload
#
url = "#{PROXY_BASE_URL}#{env['REQUEST_PATH']}?#{env['QUERY_STRING']}"
#
# FIX: Work around the fact that elasticsearch does not like `Content-Type` header
# when the request is sent via Ajax (Access-Control-Allow-Headers).
# See <https://github.com/elasticsearch/elasticsearch/issues/2186>
#
if ['POST', 'PUT'].include? env['REQUEST_METHOD'] and ( !env['params'].keys.empty? && env['params'].values.compact.empty? )
logger.info "Fixing incorrect JSON payload: #{env['params'].inspect}"
payload = env['params'].keys.first
else
payload = Oj.dump(env['params'])
end
 
logger.info "curl -X #{env['REQUEST_METHOD']} '#{url}pretty' -d '#{payload}'"
 
# 4. Perform the request on backend
#
headers = HEADERS.merge(env['headers']).merge(HTTP_AUTH_HEADER)
http = EM::HttpRequest.new(url).send( env['REQUEST_METHOD'].downcase.to_sym, { body: payload, head: headers } )
logger.info "Received response [#{http.response_header.status}] from backend"
 
# 5. Return backend response to client
#
[ 200, {'Content-Type' => http.response_header['CONTENT_TYPE']}, http.response ]
end
 
# Validates the cookie based on shared secret with Twitter:
#
# Digest::SHA1.hexdigest(user_id + consumer_secret)
#
# See https://dev.twitter.com/docs/anywhere/welcome#current-user
#
def valid_cookie?(cookie)
return false unless cookie
 
cookie_value = cookie.to_s.gsub(/twitter_anywhere_identity=/, '')
cookie_user_id, cookie_fingerprint = cookie_value.split(':')
 
return cookie_fingerprint == Digest::SHA1.hexdigest( [cookie_user_id, TWITTER_CONSUMER_SECRET].join('') )
end
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.