Skip to content
Browse files

Reimplement with an isolated namespace

  • Loading branch information...
1 parent dbef975 commit 013a8b2b15fd4e899ea87443d17468484992399d @phlipper phlipper committed Sep 19, 2012
Showing with 1,788 additions and 0 deletions.
  1. +17 −0 Gemfile
  2. +20 −0 MIT-LICENSE
  3. +55 −0 README.md
  4. +40 −0 Rakefile
  5. 0 app/assets/images/thincloud/.gitkeep
  6. 0 app/assets/images/thincloud/authentication/.gitkeep
  7. +15 −0 app/assets/javascripts/thincloud/authentication/application.js
  8. +13 −0 app/assets/stylesheets/thincloud/authentication/application.css
  9. +58 −0 app/controllers/thincloud/authentication/application_controller.rb
  10. +69 −0 app/controllers/thincloud/authentication/registrations_controller.rb
  11. +23 −0 app/controllers/thincloud/authentication/sessions_controller.rb
  12. +9 −0 app/helpers/thincloud/authentication/registrations_helper.rb
  13. +80 −0 app/models/thincloud/authentication/identity.rb
  14. +14 −0 app/views/thincloud/authentication/layouts/application.html.erb
  15. +69 −0 app/views/thincloud/authentication/registrations/_registration_form.html.erb
  16. +1 −0 app/views/thincloud/authentication/registrations/new.html.erb
  17. +46 −0 app/views/thincloud/authentication/sessions/_login_form.html.erb
  18. +2 −0 app/views/thincloud/authentication/sessions/destroy.html.erb
  19. +25 −0 app/views/thincloud/authentication/sessions/new.html.erb
  20. +14 −0 config/routes.rb
  21. +19 −0 db/migrate/20120918233329_create_thincloud_authentication_identities.rb
  22. +4 −0 lib/tasks/thincloud-authentication_tasks.rake
  23. +6 −0 lib/thincloud-authentication.rb
  24. +17 −0 lib/thincloud/authentication/engine.rb
  25. +5 −0 lib/thincloud/authentication/version.rb
  26. +8 −0 script/rails
  27. +172 −0 test/controllers/thincloud/authentication/registrations_controller_test.rb
  28. +39 −0 test/controllers/thincloud/authentication/sessions_controller_test.rb
  29. +261 −0 test/dummy/README.rdoc
  30. +7 −0 test/dummy/Rakefile
  31. +15 −0 test/dummy/app/assets/javascripts/application.js
  32. +13 −0 test/dummy/app/assets/stylesheets/application.css
  33. +3 −0 test/dummy/app/controllers/application_controller.rb
  34. +2 −0 test/dummy/app/helpers/application_helper.rb
  35. 0 test/dummy/app/mailers/.gitkeep
  36. 0 test/dummy/app/models/.gitkeep
  37. +3 −0 test/dummy/app/models/user.rb
  38. +16 −0 test/dummy/app/views/layouts/application.html.erb
  39. +4 −0 test/dummy/config.ru
  40. +66 −0 test/dummy/config/application.rb
  41. +10 −0 test/dummy/config/boot.rb
  42. +25 −0 test/dummy/config/database.yml
  43. +5 −0 test/dummy/config/environment.rb
  44. +37 −0 test/dummy/config/environments/development.rb
  45. +67 −0 test/dummy/config/environments/production.rb
  46. +37 −0 test/dummy/config/environments/test.rb
  47. +7 −0 test/dummy/config/initializers/backtrace_silencers.rb
  48. +15 −0 test/dummy/config/initializers/inflections.rb
  49. +5 −0 test/dummy/config/initializers/mime_types.rb
  50. +7 −0 test/dummy/config/initializers/secret_token.rb
  51. +8 −0 test/dummy/config/initializers/session_store.rb
  52. +14 −0 test/dummy/config/initializers/wrap_parameters.rb
  53. +5 −0 test/dummy/config/locales/en.yml
  54. +25 −0 test/dummy/config/routes.rb
  55. +8 −0 test/dummy/db/migrate/20120919182522_create_users.rb
  56. +38 −0 test/dummy/db/schema.rb
  57. 0 test/dummy/lib/assets/.gitkeep
  58. 0 test/dummy/log/.gitkeep
  59. +26 −0 test/dummy/public/404.html
  60. +26 −0 test/dummy/public/422.html
  61. +25 −0 test/dummy/public/500.html
  62. 0 test/dummy/public/favicon.ico
  63. +6 −0 test/dummy/script/rails
  64. +18 −0 test/minitest_helper.rb
  65. +82 −0 test/models/identity_test.rb
  66. +13 −0 test/models/user_test.rb
  67. +8 −0 test/support/user.rb
  68. +7 −0 test/thincloud-authentication_test.rb
  69. +34 −0 thincloud-authentication.gemspec
