Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Initial commit.

  • Loading branch information...
commit 33a553c9a02cfb852641dd3181fb6e1a3df445a2 0 parents
Giang Nguyen Duc authored
Showing with 21,754 additions and 0 deletions.
  1. +5 −0 consumer/.gitignore
  2. +52 −0 consumer/.rvmrc
  3. +9 −0 consumer/Gemfile
  4. +112 −0 consumer/Gemfile.lock
  5. +168 −0 consumer/README.md
  6. +7 −0 consumer/Rakefile
  7. +3 −0  consumer/app/controllers/application_controller.rb
  8. +59 −0 consumer/app/controllers/oauth_consumers_controller.rb
  9. +11 −0 consumer/app/controllers/welcome_controller.rb
  10. +2 −0  consumer/app/helpers/application_helper.rb
  11. +2 −0  consumer/app/helpers/welcome_helper.rb
  12. +41 −0 consumer/app/models/consumer_token.rb
  13. +12 −0 consumer/app/models/test_token.rb
  14. +12 −0 consumer/app/models/user.rb
  15. +14 −0 consumer/app/views/layouts/application.html.erb
  16. +29 −0 consumer/app/views/oauth_consumers/index.html.erb
  17. +7 −0 consumer/app/views/oauth_consumers/show.html.erb
  18. +2 −0  consumer/app/views/welcome/index.html.erb
  19. +4 −0 consumer/config.ru
  20. +53 −0 consumer/config/application.rb
  21. +6 −0 consumer/config/boot.rb
  22. +5 −0 consumer/config/environment.rb
  23. +26 −0 consumer/config/environments/development.rb
  24. +49 −0 consumer/config/environments/production.rb
  25. +35 −0 consumer/config/environments/test.rb
  26. +7 −0 consumer/config/initializers/backtrace_silencers.rb
  27. +209 −0 consumer/config/initializers/devise.rb
  28. +10 −0 consumer/config/initializers/inflections.rb
  29. +5 −0 consumer/config/initializers/mime_types.rb
  30. +73 −0 consumer/config/initializers/oauth_consumers.rb
  31. +7 −0 consumer/config/initializers/secret_token.rb
  32. +8 −0 consumer/config/initializers/session_store.rb
  33. +58 −0 consumer/config/locales/devise.en.yml
  34. +5 −0 consumer/config/locales/en.yml
  35. +20 −0 consumer/config/mongoid.yml
  36. +15 −0 consumer/config/routes.rb
  37. +7 −0 consumer/db/seeds.rb
  38. +2 −0  consumer/doc/README_FOR_APP
  39. 0  consumer/lib/tasks/.gitkeep
  40. +26 −0 consumer/public/404.html
  41. +26 −0 consumer/public/422.html
  42. +26 −0 consumer/public/500.html
  43. 0  consumer/public/favicon.ico
  44. BIN  consumer/public/images/rails.png
  45. +2 −0  consumer/public/javascripts/application.js
  46. +965 −0 consumer/public/javascripts/controls.js
  47. +974 −0 consumer/public/javascripts/dragdrop.js
  48. +1,123 −0 consumer/public/javascripts/effects.js
  49. +6,001 −0 consumer/public/javascripts/prototype.js
  50. +202 −0 consumer/public/javascripts/rails.js
  51. +5 −0 consumer/public/robots.txt
  52. 0  consumer/public/stylesheets/.gitkeep
  53. +6 −0 consumer/script/rails
  54. +11 −0 consumer/test/fixtures/users.yml
  55. +9 −0 consumer/test/functional/welcome_controller_test.rb
  56. +9 −0 consumer/test/performance/browsing_test.rb
  57. +13 −0 consumer/test/test_helper.rb
  58. +4 −0 consumer/test/unit/helpers/welcome_helper_test.rb
  59. +8 −0 consumer/test/unit/user_test.rb
  60. 0  consumer/vendor/plugins/.gitkeep
  61. +5 −0 provider/.gitignore
  62. +52 −0 provider/.rvmrc
  63. +9 −0 provider/Gemfile
  64. +112 −0 provider/Gemfile.lock
  65. +149 −0 provider/README.md
  66. +7 −0 provider/Rakefile
  67. +7 −0 provider/app/controllers/application_controller.rb
  68. +5 −0 provider/app/controllers/data_controller.rb
  69. +54 −0 provider/app/controllers/oauth_clients_controller.rb
  70. +26 −0 provider/app/controllers/oauth_controller.rb
  71. +2 −0  provider/app/helpers/application_helper.rb
  72. +2 −0  provider/app/helpers/data_helper.rb
  73. +16 −0 provider/app/models/access_token.rb
  74. +71 −0 provider/app/models/client_application.rb
  75. +20 −0 provider/app/models/oauth2_token.rb
  76. +35 −0 provider/app/models/oauth2_verifier.rb
  77. +24 −0 provider/app/models/oauth_nonce.rb
  78. +44 −0 provider/app/models/oauth_token.rb
  79. +36 −0 provider/app/models/request_token.rb
  80. +10 −0 provider/app/models/user.rb
  81. +2 −0  provider/app/views/data/index.html.erb
  82. +14 −0 provider/app/views/layouts/application.html.erb
  83. +14 −0 provider/app/views/oauth/authorize.html.erb
  84. +1 −0  provider/app/views/oauth/authorize_failure.html.erb
  85. +1 −0  provider/app/views/oauth/authorize_success.html.erb
  86. +16 −0 provider/app/views/oauth/oauth2_authorize.html.erb
  87. +17 −0 provider/app/views/oauth_clients/_form.html.erb
  88. +7 −0 provider/app/views/oauth_clients/edit.html.erb
  89. +43 −0 provider/app/views/oauth_clients/index.html.erb
  90. +5 −0 provider/app/views/oauth_clients/new.html.erb
  91. +27 −0 provider/app/views/oauth_clients/show.html.erb
  92. +4 −0 provider/config.ru
  93. +57 −0 provider/config/application.rb
  94. +6 −0 provider/config/boot.rb
  95. +5 −0 provider/config/environment.rb
  96. +26 −0 provider/config/environments/development.rb
  97. +49 −0 provider/config/environments/production.rb
  98. +35 −0 provider/config/environments/test.rb
  99. +7 −0 provider/config/initializers/backtrace_silencers.rb
  100. +209 −0 provider/config/initializers/devise.rb
  101. +10 −0 provider/config/initializers/inflections.rb
  102. +5 −0 provider/config/initializers/mime_types.rb
  103. +7 −0 provider/config/initializers/secret_token.rb
  104. +8 −0 provider/config/initializers/session_store.rb
  105. +58 −0 provider/config/locales/devise.en.yml
  106. +5 −0 provider/config/locales/en.yml
  107. +20 −0 provider/config/mongoid.yml
  108. +25 −0 provider/config/routes.rb
  109. +7 −0 provider/db/seeds.rb
  110. +2 −0  provider/doc/README_FOR_APP
  111. 0  provider/lib/tasks/.gitkeep
  112. +26 −0 provider/public/404.html
  113. +26 −0 provider/public/422.html
  114. +26 −0 provider/public/500.html
  115. 0  provider/public/favicon.ico
  116. BIN  provider/public/images/rails.png
  117. +2 −0  provider/public/javascripts/application.js
  118. +965 −0 provider/public/javascripts/controls.js
  119. +974 −0 provider/public/javascripts/dragdrop.js
  120. +1,123 −0 provider/public/javascripts/effects.js
  121. +6,001 −0 provider/public/javascripts/prototype.js
  122. +202 −0 provider/public/javascripts/rails.js
  123. +5 −0 provider/public/robots.txt
  124. 0  provider/public/stylesheets/.gitkeep
  125. +6 −0 provider/script/rails
  126. +11 −0 provider/test/fixtures/users.yml
  127. +9 −0 provider/test/functional/data_controller_test.rb
  128. +280 −0 provider/test/functional/oauth_clients_controller_test.rb
  129. +9 −0 provider/test/performance/browsing_test.rb
  130. +13 −0 provider/test/test_helper.rb
  131. +42 −0 provider/test/unit/client_application_test.rb
  132. +4 −0 provider/test/unit/helpers/data_helper_test.rb
  133. +26 −0 provider/test/unit/oauth_nonce_test.rb
  134. +57 −0 provider/test/unit/oauth_token_test.rb
  135. +8 −0 provider/test/unit/user_test.rb
  136. 0  provider/vendor/plugins/.gitkeep
5 consumer/.gitignore
@@ -0,0 +1,5 @@
+.bundle
+db/*.sqlite3
+log/*.log
+tmp/
+*.swp
52 consumer/.rvmrc
@@ -0,0 +1,52 @@
+#!/usr/bin/env bash
+
+# This is an RVM Project .rvmrc file, used to automatically load the ruby
+# development environment upon cd'ing into the directory
+
+# First we specify our desired <ruby>[@<gemset>], the @gemset name is optional,
+# Only full ruby name is supported here, for short names use:
+# echo "rvm use 1.9.3" > .rvmrc
+environment_id="ruby-1.9.3-p125@oauth-sample"
+
+# Uncomment the following lines if you want to verify rvm version per project
+# rvmrc_rvm_version="1.13.1 (stable)" # 1.10.1 seams as a safe start
+# eval "$(echo ${rvm_version}.${rvmrc_rvm_version} | awk -F. '{print "[[ "$1*65536+$2*256+$3" -ge "$4*65536+$5*256+$6" ]]"}' )" || {
+# echo "This .rvmrc file requires at least RVM ${rvmrc_rvm_version}, aborting loading."
+# return 1
+# }
+
+# First we attempt to load the desired environment directly from the environment
+# file. This is very fast and efficient compared to running through the entire
+# CLI and selector. If you want feedback on which environment was used then
+# insert the word 'use' after --create as this triggers verbose mode.
+if [[ -d "${rvm_path:-$HOME/.rvm}/environments"
+ && -s "${rvm_path:-$HOME/.rvm}/environments/$environment_id" ]]
+then
+ \. "${rvm_path:-$HOME/.rvm}/environments/$environment_id"
+ [[ -s "${rvm_path:-$HOME/.rvm}/hooks/after_use" ]] &&
+ \. "${rvm_path:-$HOME/.rvm}/hooks/after_use" || true
+ if [[ $- == *i* ]] # check for interactive shells
+ then echo "Using: $(tput setaf 2)$GEM_HOME$(tput sgr0)" # show the user the ruby and gemset they are using in green
+ else echo "Using: $GEM_HOME" # don't use colors in non-interactive shells
+ fi
+else
+ # If the environment file has not yet been created, use the RVM CLI to select.
+ rvm --create use "$environment_id" || {
+ echo "Failed to create RVM environment '${environment_id}'."
+ return 1
+ }
+fi
+
+# If you use bundler, this might be useful to you:
+# if [[ -s Gemfile ]] && {
+# ! builtin command -v bundle >/dev/null ||
+# builtin command -v bundle | GREP_OPTIONS= \grep $rvm_path/bin/bundle >/dev/null
+# }
+# then
+# printf "%b" "The rubygem 'bundler' is not installed. Installing it now.\n"
+# gem install bundler
+# fi
+# if [[ -s Gemfile ]] && builtin command -v bundle >/dev/null
+# then
+# bundle install | GREP_OPTIONS= \grep -vE '^Using|Your bundle is complete'
+# fi
9 consumer/Gemfile
@@ -0,0 +1,9 @@
+source 'http://rubygems.org'
+
+gem 'rails', '3.0.12'
+
+gem 'devise'
+gem 'oauth-plugin'
+
+gem 'mongoid'
+gem 'bson_ext'
112 consumer/Gemfile.lock
@@ -0,0 +1,112 @@
+GEM
+ remote: http://rubygems.org/
+ specs:
+ abstract (1.0.0)
+ actionmailer (3.0.12)
+ actionpack (= 3.0.12)
+ mail (~> 2.2.19)
+ actionpack (3.0.12)
+ activemodel (= 3.0.12)
+ activesupport (= 3.0.12)
+ builder (~> 2.1.2)
+ erubis (~> 2.6.6)
+ i18n (~> 0.5.0)
+ rack (~> 1.2.5)
+ rack-mount (~> 0.6.14)
+ rack-test (~> 0.5.7)
+ tzinfo (~> 0.3.23)
+ activemodel (3.0.12)
+ activesupport (= 3.0.12)
+ builder (~> 2.1.2)
+ i18n (~> 0.5.0)
+ activerecord (3.0.12)
+ activemodel (= 3.0.12)
+ activesupport (= 3.0.12)
+ arel (~> 2.0.10)
+ tzinfo (~> 0.3.23)
+ activeresource (3.0.12)
+ activemodel (= 3.0.12)
+ activesupport (= 3.0.12)
+ activesupport (3.0.12)
+ arel (2.0.10)
+ bcrypt-ruby (3.0.1)
+ bson (1.6.2)
+ bson_ext (1.6.2)
+ bson (~> 1.6.2)
+ builder (2.1.2)
+ devise (1.5.3)
+ bcrypt-ruby (~> 3.0)
+ orm_adapter (~> 0.0.3)
+ warden (~> 1.1)
+ erubis (2.6.6)
+ abstract (>= 1.0.0)
+ faraday (0.8.0)
+ multipart-post (~> 1.1)
+ httpauth (0.1)
+ i18n (0.5.0)
+ json (1.7.3)
+ mail (2.2.19)
+ activesupport (>= 2.3.6)
+ i18n (>= 0.4.0)
+ mime-types (~> 1.16)
+ treetop (~> 1.4.8)
+ mime-types (1.18)
+ mongo (1.6.2)
+ bson (~> 1.6.2)
+ mongoid (2.2.6)
+ activemodel (~> 3.0.0)
+ mongo (~> 1.3)
+ tzinfo (~> 0.3.22)
+ multi_json (1.3.5)
+ multipart-post (1.1.5)
+ oauth (0.4.6)
+ oauth-plugin (0.4.0)
+ multi_json
+ oauth (~> 0.4.4)
+ oauth2 (>= 0.5.0)
+ rack
+ oauth2 (0.6.1)
+ faraday (~> 0.7)
+ httpauth (~> 0.1)
+ multi_json (~> 1.3)
+ orm_adapter (0.0.7)
+ polyglot (0.3.3)
+ rack (1.2.5)
+ rack-mount (0.6.14)
+ rack (>= 1.0.0)
+ rack-test (0.5.7)
+ rack (>= 1.0)
+ rails (3.0.12)
+ actionmailer (= 3.0.12)
+ actionpack (= 3.0.12)
+ activerecord (= 3.0.12)
+ activeresource (= 3.0.12)
+ activesupport (= 3.0.12)
+ bundler (~> 1.0)
+ railties (= 3.0.12)
+ railties (3.0.12)
+ actionpack (= 3.0.12)
+ activesupport (= 3.0.12)
+ rake (>= 0.8.7)
+ rdoc (~> 3.4)
+ thor (~> 0.14.4)
+ rake (0.9.2.2)
+ rdoc (3.12)
+ json (~> 1.4)
+ thor (0.14.6)
+ treetop (1.4.10)
+ polyglot
+ polyglot (>= 0.3.1)
+ tzinfo (0.3.33)
+ warden (1.2.0)
+ rack (>= 1.0)
+
+PLATFORMS
+ ruby
+
+DEPENDENCIES
+ bson_ext
+ devise
+ mongoid
+ oauth-plugin
+ rails (= 3.0.12)
168 consumer/README.md
@@ -0,0 +1,168 @@
+# CONSUMER SAMPLE (MONGODB VERSION)
+
+Using 'oauth-plugin' and 'mongodb'.
+
+## Steps from scratch
+
+### 1. Create new project
+
+- `cd oauth`
+- `rails new consumer`
+- `cd consumer`
+- add these gems to your Gemfile
+
+```ruby
+gem 'rails', '3.0.12'
+
+gem 'devise'
+gem 'oauth-plugin', '~> 0.4.0'
+
+gem 'mongoid'
+gem 'bson_ext'
+```
+- `bundle install`
+
+Now you have:
+- an authentication system installed (Devise)
+- oauth-plugin which helps you a lot in generating files for Oauth
+- mongoid a driver for mongodb
+- bson_ext which mainly for mongo peformance improvement
+
+### 2. Config the app to use mongodb
+
+- delete `config/database.yml`
+- `rails g mongoid:config`
+- replace `require 'rails/all'` in `config/application.rb` with
+
+```ruby
+require "action_controller/railtie"
+require "action_mailer/railtie"
+require "active_resource/railtie"
+require "rails/test_unit/railtie"
+# require "sprockets/railtie" # Uncomment this line for Rails 3.1+
+```
+
+### 3. Config the generators
+
+This step is important, you need to do this before generating/installing Devise model, Oauth things...
+
+Add this code into your `application.rb`, uncomment haml/rspec if you use them. Keep the mongoid option as that is what we want.
+
+```ruby
+config.generators do |g|
+ g.orm :mongoid
+ #g.template_engine :haml
+ #g.test_framework :rspec
+end
+```
+
+From now on, the generators know they should invoke `mongoid` instead of `activerecord` when generating things...
+
+### 4. Generates things
+
+```ruby
+rails g devise:install
+rails g devise User
+rails g controller Welcome index
+rails g oath_consumer User
+rm public/index.html
+```
+
+Add this to your `User` model:
+
+```ruby
+references_many :consumer_tokens
+index "consumer_tokens.token"
+```
+
+In `app/model/consumer_token.rb`, find the line reads `embedded_in :user, :inverse_of => :consumer_tokens`
+
+change it to
+
+`referenced_in :user, :inverse_of => :consumer_tokens`
+
+
+Add this to `oauth_consumers_controller.rb`, comment out the line reads `before_filter :login_required, :only=>:index`.
+Uncomment/add new line that reads `before_filter :authenticate_user!, :only=>:index`
+
+In `oauth_consumers_controller.rb`, make sure these methods are NOT commented out: `go_back`, `logged_in?`, `current_user=`, `deny_access!`
+
+Added this to `User` model: `references_one :test, :class_name => "TestToken", :dependent => :destroy`
+(TestToken is the model for the provider, we would have TwitterToken, FacebookToken...etc)
+
+Create a model file named `test_token.rb` in `app/models/` with the content:
+```ruby
+class TestToken < ConsumerToken
+ TEST_SETTINGS = {
+ :site => 'http://localhost:3000', # this is the URL to `provider` app
+ :request_token_path => '/oauth/request_token',
+ :access_token_path => '/oauth/access_token',
+ :authorize_path => '/oauth/authorize'
+ }
+
+ def self.consumer(options={})
+ @consumer ||= OAuth::Consumer.new(credentials[:key], credentials[:secret], TEST_SETTINGS.merge(options))
+ end
+end
+```
+
+In `config/routes.rb`, add your root path `root :to => "welcome#index"`
+
+### 5. Connect with the Provider
+
+Let's start `provider` app on port 3000 and `consumer` app running on port 4000 (`rails s -p 4000`)
+
+Navigate to `http://localhost:3000/users/sign_up` to register an account.
+
+Navigate to `http://localhost:3000/oauth_clients/` to register your app with these info:
+
+```ruby
+Name: Test consumer
+Main Application URL: http://localhost:4000/
+Callback URL: http://localhost:4000/oauth_consumers/test/callback
+```
+
+You will be redirected to oauth_client show page with credentials (yours will be different)
+
+```ruby
+OAuth details for Test Consumer
+
+Consumer Key: d8KBiaD98Mnp2vyB9A8ZSAT0vpKu5kdFtAXUsZup
+
+Consumer Secret: UDdD5HAefrRZ1afguDy0WrTALYwZ8KXWKgLiSJCE
+
+Request Token URL http://localhost:3000/oauth/request_token
+
+Access Token URL http://localhost:3000/oauth/access_token
+
+Authorize URL http://localhost:3000/oauth/authorize
+```
+
+In `config/initializers/oauth_consumers.rb`, add the credentials above. The content will look like:
+```ruby
+OAUTH_CREDENTIALS = {
+ :test => {
+ :key => 'd8KBiaD98Mnp2vyB9A8ZSAT0vpKu5kdFtAXUsZup',
+ :secret => 'UDdD5HAefrRZ1afguDy0WrTALYwZ8KXWKgLiSJCE',
+ :expose => true
+ }
+}
+```
+Restart your `consumer` app if it was running when you changed the content of this initializer.
+
+Modify the content of Welcome#index to get the provider data:
+```ruby
+class WelcomeController < ApplicationController
+ def index
+ @consumer_tokens = TestToken.where(:user_id => current_user.id)
+ @token = @consumer_tokens.first.client
+ logger.info 'private data' + @token.get('/data/index').body
+ end
+end
+```
+
+Go to `http://localhost:4000/oauth_consumers` to see all the services. Actually we have only 1 here, it's the 'test' service which owned by 'TestToken' model.
+
+Click on the service (here is `test`) then give it access
+
+Go to `http://localhost:4000` and you will see the data from `provider` in log
7 consumer/Rakefile
@@ -0,0 +1,7 @@
+# Add your own tasks in files placed in lib/tasks ending in .rake,
+# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
+
+require File.expand_path('../config/application', __FILE__)
+require 'rake'
+
+Consumer::Application.load_tasks
3  consumer/app/controllers/application_controller.rb
@@ -0,0 +1,3 @@
+class ApplicationController < ActionController::Base
+ protect_from_forgery
+end
59 consumer/app/controllers/oauth_consumers_controller.rb
@@ -0,0 +1,59 @@
+require 'oauth/controllers/consumer_controller'
+class OauthConsumersController < ApplicationController
+ include Oauth::Controllers::ConsumerController
+ # Replace this with the equivalent for your authentication framework
+ # Eg. for devise
+ #
+ before_filter :authenticate_user!, :only=>:index
+# before_filter :login_required, :only=>:index
+
+ def index
+ @consumer_tokens=ConsumerToken.all :conditions=>{:user_id=>current_user.id}
+ @services=OAUTH_CREDENTIALS.keys-@consumer_tokens.collect{|c| c.class.service_name}
+ end
+
+ def callback
+ super
+ end
+
+ def client
+ super
+ end
+
+
+ protected
+
+ # Change this to decide where you want to redirect user to after callback is finished.
+ # params[:id] holds the service name so you could use this to redirect to various parts
+ # of your application depending on what service you're connecting to.
+ def go_back
+ redirect_to root_url
+ end
+
+ # The plugin requires logged_in? to return true or false if the user is logged in. Uncomment and
+ # call your auth frameworks equivalent below if different. eg. for devise:
+ #
+ def logged_in?
+ user_signed_in?
+ end
+
+ # The plugin requires current_user to return the current logged in user. Uncomment and
+ # call your auth frameworks equivalent below if different.
+ # def current_user
+ # current_person
+ # end
+
+ # The plugin requires a way to log a user in. Call your auth frameworks equivalent below
+ # if different. eg. for devise:
+ #
+ def current_user=(user)
+ sign_in(user)
+ end
+
+ # Override this to deny the user or redirect to a login screen depending on your framework and app
+ # if different. eg. for devise:
+ #
+ def deny_access!
+ raise Acl9::AccessDenied
+ end
+end
11 consumer/app/controllers/welcome_controller.rb
@@ -0,0 +1,11 @@
+class WelcomeController < ApplicationController
+ def index
+ begin
+ @consumer_tokens = TestToken.where(:user_id => current_user.id)
+ @token = @consumer_tokens.first.client
+ logger.info 'private data' + @token.get('/data/index').body
+ rescue
+ logger.info 'no data'
+ end
+ end
+end
2  consumer/app/helpers/application_helper.rb
@@ -0,0 +1,2 @@
+module ApplicationHelper
+end
2  consumer/app/helpers/welcome_helper.rb
@@ -0,0 +1,2 @@
+module WelcomeHelper
+end
41 consumer/app/models/consumer_token.rb
@@ -0,0 +1,41 @@
+require 'oauth/models/consumers/token'
+class ConsumerToken
+ include Mongoid::Document
+ include Mongoid::Timestamps
+ include Oauth::Models::Consumers::Token
+
+ # You can safely remove this callback if you don't allow login from any of your services
+ before_create :create_user
+
+ field :token, :type => String
+ field :secret, :type => String
+
+ index :token
+
+ # Add the following to your user model:
+ #
+ # embeds_many :consumer_tokens
+ # index "consumer_tokens.token"
+ #
+ referenced_in :user, :inverse_of => :consumer_tokens
+
+ def self.find_or_create_from_access_token(user,access_token)
+ secret = access_token.respond_to?(:secret) ? access_token.secret : nil
+
+ if user
+ user.consumer_tokens.where(:_type=>self.to_s,:token=>access_token.token).first ||
+ self.create!(:_type=>self.to_s,:token=>access_token.token, :secret=>secret, :user=>user)
+ else
+ user = User.where("consumer_tokens._type"=>self.to_s,"consumer_tokens.token"=>access_token.token).first
+ if user
+ user.consumer_tokens.detect{|t| t.token==access_token.token && t.is_a?(self)}
+ else
+ user = User.new
+ self.create!(:_type=>self.to_s,:token=>access_token.token, :secret=>secret, :user=>user)
+ user.save!
+ user.consumer_tokens.last
+ end
+ end
+ end
+
+end
12 consumer/app/models/test_token.rb
@@ -0,0 +1,12 @@
+class TestToken < ConsumerToken
+ TEST_SETTINGS = {
+ :site => 'http://localhost:3000',
+ :request_token_path => '/oauth/request_token',
+ :access_token_path => '/oauth/access_token',
+ :authorize_path => '/oauth/authorize'
+ }
+
+ def self.consumer(options={})
+ @consumer ||= OAuth::Consumer.new(credentials[:key], credentials[:secret], TEST_SETTINGS.merge(options))
+ end
+end
12 consumer/app/models/user.rb
@@ -0,0 +1,12 @@
+class User
+ include Mongoid::Document
+ # Include default devise modules. Others available are:
+ # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
+ devise :database_authenticatable, :registerable,
+ :recoverable, :rememberable, :trackable, :validatable
+
+ references_one :test, :class_name => "TestToken", :dependent => :destroy
+
+ references_many :consumer_tokens
+ index "consumer_tokens.token"
+end
14 consumer/app/views/layouts/application.html.erb
@@ -0,0 +1,14 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>Consumer</title>
+ <%= stylesheet_link_tag :all %>
+ <%= javascript_include_tag :defaults %>
+ <%= csrf_meta_tag %>
+</head>
+<body>
+
+<%= yield %>
+
+</body>
+</html>
29 consumer/app/views/oauth_consumers/index.html.erb
@@ -0,0 +1,29 @@
+<h1>Services</h1>
+
+<% if @consumer_tokens.empty? %>
+ <p>
+ You are currently not connected to any external services.
+ </p>
+<% else %>
+ <p>
+ You are connected to the following services:
+ </p>
+ <ul>
+ <% @consumer_tokens.each do |token| %>
+ <li>
+ <%= link_to token.class.service_name.to_s.humanize, oauth_consumer_path(token.class.service_name) %>
+ </li>
+ <% end %>
+ </ul>
+<% end %>
+
+<% unless @services.empty? %>
+<h3>You can connect to the following services:</h3>
+<ul>
+ <% @services.each do |service| %>
+ <li>
+ <%= link_to service.to_s.humanize, oauth_consumer_path(service) %>
+ </li>
+ <% end %>
+</ul>
+<% end %>
7 consumer/app/views/oauth_consumers/show.html.erb
@@ -0,0 +1,7 @@
+<h1>You are already Connected to <%=params[:id].humanize%></h1>
+<% form_tag oauth_consumer_path(params[:id]),:method=>:delete do %>
+ <%=submit_tag "Disconnect" %>
+ or
+ <%=submit_tag "Reconnect" %>
+ if you experienced a problem.
+<% end %>
2  consumer/app/views/welcome/index.html.erb
@@ -0,0 +1,2 @@
+<h1>Welcome#index</h1>
+<p>Find me in app/views/welcome/index.html.erb</p>
4 consumer/config.ru
@@ -0,0 +1,4 @@
+# This file is used by Rack-based servers to start the application.
+
+require ::File.expand_path('../config/environment', __FILE__)
+run Consumer::Application
53 consumer/config/application.rb
@@ -0,0 +1,53 @@
+require File.expand_path('../boot', __FILE__)
+
+#require 'rails/all'
+require "action_controller/railtie"
+require "action_mailer/railtie"
+require "active_resource/railtie"
+require "rails/test_unit/railtie"
+# require "sprockets/railtie" # Uncomment this line for Rails 3.1+
+
+# If you have a Gemfile, require the gems listed there, including any gems
+# you've limited to :test, :development, or :production.
+Bundler.require(:default, Rails.env) if defined?(Bundler)
+
+module Consumer
+ class Application < Rails::Application
+ # Settings in config/environments/* take precedence over those specified here.
+ # Application configuration should go into files in config/initializers
+ # -- all .rb files in that directory are automatically loaded.
+
+ # Custom directories with classes and modules you want to be autoloadable.
+ # config.autoload_paths += %W(#{config.root}/extras)
+
+ # Only load the plugins named here, in the order given (default is alphabetical).
+ # :all can be used as a placeholder for all plugins not explicitly named.
+ # config.plugins = [ :exception_notification, :ssl_requirement, :all ]
+
+ # Activate observers that should always be running.
+ # config.active_record.observers = :cacher, :garbage_collector, :forum_observer
+
+ # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
+ # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
+ # config.time_zone = 'Central Time (US & Canada)'
+
+ # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
+ # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
+ # config.i18n.default_locale = :de
+
+ # JavaScript files you want as :defaults (application.js is always included).
+ # config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
+
+ # Configure the default encoding used in templates for Ruby 1.9.
+ config.encoding = "utf-8"
+
+ # Configure sensitive parameters which will be filtered from the log file.
+ config.filter_parameters += [:password]
+
+ config.generators do |g|
+ g.orm :mongoid
+ #g.template_engine :haml
+ #g.test_framework :rspec
+ end
+ end
+end
6 consumer/config/boot.rb
@@ -0,0 +1,6 @@
+require 'rubygems'
+
+# Set up gems listed in the Gemfile.
+ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
+
+require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
5 consumer/config/environment.rb
@@ -0,0 +1,5 @@
+# Load the rails application
+require File.expand_path('../application', __FILE__)
+
+# Initialize the rails application
+Consumer::Application.initialize!
26 consumer/config/environments/development.rb
@@ -0,0 +1,26 @@
+Consumer::Application.configure do
+ # Settings specified here will take precedence over those in config/application.rb
+
+ # In the development environment your application's code is reloaded on
+ # every request. This slows down response time but is perfect for development
+ # since you don't have to restart the webserver when you make code changes.
+ config.cache_classes = false
+
+ # Log error messages when you accidentally call methods on nil.
+ config.whiny_nils = true
+
+ # Show full error reports and disable caching
+ config.consider_all_requests_local = true
+ config.action_view.debug_rjs = true
+ config.action_controller.perform_caching = false
+
+ # Don't care if the mailer can't send
+ config.action_mailer.raise_delivery_errors = false
+
+ # Print deprecation notices to the Rails logger
+ config.active_support.deprecation = :log
+
+ # Only use best-standards-support built into browsers
+ config.action_dispatch.best_standards_support = :builtin
+end
+
49 consumer/config/environments/production.rb
@@ -0,0 +1,49 @@
+Consumer::Application.configure do
+ # Settings specified here will take precedence over those in config/application.rb
+
+ # The production environment is meant for finished, "live" apps.
+ # Code is not reloaded between requests
+ config.cache_classes = true
+
+ # Full error reports are disabled and caching is turned on
+ config.consider_all_requests_local = false
+ config.action_controller.perform_caching = true
+
+ # Specifies the header that your server uses for sending files
+ config.action_dispatch.x_sendfile_header = "X-Sendfile"
+
+ # For nginx:
+ # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'
+
+ # If you have no front-end server that supports something like X-Sendfile,
+ # just comment this out and Rails will serve the files
+
+ # See everything in the log (default is :info)
+ # config.log_level = :debug
+
+ # Use a different logger for distributed setups
+ # config.logger = SyslogLogger.new
+
+ # Use a different cache store in production
+ # config.cache_store = :mem_cache_store
+
+ # Disable Rails's static asset server
+ # In production, Apache or nginx will already do this
+ config.serve_static_assets = false
+
+ # Enable serving of images, stylesheets, and javascripts from an asset server
+ # config.action_controller.asset_host = "http://assets.example.com"
+
+ # Disable delivery errors, bad email addresses will be ignored
+ # config.action_mailer.raise_delivery_errors = false
+
+ # Enable threaded mode
+ # config.threadsafe!
+
+ # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
+ # the I18n.default_locale when a translation can not be found)
+ config.i18n.fallbacks = true
+
+ # Send deprecation notices to registered listeners
+ config.active_support.deprecation = :notify
+end
35 consumer/config/environments/test.rb
@@ -0,0 +1,35 @@
+Consumer::Application.configure do
+ # Settings specified here will take precedence over those in config/application.rb
+
+ # The test environment is used exclusively to run your application's
+ # test suite. You never need to work with it otherwise. Remember that
+ # your test database is "scratch space" for the test suite and is wiped
+ # and recreated between test runs. Don't rely on the data there!
+ config.cache_classes = true
+
+ # Log error messages when you accidentally call methods on nil.
+ config.whiny_nils = true
+
+ # Show full error reports and disable caching
+ config.consider_all_requests_local = true
+ config.action_controller.perform_caching = false
+
+ # Raise exceptions instead of rendering exception templates
+ config.action_dispatch.show_exceptions = false
+
+ # Disable request forgery protection in test environment
+ config.action_controller.allow_forgery_protection = false
+
+ # Tell Action Mailer not to deliver emails to the real world.
+ # The :test delivery method accumulates sent emails in the
+ # ActionMailer::Base.deliveries array.
+ config.action_mailer.delivery_method = :test
+
+ # Use SQL instead of Active Record's schema dumper when creating the test database.
+ # This is necessary if your schema can't be completely dumped by the schema dumper,
+ # like if you have constraints or database-specific column types
+ # config.active_record.schema_format = :sql
+
+ # Print deprecation notices to the stderr
+ config.active_support.deprecation = :stderr
+end
7 consumer/config/initializers/backtrace_silencers.rb
@@ -0,0 +1,7 @@
+# Be sure to restart your server when you modify this file.
+
+# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
+# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
+
+# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
+# Rails.backtrace_cleaner.remove_silencers!
209 consumer/config/initializers/devise.rb
@@ -0,0 +1,209 @@
+# Use this hook to configure devise mailer, warden hooks and so forth.
+# Many of these configuration options can be set straight in your model.
+Devise.setup do |config|
+ # ==> Mailer Configuration
+ # Configure the e-mail address which will be shown in Devise::Mailer,
+ # note that it will be overwritten if you use your own mailer class with default "from" parameter.
+ config.mailer_sender = "please-change-me-at-config-initializers-devise@example.com"
+
+ # Configure the class responsible to send e-mails.
+ # config.mailer = "Devise::Mailer"
+
+ # ==> ORM configuration
+ # Load and configure the ORM. Supports :active_record (default) and
+ # :mongoid (bson_ext recommended) by default. Other ORMs may be
+ # available as additional gems.
+ require 'devise/orm/mongoid'
+
+ # ==> Configuration for any authentication mechanism
+ # Configure which keys are used when authenticating a user. The default is
+ # just :email. You can configure it to use [:username, :subdomain], so for
+ # authenticating a user, both parameters are required. Remember that those
+ # parameters are used only when authenticating and not when retrieving from
+ # session. If you need permissions, you should implement that in a before filter.
+ # You can also supply a hash where the value is a boolean determining whether
+ # or not authentication should be aborted when the value is not present.
+ # config.authentication_keys = [ :email ]
+
+ # Configure parameters from the request object used for authentication. Each entry
+ # given should be a request method and it will automatically be passed to the
+ # find_for_authentication method and considered in your model lookup. For instance,
+ # if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
+ # The same considerations mentioned for authentication_keys also apply to request_keys.
+ # config.request_keys = []
+
+ # Configure which authentication keys should be case-insensitive.
+ # These keys will be downcased upon creating or modifying a user and when used
+ # to authenticate or find a user. Default is :email.
+ config.case_insensitive_keys = [ :email ]
+
+ # Configure which authentication keys should have whitespace stripped.
+ # These keys will have whitespace before and after removed upon creating or
+ # modifying a user and when used to authenticate or find a user. Default is :email.
+ config.strip_whitespace_keys = [ :email ]
+
+ # Tell if authentication through request.params is enabled. True by default.
+ # config.params_authenticatable = true
+
+ # Tell if authentication through HTTP Basic Auth is enabled. False by default.
+ # config.http_authenticatable = false
+
+ # If http headers should be returned for AJAX requests. True by default.
+ # config.http_authenticatable_on_xhr = true
+
+ # The realm used in Http Basic Authentication. "Application" by default.
+ # config.http_authentication_realm = "Application"
+
+ # It will change confirmation, password recovery and other workflows
+ # to behave the same regardless if the e-mail provided was right or wrong.
+ # Does not affect registerable.
+ # config.paranoid = true
+
+ # ==> Configuration for :database_authenticatable
+ # For bcrypt, this is the cost for hashing the password and defaults to 10. If
+ # using other encryptors, it sets how many times you want the password re-encrypted.
+ #
+ # Limiting the stretches to just one in testing will increase the performance of
+ # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
+ # a value less than 10 in other environments.
+ config.stretches = Rails.env.test? ? 1 : 10
+
+ # Setup a pepper to generate the encrypted password.
+ # config.pepper = "754c3bfcdc4c589da292bcb75a7261de2f77bc3c9448dafcfe214af09b214cbcb5dec797832f2a57739d5572f9e53a6199cc839cc7a0bbbdc25ec1864b6da97a"
+
+ # ==> Configuration for :confirmable
+ # A period that the user is allowed to access the website even without
+ # confirming his account. For instance, if set to 2.days, the user will be
+ # able to access the website for two days without confirming his account,
+ # access will be blocked just in the third day. Default is 0.days, meaning
+ # the user cannot access the website without confirming his account.
+ # config.confirm_within = 2.days
+
+ # Defines which key will be used when confirming an account
+ # config.confirmation_keys = [ :email ]
+
+ # ==> Configuration for :rememberable
+ # The time the user will be remembered without asking for credentials again.
+ # config.remember_for = 2.weeks
+
+ # If true, a valid remember token can be re-used between multiple browsers.
+ # config.remember_across_browsers = true
+
+ # If true, extends the user's remember period when remembered via cookie.
+ # config.extend_remember_period = false
+
+ # If true, uses the password salt as remember token. This should be turned
+ # to false if you are not using database authenticatable.
+ config.use_salt_as_remember_token = true
+
+ # Options to be passed to the created cookie. For instance, you can set
+ # :secure => true in order to force SSL only cookies.
+ # config.cookie_options = {}
+
+ # ==> Configuration for :validatable
+ # Range for password length. Default is 6..128.
+ # config.password_length = 6..128
+
+ # Email regex used to validate email formats. It simply asserts that
+ # an one (and only one) @ exists in the given string. This is mainly
+ # to give user feedback and not to assert the e-mail validity.
+ # config.email_regexp = /\A[^@]+@[^@]+\z/
+
+ # ==> Configuration for :timeoutable
+ # The time you want to timeout the user session without activity. After this
+ # time the user will be asked for credentials again. Default is 30 minutes.
+ # config.timeout_in = 30.minutes
+
+ # ==> Configuration for :lockable
+ # Defines which strategy will be used to lock an account.
+ # :failed_attempts = Locks an account after a number of failed attempts to sign in.
+ # :none = No lock strategy. You should handle locking by yourself.
+ # config.lock_strategy = :failed_attempts
+
+ # Defines which key will be used when locking and unlocking an account
+ # config.unlock_keys = [ :email ]
+
+ # Defines which strategy will be used to unlock an account.
+ # :email = Sends an unlock link to the user email
+ # :time = Re-enables login after a certain amount of time (see :unlock_in below)
+ # :both = Enables both strategies
+ # :none = No unlock strategy. You should handle unlocking by yourself.
+ # config.unlock_strategy = :both
+
+ # Number of authentication tries before locking an account if lock_strategy
+ # is failed attempts.
+ # config.maximum_attempts = 20
+
+ # Time interval to unlock the account if :time is enabled as unlock_strategy.
+ # config.unlock_in = 1.hour
+
+ # ==> Configuration for :recoverable
+ #
+ # Defines which key will be used when recovering the password for an account
+ # config.reset_password_keys = [ :email ]
+
+ # Time interval you can reset your password with a reset password key.
+ # Don't put a too small interval or your users won't have the time to
+ # change their passwords.
+ config.reset_password_within = 2.hours
+
+ # ==> Configuration for :encryptable
+ # Allow you to use another encryption algorithm besides bcrypt (default). You can use
+ # :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1,
+ # :authlogic_sha512 (then you should set stretches above to 20 for default behavior)
+ # and :restful_authentication_sha1 (then you should set stretches to 10, and copy
+ # REST_AUTH_SITE_KEY to pepper)
+ # config.encryptor = :sha512
+
+ # ==> Configuration for :token_authenticatable
+ # Defines name of the authentication token params key
+ # config.token_authentication_key = :auth_token
+
+ # If true, authentication through token does not store user in session and needs
+ # to be supplied on each request. Useful if you are using the token as API token.
+ # config.stateless_token = false
+
+ # ==> Scopes configuration
+ # Turn scoped views on. Before rendering "sessions/new", it will first check for
+ # "users/sessions/new". It's turned off by default because it's slower if you
+ # are using only default views.
+ # config.scoped_views = false
+
+ # Configure the default scope given to Warden. By default it's the first
+ # devise role declared in your routes (usually :user).
+ # config.default_scope = :user
+
+ # Configure sign_out behavior.
+ # Sign_out action can be scoped (i.e. /users/sign_out affects only :user scope).
+ # The default is true, which means any logout action will sign out all active scopes.
+ # config.sign_out_all_scopes = true
+
+ # ==> Navigation configuration
+ # Lists the formats that should be treated as navigational. Formats like
+ # :html, should redirect to the sign in page when the user does not have
+ # access, but formats like :xml or :json, should return 401.
+ #
+ # If you have any extra navigational formats, like :iphone or :mobile, you
+ # should add them to the navigational formats lists.
+ #
+ # The :"*/*" and "*/*" formats below is required to match Internet
+ # Explorer requests.
+ # config.navigational_formats = [:"*/*", "*/*", :html]
+
+ # The default HTTP method used to sign out a resource. Default is :delete.
+ config.sign_out_via = :delete
+
+ # ==> OmniAuth
+ # Add a new OmniAuth provider. Check the wiki for more information on setting
+ # up on your models and hooks.
+ # config.omniauth :github, 'APP_ID', 'APP_SECRET', :scope => 'user,public_repo'
+
+ # ==> Warden configuration
+ # If you want to use other strategies, that are not supported by Devise, or
+ # change the failure app, you can configure them inside the config.warden block.
+ #
+ # config.warden do |manager|
+ # manager.intercept_401 = false
+ # manager.default_strategies(:scope => :user).unshift :some_external_strategy
+ # end
+end
10 consumer/config/initializers/inflections.rb
@@ -0,0 +1,10 @@
+# Be sure to restart your server when you modify this file.
+
+# Add new inflection rules using the following format
+# (all these examples are active by default):
+# ActiveSupport::Inflector.inflections do |inflect|
+# inflect.plural /^(ox)$/i, '\1en'
+# inflect.singular /^(ox)en/i, '\1'
+# inflect.irregular 'person', 'people'
+# inflect.uncountable %w( fish sheep )
+# end
5 consumer/config/initializers/mime_types.rb
@@ -0,0 +1,5 @@
+# Be sure to restart your server when you modify this file.
+
+# Add new mime types for use in respond_to blocks:
+# Mime::Type.register "text/richtext", :rtf
+# Mime::Type.register_alias "text/html", :iphone
73 consumer/config/initializers/oauth_consumers.rb
@@ -0,0 +1,73 @@
+# edit this file to contain credentials for the OAuth services you support.
+# each entry needs a corresponding token model.
+#
+# eg. :twitter => TwitterToken, :hour_feed => HourFeedToken etc.
+#
+OAUTH_CREDENTIALS = {
+ :test => {
+ :key => 'd8KBiaD98Mnp2vyB9A8ZSAT0vpKu5kdFtAXUsZup',
+ :secret => 'UDdD5HAefrRZ1afguDy0WrTALYwZ8KXWKgLiSJCE',
+ :expose => true
+ }
+# :twitter=>{
+# :key=>"",
+# :secret=>"",
+# :client=>:twitter_gem, # :twitter_gem or :oauth_gem (defaults to :twitter_gem)
+# :expose => false, # expose client at /oauth_consumers/twitter/client see docs
+# :allow_login => true # Use :allow_login => true to allow user to login to account
+# },
+# :google=>{
+# :key=>"",
+# :secret=>"",
+# :expose => false, # expose client at /oauth_consumers/google/client see docs
+# :scope=>"" # see http://code.google.com/apis/gdata/faq.html#AuthScopes
+# },
+# :github=>{
+# :key => "",
+# :secret => "",
+# :expose => false, # expose client at /oauth_consumers/twitter/client see docs
+#
+# },
+# :facebook=>{
+# :key => "",
+# :secret => ""
+# },
+# :agree2=>{
+# :key=>"",
+# :secret=>""
+# },
+# :fireeagle=>{
+# :key=>"",
+# :secret=>""
+# },
+# :oauth2_server => {
+# :key=>"",
+# :secret=>"",
+# :oauth_version => 2
+# :options=>{ # OAuth::Consumer options
+# :site=>"http://hourfeed.com" # Remember to add a site for a generic OAuth site
+# }
+# },
+# :hour_feed=>{
+# :key=>"",
+# :secret=>"",
+# :options=>{ # OAuth::Consumer options
+# :site=>"http://hourfeed.com" # Remember to add a site for a generic OAuth site
+# }
+# },
+# :nu_bux=>{
+# :key=>"",
+# :secret=>"",
+# :super_class=>"OpenTransactToken", # if a OAuth service follows a particular standard
+# # with a token implementation you can set the superclass
+# # to use
+# :options=>{ # OAuth::Consumer options
+# :site=>"http://nubux.heroku.com"
+# }
+# }
+}
+#
+OAUTH_CREDENTIALS={
+} unless defined? OAUTH_CREDENTIALS
+
+load 'oauth/models/consumers/service_loader.rb'
7 consumer/config/initializers/secret_token.rb
@@ -0,0 +1,7 @@
+# Be sure to restart your server when you modify this file.
+
+# Your secret key for verifying the integrity of signed cookies.
+# If you change this key, all old signed cookies will become invalid!
+# Make sure the secret is at least 30 characters and all random,
+# no regular words or you'll be exposed to dictionary attacks.
+Consumer::Application.config.secret_token = '56674b38bf87e61f6244750433ed8750c04e53fcc9c662c322f8bd5aa22856712d2ecc7cfb7ce4a7693f91a39d7a5488933754b8ff8659ba70ec9b3052ae322f'
8 consumer/config/initializers/session_store.rb
@@ -0,0 +1,8 @@
+# Be sure to restart your server when you modify this file.
+
+Consumer::Application.config.session_store :cookie_store, :key => '_consumer_session'
+
+# Use the database for sessions instead of the cookie-based default,
+# which shouldn't be used to store highly confidential information
+# (create the session table with "rails generate session_migration")
+# Consumer::Application.config.session_store :active_record_store
58 consumer/config/locales/devise.en.yml
@@ -0,0 +1,58 @@
+# Additional translations at https://github.com/plataformatec/devise/wiki/I18n
+
+en:
+ errors:
+ messages:
+ expired: "has expired, please request a new one"
+ not_found: "not found"
+ already_confirmed: "was already confirmed, please try signing in"
+ not_locked: "was not locked"
+ not_saved:
+ one: "1 error prohibited this %{resource} from being saved:"
+ other: "%{count} errors prohibited this %{resource} from being saved:"
+
+ devise:
+ failure:
+ already_authenticated: 'You are already signed in.'
+ unauthenticated: 'You need to sign in or sign up before continuing.'
+ unconfirmed: 'You have to confirm your account before continuing.'
+ locked: 'Your account is locked.'
+ invalid: 'Invalid email or password.'
+ invalid_token: 'Invalid authentication token.'
+ timeout: 'Your session expired, please sign in again to continue.'
+ inactive: 'Your account was not activated yet.'
+ sessions:
+ signed_in: 'Signed in successfully.'
+ signed_out: 'Signed out successfully.'
+ passwords:
+ send_instructions: 'You will receive an email with instructions about how to reset your password in a few minutes.'
+ updated: 'Your password was changed successfully. You are now signed in.'
+ updated_not_active: 'Your password was changed successfully.'
+ send_paranoid_instructions: "If your e-mail exists on our database, you will receive a password recovery link on your e-mail"
+ confirmations:
+ send_instructions: 'You will receive an email with instructions about how to confirm your account in a few minutes.'
+ send_paranoid_instructions: 'If your e-mail exists on our database, you will receive an email with instructions about how to confirm your account in a few minutes.'
+ confirmed: 'Your account was successfully confirmed. You are now signed in.'
+ registrations:
+ signed_up: 'Welcome! You have signed up successfully.'
+ inactive_signed_up: 'You have signed up successfully. However, we could not sign you in because your account is %{reason}.'
+ updated: 'You updated your account successfully.'
+ destroyed: 'Bye! Your account was successfully cancelled. We hope to see you again soon.'
+ reasons:
+ inactive: 'inactive'
+ unconfirmed: 'unconfirmed'
+ locked: 'locked'
+ unlocks:
+ send_instructions: 'You will receive an email with instructions about how to unlock your account in a few minutes.'
+ unlocked: 'Your account was successfully unlocked. You are now signed in.'
+ send_paranoid_instructions: 'If your account exists, you will receive an email with instructions about how to unlock it in a few minutes.'
+ omniauth_callbacks:
+ success: 'Successfully authorized from %{kind} account.'
+ failure: 'Could not authorize you from %{kind} because "%{reason}".'
+ mailer:
+ confirmation_instructions:
+ subject: 'Confirmation instructions'
+ reset_password_instructions:
+ subject: 'Reset password instructions'
+ unlock_instructions:
+ subject: 'Unlock Instructions'
5 consumer/config/locales/en.yml
@@ -0,0 +1,5 @@
+# Sample localization file for English. Add more files in this directory for other locales.
+# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
+
+en:
+ hello: "Hello world"
20 consumer/config/mongoid.yml
@@ -0,0 +1,20 @@
+development:
+ host: localhost
+ database: consumer_development
+
+test:
+ host: localhost
+ database: consumer_test
+
+# set these environment variables on your prod server
+production:
+ host: <%= ENV['MONGOID_HOST'] %>
+ port: <%= ENV['MONGOID_PORT'] %>
+ username: <%= ENV['MONGOID_USERNAME'] %>
+ password: <%= ENV['MONGOID_PASSWORD'] %>
+ database: <%= ENV['MONGOID_DATABASE'] %>
+ # slaves:
+ # - host: slave1.local
+ # port: 27018
+ # - host: slave2.local
+ # port: 27019
15 consumer/config/routes.rb
@@ -0,0 +1,15 @@
+Consumer::Application.routes.draw do
+ resources :oauth_consumers do
+ member do
+ get :callback
+ get :callback2
+ match 'client/*endpoint' => 'oauth_consumers#client'
+ end
+ end
+
+ get "welcome/index"
+
+ devise_for :users
+
+ root :to => 'welcome#index'
+end
7 consumer/db/seeds.rb
@@ -0,0 +1,7 @@
+# This file should contain all the record creation needed to seed the database with its default values.
+# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
+#
+# Examples:
+#
+# cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }])
+# Mayor.create(:name => 'Daley', :city => cities.first)
2  consumer/doc/README_FOR_APP
@@ -0,0 +1,2 @@
+Use this README file to introduce your application and point to useful places in the API for learning more.
+Run "rake doc:app" to generate API documentation for your models, controllers, helpers, and libraries.
0  consumer/lib/tasks/.gitkeep
No changes.
26 consumer/public/404.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>The page you were looking for doesn't exist (404)</title>
+ <style type="text/css">
+ body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
+ div.dialog {
+ width: 25em;
+ padding: 0 4em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #ccc;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ }
+ h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
+ </style>
+</head>
+
+<body>
+ <!-- This file lives in public/404.html -->
+ <div class="dialog">
+ <h1>The page you were looking for doesn't exist.</h1>
+ <p>You may have mistyped the address or the page may have moved.</p>
+ </div>
+</body>
+</html>
26 consumer/public/422.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>The change you wanted was rejected (422)</title>
+ <style type="text/css">
+ body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
+ div.dialog {
+ width: 25em;
+ padding: 0 4em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #ccc;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ }
+ h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
+ </style>
+</head>
+
+<body>
+ <!-- This file lives in public/422.html -->
+ <div class="dialog">
+ <h1>The change you wanted was rejected.</h1>
+ <p>Maybe you tried to change something you didn't have access to.</p>
+ </div>
+</body>
+</html>
26 consumer/public/500.html
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>We're sorry, but something went wrong (500)</title>
+ <style type="text/css">
+ body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
+ div.dialog {
+ width: 25em;
+ padding: 0 4em;
+ margin: 4em auto 0 auto;
+ border: 1px solid #ccc;
+ border-right-color: #999;
+ border-bottom-color: #999;
+ }
+ h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
+ </style>
+</head>
+
+<body>
+ <!-- This file lives in public/500.html -->
+ <div class="dialog">
+ <h1>We're sorry, but something went wrong.</h1>
+ <p>We've been notified about this issue and we'll take a look at it shortly.</p>
+ </div>
+</body>
+</html>
0  consumer/public/favicon.ico
No changes.
BIN  consumer/public/images/rails.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2  consumer/public/javascripts/application.js
@@ -0,0 +1,2 @@
+// Place your application-specific JavaScript functions and classes here
+// This file is automatically included by javascript_include_tag :defaults
965 consumer/public/javascripts/controls.js
@@ -0,0 +1,965 @@
+// script.aculo.us controls.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009
+
+// Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+// (c) 2005-2009 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
+// (c) 2005-2009 Jon Tirsen (http://www.tirsen.com)
+// Contributors:
+// Richard Livsey
+// Rahul Bhargava
+// Rob Wills
+//
+// script.aculo.us is freely distributable under the terms of an MIT-style license.
+// For details, see the script.aculo.us web site: http://script.aculo.us/
+
+// Autocompleter.Base handles all the autocompletion functionality
+// that's independent of the data source for autocompletion. This
+// includes drawing the autocompletion menu, observing keyboard
+// and mouse events, and similar.
+//
+// Specific autocompleters need to provide, at the very least,
+// a getUpdatedChoices function that will be invoked every time
+// the text inside the monitored textbox changes. This method
+// should get the text for which to provide autocompletion by
+// invoking this.getToken(), NOT by directly accessing
+// this.element.value. This is to allow incremental tokenized
+// autocompletion. Specific auto-completion logic (AJAX, etc)
+// belongs in getUpdatedChoices.
+//
+// Tokenized incremental autocompletion is enabled automatically
+// when an autocompleter is instantiated with the 'tokens' option
+// in the options parameter, e.g.:
+// new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
+// will incrementally autocomplete with a comma as the token.
+// Additionally, ',' in the above example can be replaced with
+// a token array, e.g. { tokens: [',', '\n'] } which
+// enables autocompletion on multiple tokens. This is most
+// useful when one of the tokens is \n (a newline), as it
+// allows smart autocompletion after linebreaks.
+
+if(typeof Effect == 'undefined')
+ throw("controls.js requires including script.aculo.us' effects.js library");
+
+var Autocompleter = { };
+Autocompleter.Base = Class.create({
+ baseInitialize: function(element, update, options) {
+ element = $(element);
+ this.element = element;
+ this.update = $(update);
+ this.hasFocus = false;
+ this.changed = false;
+ this.active = false;
+ this.index = 0;
+ this.entryCount = 0;
+ this.oldElementValue = this.element.value;
+
+ if(this.setOptions)
+ this.setOptions(options);
+ else
+ this.options = options || { };
+
+ this.options.paramName = this.options.paramName || this.element.name;
+ this.options.tokens = this.options.tokens || [];
+ this.options.frequency = this.options.frequency || 0.4;
+ this.options.minChars = this.options.minChars || 1;
+ this.options.onShow = this.options.onShow ||
+ function(element, update){
+ if(!update.style.position || update.style.position=='absolute') {
+ update.style.position = 'absolute';
+ Position.clone(element, update, {
+ setHeight: false,
+ offsetTop: element.offsetHeight
+ });
+ }
+ Effect.Appear(update,{duration:0.15});
+ };
+ this.options.onHide = this.options.onHide ||
+ function(element, update){ new Effect.Fade(update,{duration:0.15}) };
+
+ if(typeof(this.options.tokens) == 'string')
+ this.options.tokens = new Array(this.options.tokens);
+ // Force carriage returns as token delimiters anyway
+ if (!this.options.tokens.include('\n'))
+ this.options.tokens.push('\n');
+
+ this.observer = null;
+
+ this.element.setAttribute('autocomplete','off');
+
+ Element.hide(this.update);
+
+ Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
+ Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this));
+ },
+
+ show: function() {
+ if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
+ if(!this.iefix &&
+ (Prototype.Browser.IE) &&
+ (Element.getStyle(this.update, 'position')=='absolute')) {
+ new Insertion.After(this.update,
+ '<iframe id="' + this.update.id + '_iefix" '+
+ 'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
+ 'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
+ this.iefix = $(this.update.id+'_iefix');
+ }
+ if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
+ },
+
+ fixIEOverlapping: function() {
+ Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
+ this.iefix.style.zIndex = 1;
+ this.update.style.zIndex = 2;
+ Element.show(this.iefix);
+ },
+
+ hide: function() {
+ this.stopIndicator();
+ if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
+ if(this.iefix) Element.hide(this.iefix);
+ },
+
+ startIndicator: function() {
+ if(this.options.indicator) Element.show(this.options.indicator);
+ },
+
+ stopIndicator: function() {
+ if(this.options.indicator) Element.hide(this.options.indicator);
+ },
+
+ onKeyPress: function(event) {
+ if(this.active)
+ switch(event.keyCode) {
+ case Event.KEY_TAB:
+ case Event.KEY_RETURN:
+ this.selectEntry();
+ Event.stop(event);
+ case Event.KEY_ESC:
+ this.hide();
+ this.active = false;
+ Event.stop(event);
+ return;
+ case Event.KEY_LEFT:
+ case Event.KEY_RIGHT:
+ return;
+ case Event.KEY_UP:
+ this.markPrevious();
+ this.render();
+ Event.stop(event);
+ return;
+ case Event.KEY_DOWN:
+ this.markNext();
+ this.render();
+ Event.stop(event);
+ return;
+ }
+ else
+ if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
+ (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;
+
+ this.changed = true;
+ this.hasFocus = true;
+
+ if(this.observer) clearTimeout(this.observer);
+ this.observer =
+ setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
+ },
+
+ activate: function() {
+ this.changed = false;
+ this.hasFocus = true;
+ this.getUpdatedChoices();
+ },
+
+ onHover: function(event) {
+ var element = Event.findElement(event, 'LI');
+ if(this.index != element.autocompleteIndex)
+ {
+ this.index = element.autocompleteIndex;
+ this.render();
+ }
+ Event.stop(event);
+ },
+
+ onClick: function(event) {
+ var element = Event.findElement(event, 'LI');
+ this.index = element.autocompleteIndex;
+ this.selectEntry();
+ this.hide();
+ },
+
+ onBlur: function(event) {
+ // needed to make click events working
+ setTimeout(this.hide.bind(this), 250);
+ this.hasFocus = false;
+ this.active = false;
+ },
+
+ render: function() {
+ if(this.entryCount > 0) {
+ for (var i = 0; i < this.entryCount; i++)
+ this.index==i ?
+ Element.addClassName(this.getEntry(i),"selected") :
+ Element.removeClassName(this.getEntry(i),"selected");
+ if(this.hasFocus) {
+ this.show();
+ this.active = true;
+ }
+ } else {
+ this.active = false;
+ this.hide();
+ }
+ },
+
+ markPrevious: function() {
+ if(this.index > 0) this.index--;
+ else this.index = this.entryCount-1;
+ this.getEntry(this.index).scrollIntoView(true);
+ },
+
+ markNext: function() {
+ if(this.index < this.entryCount-1) this.index++;
+ else this.index = 0;
+ this.getEntry(this.index).scrollIntoView(false);
+ },
+
+ getEntry: function(index) {
+ return this.update.firstChild.childNodes[index];
+ },
+
+ getCurrentEntry: function() {
+ return this.getEntry(this.index);
+ },
+
+ selectEntry: function() {
+ this.active = false;
+ this.updateElement(this.getCurrentEntry());
+ },
+
+ updateElement: function(selectedElement) {
+ if (this.options.updateElement) {
+ this.options.updateElement(selectedElement);
+ return;
+ }
+ var value = '';
+ if (this.options.select) {
+ var nodes = $(selectedElement).select('.' + this.options.select) || [];
+ if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
+ } else
+ value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');
+
+ var bounds = this.getTokenBounds();
+ if (bounds[0] != -1) {
+ var newValue = this.element.value.substr(0, bounds[0]);
+ var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
+ if (whitespace)
+ newValue += whitespace[0];
+ this.element.value = newValue + value + this.element.value.substr(bounds[1]);
+ } else {
+ this.element.value = value;
+ }
+ this.oldElementValue = this.element.value;
+ this.element.focus();
+
+ if (this.options.afterUpdateElement)
+ this.options.afterUpdateElement(this.element, selectedElement);
+ },
+
+ updateChoices: function(choices) {
+ if(!this.changed && this.hasFocus) {
+ this.update.innerHTML = choices;
+ Element.cleanWhitespace(this.update);
+ Element.cleanWhitespace(this.update.down());
+
+ if(this.update.firstChild && this.update.down().childNodes) {
+ this.entryCount =
+ this.update.down().childNodes.length;
+ for (var i = 0; i < this.entryCount; i++) {
+ var entry = this.getEntry(i);
+ entry.autocompleteIndex = i;
+ this.addObservers(entry);
+ }
+ } else {
+ this.entryCount = 0;
+ }
+
+ this.stopIndicator();
+ this.index = 0;
+
+ if(this.entryCount==1 && this.options.autoSelect) {
+ this.selectEntry();
+ this.hide();
+ } else {
+ this.render();
+ }
+ }
+ },
+
+ addObservers: function(element) {
+ Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
+ Event.observe(element, "click", this.onClick.bindAsEventListener(this));
+ },
+
+ onObserverEvent: function() {
+ this.changed = false;
+ this.tokenBounds = null;
+ if(this.getToken().length>=this.options.minChars) {
+ this.getUpdatedChoices();
+ } else {
+ this.active = false;
+ this.hide();
+ }
+ this.oldElementValue = this.element.value;
+ },
+
+ getToken: function() {
+ var bounds = this.getTokenBounds();
+ return this.element.value.substring(bounds[0], bounds[1]).strip();
+ },
+
+ getTokenBounds: function() {
+ if (null != this.tokenBounds) return this.tokenBounds;
+ var value = this.element.value;
+ if (value.strip().empty()) return [-1, 0];
+ var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue);
+ var offset = (diff == this.oldElementValue.length ? 1 : 0);
+ var prevTokenPos = -1, nextTokenPos = value.length;
+ var tp;
+ for (var index = 0, l = this.options.tokens.length; index < l; ++index) {
+ tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1);
+ if (tp > prevTokenPos) prevTokenPos = tp;
+ tp = value.indexOf(this.options.tokens[index], diff + offset);
+ if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp;
+ }
+ return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]);
+ }
+});
+
+Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) {
+ var boundary = Math.min(newS.length, oldS.length);
+ for (var index = 0; index < boundary; ++index)
+ if (newS[index] != oldS[index])
+ return index;
+ return boundary;
+};
+
+Ajax.Autocompleter = Class.create(Autocompleter.Base, {
+ initialize: function(element, update, url, options) {
+ this.baseInitialize(element, update, options);
+ this.options.asynchronous = true;
+ this.options.onComplete = this.onComplete.bind(this);
+ this.options.defaultParams = this.options.parameters || null;
+ this.url = url;
+ },
+
+ getUpdatedChoices: function() {
+ this.startIndicator();
+
+ var entry = encodeURIComponent(this.options.paramName) + '=' +
+ encodeURIComponent(this.getToken());
+
+ this.options.parameters = this.options.callback ?
+ this.options.callback(this.element, entry) : entry;
+
+ if(this.options.defaultParams)
+ this.options.parameters += '&' + this.options.defaultParams;
+
+ new Ajax.Request(this.url, this.options);
+ },
+
+ onComplete: function(request) {
+ this.updateChoices(request.responseText);
+ }
+});
+
+// The local array autocompleter. Used when you'd prefer to
+// inject an array of autocompletion options into the page, rather
+// than sending out Ajax queries, which can be quite slow sometimes.
+//
+// The constructor takes four parameters. The first two are, as usual,
+// the id of the monitored textbox, and id of the autocompletion menu.
+// The third is the array you want to autocomplete from, and the fourth
+// is the options block.
+//
+// Extra local autocompletion options:
+// - choices - How many autocompletion choices to offer
+//
+// - partialSearch - If false, the autocompleter will match entered
+// text only at the beginning of strings in the
+// autocomplete array. Defaults to true, which will
+// match text at the beginning of any *word* in the
+// strings in the autocomplete array. If you want to
+// search anywhere in the string, additionally set
+// the option fullSearch to true (default: off).
+//
+// - fullSsearch - Search anywhere in autocomplete array strings.
+//
+// - partialChars - How many characters to enter before triggering
+// a partial match (unlike minChars, which defines
+// how many characters are required to do any match
+// at all). Defaults to 2.
+//
+// - ignoreCase - Whether to ignore case when autocompleting.
+// Defaults to true.
+//
+// It's possible to pass in a custom function as the 'selector'
+// option, if you prefer to write your own autocompletion logic.
+// In that case, the other options above will not apply unless
+// you support them.
+
+Autocompleter.Local = Class.create(Autocompleter.Base, {
+ initialize: function(element, update, array, options) {
+ this.baseInitialize(element, update, options);
+ this.options.array = array;
+ },
+
+ getUpdatedChoices: function() {
+ this.updateChoices(this.options.selector(this));
+ },
+
+ setOptions: function(options) {
+ this.options = Object.extend({
+ choices: 10,
+ partialSearch: true,
+ partialChars: 2,
+ ignoreCase: true,
+ fullSearch: false,
+ selector: function(instance) {
+ var ret = []; // Beginning matches
+ var partial = []; // Inside matches
+ var entry = instance.getToken();
+ var count = 0;
+
+ for (var i = 0; i < instance.options.array.length &&
+ ret.length < instance.options.choices ; i++) {
+
+ var elem = instance.options.array[i];
+ var foundPos = instance.options.ignoreCase ?
+ elem.toLowerCase().indexOf(entry.toLowerCase()) :
+ elem.indexOf(entry);
+
+ while (foundPos != -1) {
+ if (foundPos == 0 && elem.length != entry.length) {
+ ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" +
+ elem.substr(entry.length) + "</li>");
+ break;
+ } else if (entry.length >= instance.options.partialChars &&
+ instance.options.partialSearch && foundPos != -1) {
+ if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) {
+ partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" +
+ elem.substr(foundPos, entry.length) + "</strong>" + elem.substr(
+ foundPos + entry.length) + "</li>");
+ break;
+ }
+ }
+
+ foundPos = instance.options.ignoreCase ?
+ elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) :
+ elem.indexOf(entry, foundPos + 1);
+
+ }
+ }
+ if (partial.length)
+ ret = ret.concat(partial.slice(0, instance.options.choices - ret.length));
+ return "<ul>" + ret.join('') + "</ul>";
+ }
+ }, options || { });
+ }
+});
+
+// AJAX in-place editor and collection editor
+// Full rewrite by Christophe Porteneuve <tdd@tddsworld.com> (April 2007).
+
+// Use this if you notice weird scrolling problems on some browsers,
+// the DOM might be a bit confused when this gets called so do this
+// waits 1 ms (with setTimeout) until it does the activation
+Field.scrollFreeActivate = function(field) {
+ setTimeout(function() {
+ Field.activate(field);
+ }, 1);
+};
+
+Ajax.InPlaceEditor = Class.create({
+ initialize: function(element, url, options) {
+ this.url = url;
+ this.element = element = $(element);
+ this.prepareOptions();
+ this._controls = { };
+ arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!!
+ Object.extend(this.options, options || { });
+ if (!this.options.formId && this.element.id) {
+ this.options.formId = this.element.id + '-inplaceeditor';
+ if ($(this.options.formId))
+ this.options.formId = '';
+ }
+ if (this.options.externalControl)
+ this.options.externalControl = $(this.options.externalControl);
+ if (!this.options.externalControl)
+ this.options.externalControlOnly = false;
+ this._originalBackground = this.element.getStyle('background-color') || 'transparent';
+ this.element.title = this.options.clickToEditText;
+ this._boundCancelHandler = this.handleFormCancellation.bind(this);
+ this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this);
+ this._boundFailureHandler = this.handleAJAXFailure.bind(this);
+ this._boundSubmitHandler = this.handleFormSubmission.bind(this);
+ this._boundWrapperHandler = this.wrapUp.bind(this);
+ this.registerListeners();
+ },
+ checkForEscapeOrReturn: function(e) {
+ if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return;
+ if (Event.KEY_ESC == e.keyCode)
+ this.handleFormCancellation(e);
+ else if (Event.KEY_RETURN == e.keyCode)
+ this.handleFormSubmission(e);
+ },
+ createControl: function(mode, handler, extraClasses) {
+ var control = this.options[mode + 'Control'];
+ var text = this.options[mode + 'Text'];
+ if ('button' == control) {
+ var btn = document.createElement('input');
+ btn.type = 'submit';
+ btn.value = text;
+ btn.className = 'editor_' + mode + '_button';
+ if ('cancel' == mode)
+ btn.onclick = this._boundCancelHandler;
+ this._form.appendChild(btn);
+ this._controls[mode] = btn;
+ } else if ('link' == control) {
+ var link = document.createElement('a');
+ link.href = '#';
+ link.appendChild(document.createTextNode(text));
+ link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler;
+ link.className = 'editor_' + mode + '_link';
+ if (extraClasses)
+ link.className += ' ' + extraClasses;
+ this._form.appendChild(link);
+ this._controls[mode] = link;
+ }
+ },
+ createEditField: function() {
+ var text = (this.options.loadTextURL ? this.options.loadingText : this.getText());
+ var fld;
+ if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) {
+ fld = document.createElement('input');
+ fld.type = 'text';
+ var size = this.options.size || this.options.cols || 0;
+ if (0 < size) fld.size = size;
+ } else {
+ fld = document.createElement('textarea');
+ fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows);
+ fld.cols = this.options.cols || 40;
+ }
+ fld.name = this.options.paramName;
+ fld.value = text; // No HTML breaks conversion anymore
+ fld.className = 'editor_field';
+ if (this.options.submitOnBlur)
+ fld.onblur = this._boundSubmitHandler;
+ this._controls.editor = fld;
+ if (this.options.loadTextURL)
+ this.loadExternalText();
+ this._form.appendChild(this._controls.editor);
+ },
+ createForm: function() {
+ var ipe = this;
+ function addText(mode, condition) {
+ var text = ipe.options['text' + mode + 'Controls'];
+ if (!text || condition === false) return;
+ ipe._form.appendChild(document.createTextNode(text));
+ };
+ this._form = $(document.createElement('form'));
+ this._form.id = this.options.formId;
+ this._form.addClassName(this.options.formClassName);
+ this._form.onsubmit = this._boundSubmitHandler;
+ this.createEditField();
+ if ('textarea' == this._controls.editor.tagName.toLowerCase())
+ this._form.appendChild(document.createElement('br'));
+ if (this.options.onFormCustomization)
+ this.options.onFormCustomization(this, this._form);
+ addText('Before', this.options.okControl || this.options.cancelControl);
+ this.createControl('ok', this._boundSubmitHandler);
+ addText('Between', this.options.okControl && this.options.cancelControl);
+ this.createControl('cancel', this._boundCancelHandler, 'editor_cancel');
+ addText('After', this.options.okControl || this.options.cancelControl);
+ },
+ destroy: function() {
+ if (this._oldInnerHTML)
+ this.element.innerHTML = this._oldInnerHTML;
+ this.leaveEditMode();
+ this.unregisterListeners();
+ },
+ enterEditMode: function(e) {
+ if (this._saving || this._editing) return;
+ this._editing = true;
+ this.triggerCallback('onEnterEditMode');
+ if (this.options.externalControl)
+ this.options.externalControl.hide();
+ this.element.hide();
+ this.createForm();
+ this.element.parentNode.insertBefore(this._form, this.element);
+ if (!this.options.loadTextURL)
+ this.postProcessEditField();
+ if (e) Event.stop(e);
+ },
+ enterHover: function(e) {
+ if (this.options.hoverClassName)
+ this.element.addClassName(this.options.hoverClassName);
+ if (this._saving) return;
+ this.triggerCallback('onEnterHover');
+ },
+ getText: function() {
+ return this.element.innerHTML.unescapeHTML();
+ },
+ handleAJAXFailure: function(transport) {
+ this.triggerCallback('onFailure', transport);
+ if (this._oldInnerHTML) {
+ this.element.innerHTML = this._oldInnerHTML;
+ this._oldInnerHTML = null;
+ }
+ },
+ handleFormCancellation: function(e) {
+ this.wrapUp();
+ if (e) Event.stop(e);
+ },
+ handleFormSubmission: function(e) {
+ var form = this._form;
+ var value = $F(this._controls.editor);
+ this.prepareSubmission();
+ var params = this.options.callback(form, value) || '';
+ if (Object.isString(params))
+ params = params.toQueryParams();
+ params.editorId = this.element.id;
+ if (this.options.htmlResponse) {
+ var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions);
+ Object.extend(options, {
+ parameters: params,
+ onComplete: this._boundWrapperHandler,
+ onFailure: this._boundFailureHandler
+ });
+ new Ajax.Updater({ success: this.element }, this.url, options);
+ } else {
+ var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
+ Object.extend(options, {
+ parameters: params,
+ onComplete: this._boundWrapperHandler,
+ onFailure: this._boundFailureHandler
+ });
+ new Ajax.Request(this.url, options);
+ }
+ if (e) Event.stop(e);
+ },
+ leaveEditMode: function() {
+ this.element.removeClassName(this.options.savingClassName);
+ this.removeForm();
+ this.leaveHover();
+ this.element.style.backgroundColor = this._originalBackground;
+ this.element.show();
+ if (this.options.externalControl)
+ this.options.externalControl.show();
+ this._saving = false;
+ this._editing = false;
+ this._oldInnerHTML = null;
+ this.triggerCallback('onLeaveEditMode');
+ },
+ leaveHover: function(e) {
+ if (this.options.hoverClassName)
+ this.element.removeClassName(this.options.hoverClassName);
+ if (this._saving) return;
+ this.triggerCallback('onLeaveHover');
+ },
+ loadExternalText: function() {
+ this._form.addClassName(this.options.loadingClassName);
+ this._controls.editor.disabled = true;
+ var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
+ Object.extend(options, {
+ parameters: 'editorId=' + encodeURIComponent(this.element.id),
+ onComplete: Prototype.emptyFunction,
+ onSuccess: function(transport) {
+ this._form.removeClassName(this.options.loadingClassName);
+ var text = transport.responseText;
+ if (this.options.stripLoadedTextTags)
+ text = text.stripTags();
+ this._controls.editor.value = text;
+ this._controls.editor.disabled = false;
+ this.postProcessEditField();
+ }.bind(this),
+ onFailure: this._boundFailureHandler
+ });
+ new Ajax.Request(this.options.loadTextURL, options);
+ },
+ postProcessEditField: function() {
+ var fpc = this.options.fieldPostCreation;
+ if (fpc)
+ $(this._controls.editor)['focus' == fpc ? 'focus' : 'activate']();
+ },
+ prepareOptions: function() {
+ this.options = Object.clone(Ajax.InPlaceEditor.DefaultOptions);
+ Object.extend(this.options, Ajax.InPlaceEditor.DefaultCallbacks);
+ [this._extraDefaultOptions].flatten().compact().each(function(defs) {
+ Object.extend(this.options, defs);
+ }.bind(this));
+ },
+ prepareSubmission: function() {
+ this._saving = true;
+ this.removeForm();
+ this.leaveHover();
+ this.showSaving();
+ },
+ registerListeners: function() {
+ this._listeners = { };
+ var listener;
+ $H(Ajax.InPlaceEditor.Listeners).each(function(pair) {
+ listener = this[pair.value].bind(this);
+ this._listeners[pair.key] = listener;
+ if (!this.options.externalControlOnly)
+ this.element.observe(pair.key, listener);
+ if (this.options.externalControl)
+ this.options.externalControl.observe(pair.key, listener);
+ }.bind(this));
+ },
+ removeForm: function() {
+ if (!this._form) return;
+ this._form.remove();
+ this._form = null;
+ this._controls = { };
+ },
+ showSaving: function() {
+ this._oldInnerHTML = this.element.innerHTML;
+ this.element.innerHTML = this.options.savingText;
+ this.element.addClassName(this.options.savingClassName);
+ this.element.style.backgroundColor = this._originalBackground;
+ this.element.show();
+ },
+ triggerCallback: function(cbName, arg) {
+ if ('function' == typeof this.options[cbName]) {
+ this.options[cbName](this, arg);
+ }
+ },
+ unregisterListeners: function() {
+ $H(this._listeners).each(function(pair) {
+ if (!this.options.externalControlOnly)
+ this.element.stopObserving(pair.key, pair.value);
+ if (this.options.externalControl)
+ this.options.externalControl.stopObserving(pair.key, pair.value);
+ }.bind(this));
+ },
+ wrapUp: function(transport) {
+ this.leaveEditMode();
+ // Can't use triggerCallback due to backward compatibility: requires
+ // binding + direct element
+ this._boundComplete(transport, this.element);
+ }
+});
+
+Object.extend(Ajax.InPlaceEditor.prototype, {
+ dispose: Ajax.InPlaceEditor.prototype.destroy
+});
+
+Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, {
+ initialize: function($super, element, url, options) {
+ this._extraDefaultOptions = Ajax.InPlaceCollectionEditor.DefaultOptions;
+ $super(element, url, options);
+ },
+
+ createEditField: function() {
+ var list = document.createElement('select');
+ list.name = this.options.paramName;
+ list.size = 1;
+ this._controls.editor = list;
+ this._collection = this.options.collection || [];
+ if (this.options.loadCollectionURL)
+ this.loadCollection();
+ else
+ this.checkForExternalText();
+ this._form.appendChild(this._controls.editor);
+ },
+
+ loadCollection: function() {
+ this._form.addClassName(this.options.loadingClassName);
+ this.showLoadingText(this.options.loadingCollectionText);
+ var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
+ Object.extend(options, {
+ parameters: 'editorId=' + encodeURIComponent(this.element.id),
+ onComplete: Prototype.emptyFunction,
+ onSuccess: function(transport) {
+ var js = transport.responseText.strip();
+ if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check
+ throw('Server returned an invalid collection representation.');
+ this._collection = eval(js);
+ this.checkForExternalText();
+ }.bind(this),
+ onFailure: this.onFailure
+ });
+ new Ajax.Request(this.options.loadCollectionURL, options);
+ },
+
+ showLoadingText: function(text) {
+ this._controls.editor.disabled = true;
+ var tempOption = this._controls.editor.firstChild;
+ if (!tempOption) {
+ tempOption = document.createElement('option');
+ tempOption.value = '';
+ this._controls.editor.appendChild(tempOption);
+ tempOption.selected = true;
+ }
+ tempOption.update((text || '').stripScripts().stripTags());
+ },
+
+ checkForExternalText: function() {
+ this._text = this.getText();
+ if (this.options.loadTextURL)
+ this.loadExternalText();
+ else
+ this.buildOptionList();
+ },
+
+ loadExternalText: function() {
+ this.showLoadingText(this.options.loadingText);
+ var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
+ Object.extend(options, {
+ parameters: 'editorId=' + encodeURIComponent(this.element.id),
+ onComplete: Prototype.emptyFunction,
+ onSuccess: function(transport) {
+ this._text = transport.responseText.strip();
+ this.buildOptionList();
+ }.bind(this),
+ onFailure: this.onFailure
+ });
+ new Ajax.Request(this.options.loadTextURL, options);
+ },
+
+ buildOptionList: function() {
+ this._form.removeClassName(this.options.loadingClassName);
+ this._collection = this._collection.map(function(entry) {
+ return 2 === entry.length ? entry : [entry, entry].flatten();
+ });
+ var marker = ('value' in this.options) ? this.options.value : this._text;
+ var textFound = this._collection.any(function(entry) {
+ return entry[0] == marker;
+ }.bind(this));
+ this._controls.editor.update('');
+ var option;
+ this._collection.each(function(entry, index) {
+ option = document.createElement('option');
+ option.value = entry[0];
+ option.selected = textFound ? entry[0] == marker : 0 == index;
+ option.appendChild(document.createTextNode(entry[1]));
+ this._controls.editor.appendChild(option);
+ }.bind(this));
+ this._controls.editor.disabled = false;
+ Field.scrollFreeActivate(this._controls.editor);
+ }
+});
+
+//**** DEPRECATION LAYER FOR InPlace[Collection]Editor! ****
+//**** This only exists for a while, in order to let ****
+//**** users adapt to the new API. Read up on the new ****
+//**** API and convert your code to it ASAP! ****
+
+Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions = function(options) {
+ if (!options) return;
+ function fallback(name, expr) {
+ if (name in options || expr === undefined) return;
+ options[name] = expr;
+ };
+ fallback('cancelControl', (options.cancelLink ? 'link' : (options.cancelButton ? 'button' :
+ options.cancelLink == options.cancelButton == false ? false : undefined)));
+ fallback('okControl', (options.okLink ? 'link' : (options.okButton ? 'button' :
+ options.okLink == options.okButton == false ? false : undefined)));
+ fallback('highlightColor', options.highlightcolor);
+ fallback('highlightEndColor', options.highlightendcolor);
+};
+
+Object.extend(Ajax.InPlaceEditor, {
+ DefaultOptions: {
+ ajaxOptions: { },
+ autoRows: 3, // Use when multi-line w/ rows == 1
+ cancelControl: 'link', // 'link'|'button'|false
+ cancelText: 'cancel',
+ clickToEditText: 'Click to edit',
+ externalControl: null, // id|elt
+ externalControlOnly: false,
+ fieldPostCreation: 'activate', // 'activate'|'focus'|false
+ formClassName: 'inplaceeditor-form',
+ formId: null, // id|elt
+ highlightColor: '#ffff99',
+ highlightEndColor: '#ffffff',
+ hoverClassName: '',
+ htmlResponse: true,
+ loadingClassName: 'inplaceeditor-loading',
+ loadingText: 'Loading...',
+ okControl: 'button', // 'link'|'button'|false
+ okText: 'ok',
+ paramName: 'value',
+ rows: 1, // If 1 and multi-line, uses autoRows
+ savingClassName: 'inplaceeditor-saving',
+ savingText: 'Saving...',
+ size: 0,
+ stripLoadedTextTags: false,
+ submitOnBlur: false,
+ textAfterControls: '',
+ textBeforeControls: '',
+ textBetweenControls: ''
+ },
+ DefaultCallbacks: {
+ callback: function(form) {
+ return Form.serialize(form);