View
17 Gemfile
@@ -0,0 +1,17 @@
+source "http://rubygems.org"
+
+# Declare your gem's dependencies in thincloud-authentication.gemspec.
+# Bundler will treat runtime dependencies like base dependencies, and
+# development dependencies will be added by default to the :development group.
+gemspec
+
+# jquery-rails is used by the dummy application
+gem "jquery-rails"
+
+# Declare any dependencies that are still in development here instead of in
+# your gemspec. These might include edge Rails or gems from your path or
+# Git. Remember to move these dependencies to your gemspec before releasing
+# your gem to rubygems.org.
+
+# To use debugger
+# gem 'debugger'
View
20 MIT-LICENSE
@@ -0,0 +1,20 @@
+Copyright 2012 New Leaders
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
View
55 README.md
@@ -0,0 +1,55 @@
+# Thincloud::Authentication
+
+## Description
+
+A Rails Engine to provide authentication for Thincloud applications.
+
+## Requirements
+
+This gem requires Rails 3.2+ and has been tested on the following versions:
+
+* 3.2
+
+This gem has been tested against the following Ruby versions:
+
+* 1.9.3
+
+
+## Installation
+
+Add this line to your application's Gemfile:
+
+``` ruby
+gem "thincloud-authentication"
+```
+
+And then execute:
+
+```
+$ bundle
+```
+
+Or install it yourself as:
+
+```
+$ gem install thincloud-authentication
+```
+
+## Usage
+
+TODO
+
+## Contributing
+
+1. [Fork it](https://github.com/newleaders/thincloud-authentication/fork_select)
+2. Create your feature branch (`git checkout -b my-new-feature`)
+3. Commit your changes (`git commit -am 'Added some feature'`)
+4. Push to the branch (`git push origin my-new-feature`)
+5. [Create a Pull Request](https://github.com/newleaders/thincloud-authentication/pull/new)
+
+
+## License
+
+* Freely distributable and licensed under the MIT-style license. See LICENSE file for details.
+* Copyright (c) 2012 New Leaders
+* [https://newleaders.com](https://newleaders.com)
View
40 Rakefile
@@ -0,0 +1,40 @@
+#!/usr/bin/env rake
+begin
+ require 'bundler/setup'
+rescue LoadError
+ puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
+end
+begin
+ require 'rdoc/task'
+rescue LoadError
+ require 'rdoc/rdoc'
+ require 'rake/rdoctask'
+ RDoc::Task = Rake::RDocTask
+end
+
+RDoc::Task.new(:rdoc) do |rdoc|
+ rdoc.rdoc_dir = 'rdoc'
+ rdoc.title = 'Thincloud::Authentication'
+ rdoc.options << '--line-numbers'
+ rdoc.rdoc_files.include('README.rdoc')
+ rdoc.rdoc_files.include('lib/**/*.rb')
+end
+
+APP_RAKEFILE = File.expand_path("../test/dummy/Rakefile", __FILE__)
+load 'rails/tasks/engine.rake'
+
+
+
+Bundler::GemHelper.install_tasks
+
+require 'rake/testtask'
+
+Rake::TestTask.new(:test) do |t|
+ t.libs << 'lib'
+ t.libs << 'test'
+ t.pattern = 'test/**/*_test.rb'
+ t.verbose = false
+end
+
+
+task :default => :test
View
0 app/assets/images/thincloud/.gitkeep
No changes.
View
0 app/assets/images/thincloud/authentication/.gitkeep
No changes.
View
15 app/assets/javascripts/thincloud/authentication/application.js
@@ -0,0 +1,15 @@
+// This is a manifest file that'll be compiled into application.js, which will include all the files
+// listed below.
+//
+// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
+// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
+//
+// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
+// the compiled file.
+//
+// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
+// GO AFTER THE REQUIRES BELOW.
+//
+//= require jquery
+//= require jquery_ujs
+//= require_tree .
View
13 app/assets/stylesheets/thincloud/authentication/application.css
@@ -0,0 +1,13 @@
+/*
+ * This is a manifest file that'll be compiled into application.css, which will include all the files
+ * listed below.
+ *
+ * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
+ * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.
+ *
+ * You're free to add application-wide styles to this file and they'll appear at the top of the
+ * compiled file, but it's generally better to create a new file per style scope.
+ *
+ *= require_self
+ *= require_tree .
+ */
View
58 app/controllers/thincloud/authentication/application_controller.rb
@@ -0,0 +1,58 @@
+module Thincloud::Authentication
+ # Public: Primary controller settings and helpers for the engine.
+ class ApplicationController < ActionController::Base
+ layout "application"
+
+ protected
+
+ # Protected: The user that is currently logged in.
+ #
+ # This method is also available as a view helper.
+ #
+ # Returns: An instance of `User` or `nil`.
+ def current_user
+ return nil unless session[:uid].present?
+ @current_user ||= User.find(session[:uid])
+ end
+ helper_method :current_user
+
+ # Protected: Determine if the current request has a logged in user.
+ #
+ # This method is also available as a view helper.
+ #
+ # Returns: Boolean.
+ def logged_in?
+ current_user.present?
+ end
+ helper_method :logged_in?
+
+ # Protected: Require an authenticated user to perform an action.
+ #
+ # Use in a `before_filter`.
+ #
+ # Returns: Redirect if not logged in, otherwise `nil`.
+ def authenticate!
+ unless logged_in?
+ redirect_to login_url, alert: "You must be logged in to continue."
+ end
+ end
+
+ # Protected: Set the `current_user` to the provided `User` instance.
+ #
+ # user - An instance of `User` that has been authenticated.
+ #
+ # Returns: The `id` of the provided user.
+ def login_as(user)
+ reset_session # avoid session fixation
+ session[:uid] = user.id
+ end
+
+ # Protected: Clear the session of an authenticated user.
+ #
+ # Returns: A new empty session instance.
+ def logout
+ reset_session
+ end
+
+ end
+end
View
69 app/controllers/thincloud/authentication/registrations_controller.rb
@@ -0,0 +1,69 @@
+require_dependency "thincloud/authentication/application_controller"
+
+module Thincloud::Authentication
+ # Public: Handle OmniAuth callbacks.
+ class RegistrationsController < ApplicationController
+ def new
+ @identity = Identity.new
+ end
+
+ def create
+ # identity exists
+ if omniauth && identity = Identity.find_omniauth(omniauth)
+ login_as identity.user
+ redirect_to root_url, notice: "You have been logged in."
+ # new identity for current_user
+ elsif current_user
+ current_user.identities.build.apply_omniauth(omniauth).save
+ redirect_to root_url, notice: "You have been logged in."
+ # failed identity login
+ elsif invalid_identity_credentials?
+ redirect_to auth_failure_url message: "invalid_credentials",
+ strategy: "identity"
+ # create a new identity
+ else
+ # params[:identity] exists when creating a local identity provider
+ @identity = Identity.new(params[:identity])
+ @identity.user = User.create
+
+ # omniauth exists if coming from a 3rd party provider like LinkedIn
+ if omniauth
+ @identity.apply_omniauth(omniauth)
+ else
+ flash[:alert] = "Welcome! Please check your email to verify your " <<
+ "registration."
+ end
+
+ if @identity.save
+ login_as @identity.user if omniauth
+ redirect_to root_url
+ else
+ render :new
+ end
+ end
+ end
+
+ def verify
+ identity = Identity.verify!(params[:token])
+ login_as identity.user
+ redirect_to root_url,
+ notice: "Thank you! Your registration has been verified."
+ end
+
+ private
+
+ # Private: Accessor for OmniAuth environment.
+ #
+ # Returns: An instance of `OmniAuth::InfoHash` or `nil`.
+ def omniauth
+ request.env["omniauth.auth"]
+ end
+
+ # Private: Determine if the request is from an invalid Identity login.
+ #
+ # Returns: Boolean.
+ def invalid_identity_credentials?
+ params[:provider] == "identity" && params[:auth_key].present?
+ end
+ end
+end
View
23 app/controllers/thincloud/authentication/sessions_controller.rb
@@ -0,0 +1,23 @@
+require_dependency "thincloud/authentication/application_controller"
+
+module Thincloud::Authentication
+ # Public: Handle login/logout behavior.
+ class SessionsController < ApplicationController
+ before_filter :authenticate!, only: [:authenticated]
+
+ def new
+ redirect_to root_url if logged_in?
+ @identity = Identity.new
+ end
+
+ def destroy
+ logout
+ redirect_to root_url, notice: "You have been logged out."
+ end
+
+ def authenticated
+ # dummy method to test the :authenticate! before_filter
+ render text: "Authenticated!"
+ end
+ end
+end
View
9 app/helpers/thincloud/authentication/registrations_helper.rb
@@ -0,0 +1,9 @@
+module Thincloud::Authentication
+ module RegistrationsHelper
+
+ def form_error_class_for(form, field)
+ "error" if form.object.errors[field].present?
+ end
+
+ end
+end
View
80 app/models/thincloud/authentication/identity.rb
@@ -0,0 +1,80 @@
+module Thincloud::Authentication
+ # Public: This class represents a User identity (name, email, login provider)
+ class Identity < ::OmniAuth::Identity::Models::ActiveRecord
+ belongs_to :user
+
+ # Limit the ability to mass-assign sensitive fields.
+ attr_accessible :name, :email, :password, :password_confirmation
+
+ validates :name, presence: true
+ validates :email, presence: true, uniqueness: true, format: /@/
+
+ # Ensure that a `verification_token` exists for new records.
+ after_initialize do
+ self.verification_token = SecureRandom.urlsafe_base64 if new_record?
+ end
+
+ # Only validate password if the 'provider' is 'identity'.
+ before_validation do
+ self.password_digest = 0 unless provider == "identity"
+ end
+
+ # Public: Use a helpful attribute name when displaying errors.
+ def self.human_attribute_name(attr, options={})
+ attr == :password_digest ? "Password" : super
+ end
+
+ # Public: Find an `Identity` by OmniAuth parameters.
+ #
+ # omniauth - An instance of `OmniAuth::AuthHash`
+ #
+ # Returns: An instance of `Identity` or `nil`.
+ def self.find_omniauth(omniauth)
+ find_by_provider_and_uid omniauth["provider"], omniauth["uid"]
+ end
+
+ # Public: Mark the `Identity` as having been verified.
+ #
+ # token - A String containing the `verification_token` to look up.
+ #
+ # Returns: An instance of the found `Identity`.
+ # Raises: ActiveRecord::RecordNotFound if the `token` cannot be retrieved.
+ def self.verify!(token)
+ find_by_verification_token!(token).tap do |identity|
+ # ensure 'uid' exists, needed for 'identity' provider
+ identity.uid = identity.id if identity.uid.blank?
+ identity.verification_token = nil
+ identity.verified_at = Time.zone.now
+ identity.save
+ end
+ end
+
+ # Public: Shim to overcome odd behavior seen during testing with SQLite
+ def uid
+ read_attribute :uid
+ end
+
+ # Public: Indicate if the `Identity` has been verified.
+ #
+ # Returns: Boolean.
+ def verified?
+ verification_token.blank? && verified_at.present?
+ end
+
+ # Public: Apply attributes returned from OmniAuth.
+ #
+ # omniauth - An instance of `OmniAuth::AuthHash`.
+ def apply_omniauth(omniauth)
+ info = omniauth["info"]
+
+ user_name = %Q(#{info["first_name"]} #{info["last_name"]})
+ user_name.gsub!(/\s+/, " ").strip!
+
+ self.provider = omniauth["provider"]
+ self.uid = omniauth["uid"]
+ self.name = user_name if self.name.blank?
+ self.email = info["email"] if info["email"] && self.email.blank?
+ self
+ end
+ end
+end
View
14 app/views/thincloud/authentication/layouts/application.html.erb
@@ -0,0 +1,14 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>Thincloud::Authentication</title>
+ <%= stylesheet_link_tag "thincloud/authentication/application", :media => "all" %>
+ <%= javascript_include_tag "thincloud/authentication/application" %>
+ <%= csrf_meta_tags %>
+</head>
+<body>
+
+<%= yield %>
+
+</body>
+</html>
View
69 app/views/thincloud/authentication/registrations/_registration_form.html.erb
@@ -0,0 +1,69 @@
+<%= form_for @identity, url: registrations_path, html: { class: "form-horizontal" } do |f| %>
+ <fieldset>
+ <legend>Register</legend>
+
+ <% if @identity.errors.any? %>
+ <div class="alert alert-block alert-error">
+ <h4><i class="icon-warning-sign"></i> Error</h4>
+ Please check the following <%= pluralize @identity.errors.size, "item" %>:
+ </div>
+ <% end %>
+
+ <div class="control-group <%= form_error_class_for(f, :name) %>">
+ <%= f.label :name, "Name", class: "control-label" %>
+ <div class="controls">
+ <div class="input-prepend">
+ <span class="add-on"><i class="icon-user"></i></span>
+ <%= f.text_field :name %>
+ </div>
+ <%= content_tag :span, "#{:name.to_s.humanize} #{f.object.errors[:name].to_sentence}", class: "help-inline" %>
+ </div>
+ </div>
+
+
+ <div class="control-group <%= form_error_class_for(f, :email) %>">
+ <%= f.label :email, "Email", class: "control-label" %>
+ <div class="controls">
+ <div class="input-prepend">
+ <span class="add-on"><i class="icon-envelope"></i></span>
+ <%= f.email_field :email %>
+ </div>
+ <%= content_tag :span, "#{:email.to_s.humanize} #{f.object.errors[:email].to_sentence}", class: "help-inline" %>
+ </div>
+ </div>
+
+ <div class="control-group <%= form_error_class_for(f, :password_digest) %>">
+ <%= f.label :password, "Password", class: "control-label" %>
+ <div class="controls">
+ <div class="input-prepend">
+ <span class="add-on"><i class="icon-lock"></i></span>
+ <%= f.password_field :password %>
+ </div>
+ <%= content_tag :span, "#{:password.to_s.humanize} #{f.object.errors[:password_digest].to_sentence}", class: "help-inline" %>
+ </div>
+ </div>
+
+ <div class="control-group <%= form_error_class_for(f, :password) %>">
+ <%= f.label :password_confirmation, "Confirmation", class: "control-label" %>
+ <div class="controls">
+ <div class="input-prepend">
+ <span class="add-on"><i class="icon-lock"></i></span>
+ <%= f.password_field :password_confirmation %>
+ </div>
+ <%= content_tag :span, "#{:password.to_s.humanize} #{f.object.errors[:password].to_sentence}", class: "help-inline" %>
+ </div>
+ </div>
+
+ <div class="control-group">
+ <div class="controls">
+ <%= button_tag type: "submit", class: "btn btn-large btn-primary" do %>
+ <i class="icon-ok icon-white"></i> Register
+ <% end %>
+
+ <%= link_to root_url, class: "btn btn-large" do %>
+ <i class="icon-remove"></i> Cancel
+ <% end %>
+ </div>
+ </div>
+ </fieldset>
+<% end %>
View
1 app/views/thincloud/authentication/registrations/new.html.erb
@@ -0,0 +1 @@
+<%= render "registration_form" %>
View
46 app/views/thincloud/authentication/sessions/_login_form.html.erb
@@ -0,0 +1,46 @@
+<%= form_tag auth_callback_url(provider: "identity"), class: "form-horizontal" do %>
+ <fieldset>
+ <legend>Login</legend>
+
+ <% if params[:message].present? %>
+ <div class="alert alert-block alert-error">
+ <h4><i class="icon-warning-sign"></i> Error</h4>
+ <%= params[:message].humanize %>
+ </div>
+ <% end %>
+
+ <div class="control-group">
+ <%= label_tag :auth_key, "Email", class: "control-label" %>
+ <div class="controls">
+ <div class="input-prepend">
+ <span class="add-on"><i class="icon-envelope"></i></span>
+ <%= email_field_tag :auth_key, params[:auth_key] %>
+ </div>
+ </div>
+ </div>
+
+ <div class="control-group">
+ <%= label_tag :password, "Password", class: "control-label" %>
+ <div class="controls">
+ <div class="input-prepend">
+ <span class="add-on"><i class="icon-lock"></i></span>
+ <%= password_field_tag :password %>
+ </div>
+ </div>
+ </div>
+
+ <div class="control-group">
+ <div class="controls">
+ <%= button_tag type: "submit", class: "btn btn-large btn-primary" do %>
+ <i class="icon-ok icon-white"></i> Login
+ <% end %>
+
+ or
+
+ <%= link_to signup_url, class: "btn btn-large" do %>
+ <i class="icon-user"></i> Signup
+ <% end %>
+ </div>
+ </div>
+ </fieldset>
+<% end %>
View
2 app/views/thincloud/authentication/sessions/destroy.html.erb
@@ -0,0 +1,2 @@
+<h1>Sessions#destroy</h1>
+<p>Find me in app/views/sessions/destroy.html.erb</p>
View
25 app/views/thincloud/authentication/sessions/new.html.erb
@@ -0,0 +1,25 @@
+Current User: <%= current_user.inspect %>
+Signed In: <%= logged_in? %>
+
+<div class="tabbable">
+ <ul class="nav nav-tabs">
+ <li class="active">
+ <a href="#login" data-toggle="tab"><i class="icon-lock"></i> Login</a>
+ </li>
+ <li>
+ <a href="#register" data-toggle="tab"><i class="icon-user"></i> Register</a>
+ </li>
+ </ul>
+
+ <div class="tab-content">
+ <!-- Login -->
+ <div class="tab-pane active" id="login">
+ <%= render "login_form" %>
+ </div>
+
+ <!-- Register -->
+ <div class="tab-pane" id="register">
+ <%= render "thincloud/authentication/registrations/registration_form" %>
+ </div>
+ </div>
+</div>
View
14 config/routes.rb
@@ -0,0 +1,14 @@
+Thincloud::Authentication::Engine.routes.draw do
+ match "auth/:provider/callback" => "registrations#create", as: "auth_callback"
+ get "auth/failure", to: "sessions#new", as: "auth_failure"
+
+ get "login", to: "sessions#new", as: "login"
+ delete "logout", to: "sessions#destroy", as: "logout"
+ get "authenticated", to: "sessions#authenticated"
+
+ resources :registrations, only: [:new, :create]
+ get "signup", to: "registrations#new", as: "signup"
+ get "verify/:token", to: "registrations#verify", as: "verify_token"
+
+ root to: "sessions#new"
+end
View
19 db/migrate/20120918233329_create_thincloud_authentication_identities.rb
@@ -0,0 +1,19 @@
+class CreateThincloudAuthenticationIdentities < ActiveRecord::Migration
+ def change
+ create_table :thincloud_authentication_identities do |t|
+ t.integer :user_id, null: false
+ t.string :provider, null: false, default: "identity"
+ t.string :uid
+ t.string :name, null: false
+ t.string :email, null: false
+ t.string :password_digest, null: false
+ t.string :verification_token
+ t.datetime :verified_at
+
+ t.timestamps
+ end
+ add_index :thincloud_authentication_identities, :user_id
+ add_index :thincloud_authentication_identities, [:provider, :uid], unique: true
+ add_index :thincloud_authentication_identities, :email
+ end
+end
View
4 lib/tasks/thincloud-authentication_tasks.rake
@@ -0,0 +1,4 @@
+# desc "Explaining what the task does"
+# task :thincloud-authentication do
+# # Task goes here
+# end
View
6 lib/thincloud-authentication.rb
@@ -0,0 +1,6 @@
+require "thincloud/authentication/engine"
+
+module Thincloud
+ module Authentication
+ end
+end
View
17 lib/thincloud/authentication/engine.rb
@@ -0,0 +1,17 @@
+module Thincloud
+ module Authentication
+ # Public: Initialize the Rails engine
+ class Engine < ::Rails::Engine
+ isolate_namespace Thincloud::Authentication
+
+ initializer "thincloud.authentication.omniauth" do |app|
+ require "omniauth"
+ require "omniauth-identity"
+ end
+
+ config.generators do |g|
+ g.test_framework :mini_test, spec: true, fixture: false
+ end
+ end
+ end
+end
View
5 lib/thincloud/authentication/version.rb
@@ -0,0 +1,5 @@
+module Thincloud
+ module Authentication
+ VERSION = "0.0.1"
+ end
+end
View
8 script/rails
@@ -0,0 +1,8 @@
+#!/usr/bin/env ruby
+# This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application.
+
+ENGINE_ROOT = File.expand_path('../..', __FILE__)
+ENGINE_PATH = File.expand_path('../../lib/thincloud-authentication/engine', __FILE__)
+
+require 'rails/all'
+require 'rails/engine/commands'
View
172 test/controllers/thincloud/authentication/registrations_controller_test.rb
@@ -0,0 +1,172 @@
+require "minitest_helper"
+
+module Thincloud::Authentication
+ describe RegistrationsController do
+ describe "GET new" do
+ before { get :new }
+
+ it { assert_response :success }
+ it { assigns[:identity].wont_be_nil }
+ end
+
+ describe "POST create" do
+ describe "with errors" do
+ before { post :create, identity: {} }
+
+ it { assert_response :success }
+ it { assert_template :new }
+ it { assigns[:identity].wont_be_nil }
+ it { assigns[:identity].errors.any?.must_equal true }
+ end
+
+ describe "find an existing Identity" do
+ let(:user) { User.create }
+ let(:identity) { id = Identity.new; id.user = user; id }
+ let(:auth_hash) do
+ OmniAuth::AuthHash.new(
+ credentials: Hashie::Mash.new, extra: Hashie::Mash.new,
+ info: OmniAuth::AuthHash::InfoHash.new(
+ email: "foo@bar.com", name: "Foo"
+ ),
+ provider: "identity", uid: 123
+ )
+ end
+
+ before do
+ RegistrationsController.any_instance.stubs(:omniauth).returns(
+ auth_hash
+ )
+ Identity.stubs(:find_omniauth).with(auth_hash).returns(identity)
+ User.stubs(:find).with(123).returns(user)
+ post :create
+ end
+
+ it { session[:uid].wont_be_nil }
+ it { assert_response :redirect }
+ it { assert_redirected_to root_url }
+ it { flash[:notice].must_equal "You have been logged in." }
+ end
+
+ describe "add an Identity to current_user" do
+ let(:user) { User.create }
+ let(:identity) do
+ attrs = {
+ name: "foo", email: "foo@bar", password: "foo",
+ password_confirmation: "foo"
+ }
+ Identity.new(attrs).tap do |identity|
+ identity.user = user
+ identity.save
+ end
+ end
+
+ let(:auth_hash) do
+ OmniAuth::AuthHash.new(
+ credentials: Hashie::Mash.new, extra: Hashie::Mash.new,
+ info: OmniAuth::AuthHash::InfoHash.new(
+ email: "foo2@bar2.com", first_name: "New", last_name: "Name",
+ ),
+ provider: "linkedin", uid: "xxsdflkjsdf"
+ )
+ end
+
+ before do
+ RegistrationsController.any_instance.stubs(:omniauth).returns(
+ auth_hash
+ )
+ RegistrationsController.any_instance.stubs(:current_user).returns(user)
+ identity
+ post :create
+ end
+
+ it { assert_response :redirect }
+ it { assert_redirected_to root_url }
+ it { flash[:notice].must_equal "You have been logged in." }
+
+ it { user.identities.count.must_equal 2 }
+ it { user.identities.last.provider.must_equal "linkedin" }
+ it { user.identities.last.read_attribute(:uid).must_equal "xxsdflkjsdf" }
+ it { user.identities.last.name.must_equal "New Name" }
+ it { user.identities.last.email.must_equal "foo2@bar2.com" }
+ end
+
+ describe "invalid Identity credentials" do
+ before do
+ post :create, { auth_key: "invalid@email", provider: "identity" }
+ end
+
+ it { assert_response :redirect }
+ it { assert_redirected_to auth_failure_url(message: "invalid_credentials", strategy: "identity") }
+ end
+
+ describe "create a new Identity" do
+ describe "with 'identity' provider" do
+ before do
+ post :create, identity: {
+ name: "Foo", email: "foo@bar.com",
+ password: "test", password_confirmation: "test"
+ }
+ end
+
+ it { assert_response :redirect }
+ it { assert_redirected_to root_url }
+ it { session[:uid].must_be_nil }
+ it { flash[:alert].must_equal "Welcome! Please check your email to " <<
+ "verify your registration." }
+ it { User.count.must_equal 1 }
+ it { Identity.count.must_equal 1 }
+ end
+
+ describe "with 'linkedin' provider" do
+ let(:auth_hash) do
+ OmniAuth::AuthHash.new(
+ credentials: Hashie::Mash.new, extra: Hashie::Mash.new,
+ info: OmniAuth::AuthHash::InfoHash.new(
+ email: "foo2@bar2.com", first_name: "New", last_name: "Name",
+ ),
+ provider: "linkedin", uid: "xxsdflkjsdf"
+ )
+ end
+
+ before do
+ RegistrationsController.any_instance.stubs(:omniauth).returns(
+ auth_hash
+ )
+ post :create
+ end
+
+ it { assert_response :redirect }
+ it { assert_redirected_to root_url }
+ it { session[:uid].must_equal assigns[:identity].user.id }
+ it { flash[:alert].must_be_nil }
+ it { User.count.must_equal 1 }
+ it { Identity.count.must_equal 1 }
+ end
+ end
+ end
+
+ describe "GET verify" do
+ describe "invalid token" do
+ it "raises an exception" do
+ -> {
+ get :verify, token: "invalid"
+ }.must_raise(ActiveRecord::RecordNotFound)
+ end
+ end
+
+ describe "valid token" do
+ let(:user) { User.create }
+ let(:identity) { id = Identity.new; id.user = user; id }
+
+ before do
+ Identity.stubs(:verify!).with("token").returns(identity)
+ get :verify, token: "token"
+ end
+
+ it { assert_response :redirect }
+ it { assert_redirected_to root_url }
+ it { flash[:notice].must_equal "Thank you! Your registration has been verified." }
+ end
+ end
+ end
+end
View
39 test/controllers/thincloud/authentication/sessions_controller_test.rb
@@ -0,0 +1,39 @@
+require "minitest_helper"
+
+module Thincloud::Authentication
+ describe SessionsController do
+ describe "GET new" do
+ before { get :new }
+
+ it { assert_response :success }
+ it { assert_template :new }
+ end
+
+ describe "DELETE destroy" do
+ before { delete :destroy }
+
+ it { assert_response :redirect }
+ it { flash[:notice].must_equal "You have been logged out." }
+ end
+
+ describe "GET authenticated" do
+ describe "not logged in" do
+ before { get :authenticated }
+
+ it { assert_response :redirect }
+ it { assert_redirected_to login_url }
+ it { flash[:alert].must_equal "You must be logged in to continue." }
+ end
+
+ describe "logged in" do
+ before do
+ User.stubs(:find).with(123).returns(User.new)
+ session[:uid] = 123
+ get :authenticated
+ end
+
+ it { assert_response :success }
+ end
+ end
+ end
+end
View
261 test/dummy/README.rdoc
@@ -0,0 +1,261 @@
+== Welcome to Rails
+
+Rails is a web-application framework that includes everything needed to create
+database-backed web applications according to the Model-View-Control pattern.
+
+This pattern splits the view (also called the presentation) into "dumb"
+templates that are primarily responsible for inserting pre-built data in between
+HTML tags. The model contains the "smart" domain objects (such as Account,
+Product, Person, Post) that holds all the business logic and knows how to
+persist themselves to a database. The controller handles the incoming requests
+(such as Save New Account, Update Product, Show Post) by manipulating the model
+and directing data to the view.
+
+In Rails, the model is handled by what's called an object-relational mapping
+layer entitled Active Record. This layer allows you to present the data from
+database rows as objects and embellish these data objects with business logic
+methods. You can read more about Active Record in
+link:files/vendor/rails/activerecord/README.html.
+
+The controller and view are handled by the Action Pack, which handles both
+layers by its two parts: Action View and Action Controller. These two layers
+are bundled in a single package due to their heavy interdependence. This is
+unlike the relationship between the Active Record and Action Pack that is much
+more separate. Each of these packages can be used independently outside of
+Rails. You can read more about Action Pack in
+link:files/vendor/rails/actionpack/README.html.
+
+
+== Getting Started
+
+1. At the command prompt, create a new Rails application:
+ <tt>rails new myapp</tt> (where <tt>myapp</tt> is the application name)
+
+2. Change directory to <tt>myapp</tt> and start the web server:
+ <tt>cd myapp; rails server</tt> (run with --help for options)
+
+3. Go to http://localhost:3000/ and you'll see:
+ "Welcome aboard: You're riding Ruby on Rails!"
+
+4. Follow the guidelines to start developing your application. You can find
+the following resources handy:
+
+* The Getting Started Guide: http://guides.rubyonrails.org/getting_started.html
+* Ruby on Rails Tutorial Book: http://www.railstutorial.org/
+
+
+== Debugging Rails
+
+Sometimes your application goes wrong. Fortunately there are a lot of tools that
+will help you debug it and get it back on the rails.
+
+First area to check is the application log files. Have "tail -f" commands
+running on the server.log and development.log. Rails will automatically display
+debugging and runtime information to these files. Debugging info will also be
+shown in the browser on requests from 127.0.0.1.
+
+You can also log your own messages directly into the log file from your code
+using the Ruby logger class from inside your controllers. Example:
+
+ class WeblogController < ActionController::Base
+ def destroy
+ @weblog = Weblog.find(params[:id])
+ @weblog.destroy
+ logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!")
+ end
+ end
+
+The result will be a message in your log file along the lines of:
+
+ Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1!
+
+More information on how to use the logger is at http://www.ruby-doc.org/core/
+
+Also, Ruby documentation can be found at http://www.ruby-lang.org/. There are
+several books available online as well:
+
+* Programming Ruby: http://www.ruby-doc.org/docs/ProgrammingRuby/ (Pickaxe)
+* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide)
+
+These two books will bring you up to speed on the Ruby language and also on
+programming in general.
+
+
+== Debugger
+
+Debugger support is available through the debugger command when you start your
+Mongrel or WEBrick server with --debugger. This means that you can break out of
+execution at any point in the code, investigate and change the model, and then,
+resume execution! You need to install ruby-debug to run the server in debugging
+mode. With gems, use <tt>sudo gem install ruby-debug</tt>. Example:
+
+ class WeblogController < ActionController::Base
+ def index
+ @posts = Post.all
+ debugger
+ end
+ end
+
+So the controller will accept the action, run the first line, then present you
+with a IRB prompt in the server window. Here you can do things like:
+
+ >> @posts.inspect
+ => "[#<Post:0x14a6be8
+ @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>,
+ #<Post:0x14a6620
+ @attributes={"title"=>"Rails", "body"=>"Only ten..", "id"=>"2"}>]"
+ >> @posts.first.title = "hello from a debugger"
+ => "hello from a debugger"
+
+...and even better, you can examine how your runtime objects actually work:
+
+ >> f = @posts.first
+ => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
+ >> f.
+ Display all 152 possibilities? (y or n)
+
+Finally, when you're ready to resume execution, you can enter "cont".
+
+
+== Console
+
+The console is a Ruby shell, which allows you to interact with your
+application's domain model. Here you'll have all parts of the application
+configured, just like it is when the application is running. You can inspect
+domain models, change values, and save to the database. Starting the script
+without arguments will launch it in the development environment.
+
+To start the console, run <tt>rails console</tt> from the application
+directory.
+
+Options:
+
+* Passing the <tt>-s, --sandbox</tt> argument will rollback any modifications
+ made to the database.
+* Passing an environment name as an argument will load the corresponding
+ environment. Example: <tt>rails console production</tt>.
+
+To reload your controllers and models after launching the console run
+<tt>reload!</tt>
+
+More information about irb can be found at:
+link:http://www.rubycentral.org/pickaxe/irb.html
+
+
+== dbconsole
+
+You can go to the command line of your database directly through <tt>rails
+dbconsole</tt>. You would be connected to the database with the credentials
+defined in database.yml. Starting the script without arguments will connect you
+to the development database. Passing an argument will connect you to a different
+database, like <tt>rails dbconsole production</tt>. Currently works for MySQL,
+PostgreSQL and SQLite 3.
+
+== Description of Contents
+
+The default directory structure of a generated Ruby on Rails application:
+
+ |-- app
+ | |-- assets
+ | |-- images
+ | |-- javascripts
+ | `-- stylesheets
+ | |-- controllers
+ | |-- helpers
+ | |-- mailers
+ | |-- models
+ | `-- views
+ | `-- layouts
+ |-- config
+ | |-- environments
+ | |-- initializers
+ | `-- locales
+ |-- db
+ |-- doc
+ |-- lib
+ | `-- tasks
+ |-- log
+ |-- public
+ |-- script
+ |-- test
+ | |-- fixtures
+ | |-- functional
+ | |-- integration
+ | |-- performance
+ | `-- unit
+ |-- tmp
+ | |-- cache
+ | |-- pids
+ | |-- sessions
+ | `-- sockets
+ `-- vendor
+ |-- assets
+ `-- stylesheets
+ `-- plugins
+
+app
+ Holds all the code that's specific to this particular application.
+
+app/assets
+ Contains subdirectories for images, stylesheets, and JavaScript files.
+
+app/controllers
+ Holds controllers that should be named like weblogs_controller.rb for
+ automated URL mapping. All controllers should descend from
+ ApplicationController which itself descends from ActionController::Base.
+
+app/models
+ Holds models that should be named like post.rb. Models descend from
+ ActiveRecord::Base by default.
+
+app/views
+ Holds the template files for the view that should be named like
+ weblogs/index.html.erb for the WeblogsController#index action. All views use
+ eRuby syntax by default.
+
+app/views/layouts
+ Holds the template files for layouts to be used with views. This models the
+ common header/footer method of wrapping views. In your views, define a layout
+ using the <tt>layout :default</tt> and create a file named default.html.erb.
+ Inside default.html.erb, call <% yield %> to render the view using this
+ layout.
+
+app/helpers
+ Holds view helpers that should be named like weblogs_helper.rb. These are
+ generated for you automatically when using generators for controllers.
+ Helpers can be used to wrap functionality for your views into methods.
+
+config
+ Configuration files for the Rails environment, the routing map, the database,
+ and other dependencies.
+
+db
+ Contains the database schema in schema.rb. db/migrate contains all the
+ sequence of Migrations for your schema.
+
+doc
+ This directory is where your application documentation will be stored when
+ generated using <tt>rake doc:app</tt>
+
+lib
+ Application specific libraries. Basically, any kind of custom code that
+ doesn't belong under controllers, models, or helpers. This directory is in
+ the load path.
+
+public
+ The directory available for the web server. Also contains the dispatchers and the
+ default HTML files. This should be set as the DOCUMENT_ROOT of your web
+ server.
+
+script
+ Helper scripts for automation and generation.
+
+test
+ Unit and functional tests along with fixtures. When using the rails generate
+ command, template test files will be generated for you and placed in this
+ directory.
+
+vendor
+ External libraries that the application depends on. Also includes the plugins
+ subdirectory. If the app has frozen rails, those gems also go here, under
+ vendor/rails/. This directory is in the load path.
View
7 test/dummy/Rakefile
@@ -0,0 +1,7 @@
+#!/usr/bin/env rake
+# 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__)
+
+Dummy::Application.load_tasks
View
15 test/dummy/app/assets/javascripts/application.js
@@ -0,0 +1,15 @@
+// This is a manifest file that'll be compiled into application.js, which will include all the files
+// listed below.
+//
+// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
+// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
+//
+// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
+// the compiled file.
+//
+// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
+// GO AFTER THE REQUIRES BELOW.
+//
+//= require jquery
+//= require jquery_ujs
+//= require_tree .
View
13 test/dummy/app/assets/stylesheets/application.css
@@ -0,0 +1,13 @@
+/*
+ * This is a manifest file that'll be compiled into application.css, which will include all the files
+ * listed below.
+ *
+ * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
+ * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path.
+ *
+ * You're free to add application-wide styles to this file and they'll appear at the top of the
+ * compiled file, but it's generally better to create a new file per style scope.
+ *
+ *= require_self
+ *= require_tree .
+ */
View
3 test/dummy/app/controllers/application_controller.rb
@@ -0,0 +1,3 @@
+class ApplicationController < ActionController::Base
+ protect_from_forgery
+end
View
2 test/dummy/app/helpers/application_helper.rb
@@ -0,0 +1,2 @@
+module ApplicationHelper
+end
View
0 test/dummy/app/mailers/.gitkeep
No changes.
View
0 test/dummy/app/models/.gitkeep
No changes.
View
3 test/dummy/app/models/user.rb
@@ -0,0 +1,3 @@
+class User < ActiveRecord::Base
+ # attr_accessible :title, :body
+end
View
16 test/dummy/app/views/layouts/application.html.erb
@@ -0,0 +1,16 @@
+<!DOCTYPE html>
+<html>
+<head>
+ <title>Dummy</title>
+ <%= stylesheet_link_tag "application", :media => "all" %>
+ <%= javascript_include_tag "application" %>
+ <%= csrf_meta_tags %>
+</head>
+<body>
+
+<%= logged_in? ? "yes" : "no" %>
+
+<%= yield %>
+
+</body>
+</html>
View
4 test/dummy/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 Dummy::Application
View
66 test/dummy/config/application.rb
@@ -0,0 +1,66 @@
+require File.expand_path('../boot', __FILE__)
+
+# require 'rails/all'
+require "active_record/railtie"
+require "action_controller/railtie"
+require "action_mailer/railtie"
+require "active_resource/railtie"
+require "sprockets/railtie"
+# require "rails/test_unit/railtie"
+
+
+Bundler.require
+require "thincloud-authentication"
+
+module Dummy
+ 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
+
+ # 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]
+
+ # Enable escaping HTML in JSON.
+ config.active_support.escape_html_entities_in_json = true
+
+ # Use SQL instead of Active Record's schema dumper when creating the 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
+
+ # Enforce whitelist mode for mass assignment.
+ # This will create an empty whitelist of attributes available for mass-assignment for all models
+ # in your app. As such, your models will need to explicitly whitelist or blacklist accessible
+ # parameters by using an attr_accessible or attr_protected declaration.
+ config.active_record.whitelist_attributes = true
+
+ # Enable the asset pipeline
+ config.assets.enabled = true
+
+ # Version of your assets, change this if you want to expire all your assets
+ config.assets.version = '1.0'
+ end
+end
+
View
10 test/dummy/config/boot.rb
@@ -0,0 +1,10 @@
+require 'rubygems'
+gemfile = File.expand_path('../../../../Gemfile', __FILE__)
+
+if File.exist?(gemfile)
+ ENV['BUNDLE_GEMFILE'] = gemfile
+ require 'bundler'
+ Bundler.setup
+end
+
+$:.unshift File.expand_path('../../../../lib', __FILE__)
View
25 test/dummy/config/database.yml
@@ -0,0 +1,25 @@
+# SQLite version 3.x
+# gem install sqlite3
+#
+# Ensure the SQLite 3 gem is defined in your Gemfile
+# gem 'sqlite3'
+development:
+ adapter: sqlite3
+ database: db/development.sqlite3
+ pool: 5
+ timeout: 5000
+
+# Warning: The database defined as "test" will be erased and
+# re-generated from your development database when you run "rake".
+# Do not set this db to the same as development or production.
+test:
+ adapter: sqlite3
+ database: db/test.sqlite3
+ pool: 5
+ timeout: 5000
+
+production:
+ adapter: sqlite3
+ database: db/production.sqlite3
+ pool: 5
+ timeout: 5000
View
5 test/dummy/config/environment.rb
@@ -0,0 +1,5 @@
+# Load the rails application
+require File.expand_path('../application', __FILE__)
+
+# Initialize the rails application
+Dummy::Application.initialize!
View
37 test/dummy/config/environments/development.rb
@@ -0,0 +1,37 @@
+Dummy::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 web server 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_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
+
+ # Raise exception on mass assignment protection for Active Record models
+ config.active_record.mass_assignment_sanitizer = :strict
+
+ # Log the query plan for queries taking more than this (works
+ # with SQLite, MySQL, and PostgreSQL)
+ config.active_record.auto_explain_threshold_in_seconds = 0.5
+
+ # Do not compress assets
+ config.assets.compress = false
+
+ # Expands the lines which load the assets
+ config.assets.debug = true
+end
View
67 test/dummy/config/environments/production.rb
@@ -0,0 +1,67 @@
+Dummy::Application.configure do
+ # Settings specified here will take precedence over those in config/application.rb
+
+ # 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
+
+ # Disable Rails's static asset server (Apache or nginx will already do this)
+ config.serve_static_assets = false
+
+ # Compress JavaScripts and CSS
+ config.assets.compress = true
+
+ # Don't fallback to assets pipeline if a precompiled asset is missed
+ config.assets.compile = false
+
+ # Generate digests for assets URLs
+ config.assets.digest = true
+
+ # Defaults to nil and saved in location specified by config.assets.prefix
+ # config.assets.manifest = YOUR_PATH
+
+ # Specifies the header that your server uses for sending files
+ # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
+ # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
+
+ # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
+ # config.force_ssl = true
+
+ # See everything in the log (default is :info)
+ # config.log_level = :debug
+
+ # Prepend all log lines with the following tags
+ # config.log_tags = [ :subdomain, :uuid ]
+
+ # Use a different logger for distributed setups
+ # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
+
+ # Use a different cache store in production
+ # config.cache_store = :mem_cache_store
+
+ # Enable serving of images, stylesheets, and JavaScripts from an asset server
+ # config.action_controller.asset_host = "http://assets.example.com"
+
+ # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
+ # config.assets.precompile += %w( search.js )
+
+ # 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
+
+ # Log the query plan for queries taking more than this (works
+ # with SQLite, MySQL, and PostgreSQL)
+ # config.active_record.auto_explain_threshold_in_seconds = 0.5
+end
View
37 test/dummy/config/environments/test.rb
@@ -0,0 +1,37 @@
+Dummy::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
+
+ # Configure static asset server for tests with Cache-Control for performance
+ config.serve_static_assets = true
+ config.static_cache_control = "public, max-age=3600"
+
+ # 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
+
+ # Raise exception on mass assignment protection for Active Record models
+ config.active_record.mass_assignment_sanitizer = :strict
+
+ # Print deprecation notices to the stderr
+ config.active_support.deprecation = :stderr
+end
View
7 test/dummy/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!
View
15 test/dummy/config/initializers/inflections.rb
@@ -0,0 +1,15 @@
+# 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
+#
+# These inflection rules are supported but not enabled by default:
+# ActiveSupport::Inflector.inflections do |inflect|
+# inflect.acronym 'RESTful'
+# end
View
5 test/dummy/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
View
7 test/dummy/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.
+Dummy::Application.config.secret_token = '10f26bd4422ca14f13654103c24674b87a3a02ca0a5018de8aea342981579c4395f65989b3a31740f6dc089dd1bbefbc6e9372d96e4be8adb709b8bc66da6878'
View
8 test/dummy/config/initializers/session_store.rb
@@ -0,0 +1,8 @@
+# Be sure to restart your server when you modify this file.
+
+Dummy::Application.config.session_store :cookie_store, key: '_dummy_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")
+# Dummy::Application.config.session_store :active_record_store
View
14 test/dummy/config/initializers/wrap_parameters.rb
@@ -0,0 +1,14 @@
+# Be sure to restart your server when you modify this file.
+#
+# This file contains settings for ActionController::ParamsWrapper which
+# is enabled by default.
+
+# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
+ActiveSupport.on_load(:action_controller) do
+ wrap_parameters format: [:json]
+end
+
+# Disable root element in JSON by default.
+ActiveSupport.on_load(:active_record) do
+ self.include_root_in_json = false
+end
View
5 test/dummy/config/locales/en.yml
@@ -0,0 +1,5 @@
+# Sample localization file for English. Add more files in this directory for other locales.
+# See https://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
+
+en:
+ hello: "Hello world"
View
25 test/dummy/config/routes.rb
@@ -0,0 +1,25 @@
+Rails.application.routes.draw do
+
+ mount Thincloud::Authentication::Engine => "/auth"
+
+ namespace :thincloud do
+ namespace :authentication do
+ match "auth/:provider/callback" => "registrations#create"
+ get "auth/failure", to: "sessions#new"
+
+ get "login", to: "sessions#new", as: "login"
+ delete "logout", to: "sessions#destroy", as: "logout"
+ get "authenticated", to: "sessions#authenticated"
+
+ resources :registrations, only: [:new, :create]
+ get "signup", to: "registrations#new", as: "signup"
+ get "verify/:token", to: "registrations#verify", as: "verify_token"
+ end
+ end
+
+ match "auth/:provider/callback" => "thincloud/authentication/registrations#create", as: "auth_callback"
+ get "auth/failure", to: "thincloud/authentication/sessions#new"
+ get "login", to: "thincloud/authentication/sessions#new"
+
+ root to: "thincloud/authentication/sessions#new"
+end
View
8 test/dummy/db/migrate/20120919182522_create_users.rb
@@ -0,0 +1,8 @@
+class CreateUsers < ActiveRecord::Migration
+ def change
+ create_table :users do |t|
+
+ t.timestamps
+ end
+ end
+end
View
38 test/dummy/db/schema.rb
@@ -0,0 +1,38 @@
+# encoding: UTF-8
+# This file is auto-generated from the current state of the database. Instead
+# of editing this file, please use the migrations feature of Active Record to
+# incrementally modify your database, and then regenerate this schema definition.
+#
+# Note that this schema.rb definition is the authoritative source for your
+# database schema. If you need to create the application database on another
+# system, you should be using db:schema:load, not running all the migrations
+# from scratch. The latter is a flawed and unsustainable approach (the more migrations
+# you'll amass, the slower it'll run and the greater likelihood for issues).
+#
+# It's strongly recommended to check this file into your version control system.
+
+ActiveRecord::Schema.define(:version => 20120919182522) do
+
+ create_table "thincloud_authentication_identities", :force => true do |t|
+ t.integer "user_id", :null => false
+ t.string "provider", :default => "identity", :null => false
+ t.string "uid"
+ t.string "name", :null => false
+ t.string "email", :null => false
+ t.string "password_digest", :null => false
+ t.string "verification_token"
+ t.datetime "verified_at"
+ t.datetime "created_at", :null => false
+ t.datetime "updated_at", :null => false
+ end
+
+ add_index "thincloud_authentication_identities", ["email"], :name => "index_thincloud_authentication_identities_on_email"
+ add_index "thincloud_authentication_identities", ["provider", "uid"], :name => "index_thincloud_authentication_identities_on_provider_and_uid", :unique => true
+ add_index "thincloud_authentication_identities", ["user_id"], :name => "index_thincloud_authentication_identities_on_user_id"
+
+ create_table "users", :force => true do |t|
+ t.datetime "created_at", :null => false
+ t.datetime "updated_at", :null => false
+ end
+
+end
View
0 test/dummy/lib/assets/.gitkeep
No changes.
View
0 test/dummy/log/.gitkeep
No changes.
View
26 test/dummy/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>
View
26 test/dummy/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>
View
25 test/dummy/public/500.html
@@ -0,0 +1,25 @@
+<!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>
+ </div>
+</body>
+</html>
View
0 test/dummy/public/favicon.ico
No changes.
View
6 test/dummy/script/rails
@@ -0,0 +1,6 @@
+#!/usr/bin/env ruby
+# This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application.
+
+APP_PATH = File.expand_path('../../config/application', __FILE__)
+require File.expand_path('../../config/boot', __FILE__)
+require 'rails/commands'
View
18 test/minitest_helper.rb
@@ -0,0 +1,18 @@
+require "simplecov"
+SimpleCov.add_filter "test"
+SimpleCov.add_filter "config"
+SimpleCov.command_name "MiniTest"
+SimpleCov.start
+
+ENV["RAILS_ENV"] = "test"
+require File.expand_path("../dummy/config/environment", __FILE__)
+
+require "minitest/autorun"
+require "minitest/rails"
+require "minitest/pride"
+require "minitest-rails-shoulda"
+
+Rails.backtrace_cleaner.remove_silencers!
+
+# Load support files
+Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }
View
82 test/models/identity_test.rb
@@ -0,0 +1,82 @@
+require "minitest_helper"
+
+module Thincloud::Authentication
+ describe Identity do
+ let(:identity) { Identity.new }
+
+ it { identity.must validate_presence_of(:name) }
+ it { identity.must validate_presence_of(:email) }
+ it { identity.must allow_value("foo@bar.com").for(:email) }
+ it { identity.wont allow_value("foo").for(:email) }
+ it { identity.must validate_presence_of(:password_digest) }
+ it { identity.must validate_confirmation_of(:password) }
+ it { identity.must_respond_to(:verification_token) }
+ it { identity.verification_token.wont_be_nil }
+ it { identity.verification_token.must_match /[\w\-]{22}/ }
+ it { identity.must_respond_to(:verified_at) }
+
+ describe "self.find_omniauth(omniauth)" do
+ let(:auth_hash) do
+ OmniAuth::AuthHash.new(provider: "identity", uid: "123")
+ end
+
+ before do
+ Identity.expects(:find_by_provider_and_uid).with("identity", "123")
+ end
+
+ it { Identity.find_omniauth(auth_hash) }
+ end
+
+ describe "self.verify!(token)" do
+ it "raises an exception" do
+ -> {
+ Identity.verify!("invalid")
+ }.must_raise(ActiveRecord::RecordNotFound)
+ end
+
+ describe "when found" do
+ before do
+ Identity.stubs(:find_by_verification_token!).with("token").returns(
+ identity
+ )
+ Identity.any_instance.stubs(:save).returns(identity)
+ end
+
+ it { Identity.verify!("token").must_equal identity }
+ end
+ end
+
+ describe "#verified?" do
+ it { identity.verified?.must_equal false }
+
+ describe "when true" do
+ before do
+ identity.verification_token = nil
+ identity.verified_at = Time.now
+ end
+
+ it { identity.verified?.must_equal true }
+ end
+ end
+
+ describe "#apply_omniauth(omniauth)" do
+ let(:identity) { Identity.new }
+ let(:auth_hash) do
+ OmniAuth::AuthHash.new(
+ provider: "linkedin", uid: "xxsdflkjsdf",
+ credentials: Hashie::Mash.new, extra: Hashie::Mash.new,
+ info: OmniAuth::AuthHash::InfoHash.new(
+ email: "foo@bar.com", first_name: "New", last_name: "Name",
+ )
+ )
+ end
+
+ before { identity.apply_omniauth(auth_hash) }
+
+ it { identity.name.must_equal "New Name" }
+ it { identity.email.must_equal "foo@bar.com" }
+ it { identity.provider.must_equal "linkedin" }
+ it { identity.uid.must_equal "xxsdflkjsdf" }
+ end
+ end
+end
View
13 test/models/user_test.rb
@@ -0,0 +1,13 @@
+require "minitest_helper"
+
+module Thincloud::Authentication
+ describe User do
+ before do
+ @user = User.new
+ end
+
+ it "must be valid" do
+ @user.valid?.must_equal true
+ end
+ end
+end
View
8 test/support/user.rb
@@ -0,0 +1,8 @@
+module Thincloud
+ module Authentication
+ class User < ActiveRecord::Base
+ has_many :identities, class_name: "Thincloud::Authentication::Identity"
+ self.table_name = "users"
+ end
+ end
+end
View
7 test/thincloud-authentication_test.rb
@@ -0,0 +1,7 @@
+require "minitest_helper"
+
+class Thincloud::AuthenticationTest < ActiveSupport::TestCase
+ test "truth" do
+ assert_kind_of Module, Thincloud::Authentication
+ end
+end
View
34 thincloud-authentication.gemspec
@@ -0,0 +1,34 @@
+$:.push File.expand_path("../lib", __FILE__)
+
+# Maintain your gem's version:
+require "thincloud/authentication/version"
+
+# Describe your gem and declare its dependencies:
+Gem::Specification.new do |s|
+ s.name = "thincloud-authentication"
+ s.version = Thincloud::Authentication::VERSION
+ s.authors = ["Phil Cohen", "Robert Bousquet"]
+ s.email = ["pcohen@newleaders.com", "rbousquet@newleaders.com"]
+ s.homepage = "https://github.com/newleaders/thincloud-authentication"
+ s.summary = "Rails Engine to provide authentication for Thincloud applications"
+ s.description = "Rails Engine to provide authentication for Thincloud applications"
+
+ s.files = Dir["{app,config,db,lib}/**/*"] + %w[MIT-LICENSE Rakefile README.md]
+
+ s.add_dependency "rails", "~> 3.2.8"
+ s.add_dependency "omniauth", "~> 1.1.1"
+ s.add_dependency "omniauth-identity", "~> 1.1.0"
+
+ s.add_development_dependency "sqlite3"
+ s.add_development_dependency "cane"
+ s.add_development_dependency "guard"
+ s.add_development_dependency "growl"
+ s.add_development_dependency "minitest"
+ s.add_development_dependency "guard-minitest"
+ s.add_development_dependency "minitest-rails"
+ s.add_development_dependency "minitest-rails-shoulda"
+ s.add_development_dependency "rb-fsevent"
+ s.add_development_dependency "simplecov"
+ s.add_development_dependency "mocha" # Must be after minitest
+
+end

0 comments on commit 013a8b2

Please sign in to comment.
Something went wrong with that request. Please try again.