├── .gitignore ├── CHANGELOG.md ├── Gemfile ├── MIT-LICENSE ├── README.md ├── Rakefile ├── devise_ldap_authenticatable.gemspec ├── lib ├── devise_ldap_authenticatable.rb ├── devise_ldap_authenticatable │ ├── exception.rb │ ├── ldap │ │ ├── adapter.rb │ │ └── connection.rb │ ├── logger.rb │ ├── model.rb │ ├── strategy.rb │ └── version.rb └── generators │ └── devise_ldap_authenticatable │ ├── install_generator.rb │ └── templates │ └── ldap.yml └── spec ├── ldap ├── .gitignore ├── base.ldif ├── clear.ldif ├── local.schema ├── openldap-data │ ├── .gitignore │ └── run │ │ ├── .gitignore │ │ └── .gitkeep ├── run-server ├── server.pem └── slapd-test.conf.erb ├── rails_app ├── Rakefile ├── app │ ├── controllers │ │ ├── application_controller.rb │ │ └── posts_controller.rb │ ├── helpers │ │ ├── application_helper.rb │ │ └── posts_helper.rb │ ├── models │ │ ├── post.rb │ │ └── user.rb │ └── views │ │ ├── layouts │ │ └── application.html.erb │ │ └── posts │ │ └── index.html.erb ├── config.ru ├── config │ ├── application.rb │ ├── boot.rb │ ├── cucumber.yml │ ├── database.yml │ ├── environment.rb │ ├── environments │ │ ├── development.rb │ │ ├── production.rb │ │ └── test.rb │ ├── initializers │ │ ├── backtrace_silencers.rb │ │ ├── devise.rb │ │ ├── inflections.rb │ │ ├── mime_types.rb │ │ ├── secret_token.rb │ │ └── session_store.rb │ ├── ldap.yml │ ├── ldap_with_boolean_ssl.yml │ ├── ldap_with_erb.yml │ ├── ldap_with_uid.yml │ ├── locales │ │ ├── devise.en.yml │ │ └── en.yml │ ├── routes.rb │ ├── ssl_ldap.yml │ ├── ssl_ldap_with_erb.yml │ └── ssl_ldap_with_uid.yml ├── db │ ├── migrate │ │ └── 20100708120448_devise_create_users.rb │ └── schema.rb ├── features │ ├── manage_logins.feature │ ├── step_definitions │ │ ├── login_steps.rb │ │ └── web_steps.rb │ └── support │ │ ├── env.rb │ │ └── paths.rb ├── lib │ └── tasks │ │ ├── .gitkeep │ │ └── cucumber.rake ├── public │ ├── 404.html │ ├── 422.html │ ├── 500.html │ ├── images │ │ └── rails.png │ ├── javascripts │ │ ├── application.js │ │ ├── controls.js │ │ ├── dragdrop.js │ │ ├── effects.js │ │ ├── prototype.js │ │ └── rails.js │ └── stylesheets │ │ └── .gitkeep └── script │ ├── cucumber │ └── rails ├── spec_helper.rb ├── support └── factories.rb └── unit ├── adapter_spec.rb ├── connection_spec.rb └── user_spec.rb /.gitignore: -------------------------------------------------------------------------------- 1 | .bundle 2 | Gemfile.lock 3 | log 4 | *.sqlite3 5 | test/ldap/openldap-data/* 6 | !test/ldap/openldap-data/run 7 | test/ldap/openldap-data/run/slapd.* 8 | test/rails_app/tmp 9 | pkg/* 10 | *.gem 11 | .vscode 12 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | CHANGELOG 2 | ========= 3 | 4 | v0.8 5 | ---- 6 | 7 | [Issue #102](https://github.com/cschiewek/devise_ldap_authenticatable/pull/102): Extract method in_group? from in_required_groups? and expose it to the model 8 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | source "http://rubygems.org" 2 | 3 | gemspec 4 | 5 | group :development, :test do 6 | gem 'debugger', platform: :ruby_19 7 | gem 'byebug', platform: :ruby_20 8 | end -------------------------------------------------------------------------------- /MIT-LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2010 Curtis Schiewek 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining 4 | a copy of this software and associated documentation files (the 5 | "Software"), to deal in the Software without restriction, including 6 | without limitation the rights to use, copy, modify, merge, publish, 7 | distribute, sublicense, and/or sell copies of the Software, and to 8 | permit persons to whom the Software is furnished to do so, subject to 9 | the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be 12 | included in all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 15 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 17 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 18 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 19 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 20 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Devise LDAP Authenticatable 2 | =========================== 3 | 4 | [![Gem Version](https://badge.fury.io/rb/devise_ldap_authenticatable.svg)](http://badge.fury.io/rb/devise_ldap_authenticatable) 5 | [![Code Climate](https://codeclimate.com/github/cschiewek/devise_ldap_authenticatable.svg)](https://codeclimate.com/github/cschiewek/devise_ldap_authenticatable) 6 | 7 | Devise LDAP Authenticatable is a LDAP based authentication strategy for the [Devise](http://github.com/plataformatec/devise) authentication framework. 8 | 9 | If you are building applications for use within your organization which require authentication and you want to use LDAP, this plugin is for you. 10 | 11 | Devise LDAP Authenticatable works in replacement of Database Authenticatable. This devise plugin has not been tested with DatabaseAuthenticatable enabled at the same time. This is meant as a drop in replacement for DatabaseAuthenticatable allowing for a semi single sign on approach. 12 | 13 | For a screencast with an example application, please visit: [http://corrupt.net/2010/07/05/LDAP-Authentication-With-Devise/](http://corrupt.net/2010/07/05/LDAP-Authentication-With-Devise/) 14 | 15 | Prerequisites 16 | ------------- 17 | * devise ~> 3.0.0 (which requires rails ~> 4.0) 18 | * net-ldap ~> 0.6.0 19 | 20 | Note: Rails 3.x / Devise 2.x has been moved to the 0.7 branch. All 0.7.x gems will support Rails 3, where as 0.8.x will support Rails 4. 21 | 22 | If you are transitioning from having Devise manage your users' passwords in the database to using LDAP auth, you may have to update your `users` table to make `encrypted_password` nullable, or else the LDAP user insert will fail. 23 | 24 | Usage 25 | ----- 26 | In the Gemfile for your application: 27 | 28 | ```ruby 29 | gem "devise_ldap_authenticatable" 30 | ``` 31 | To get the latest version, pull directly from github instead of the gem: 32 | 33 | ```ruby 34 | gem "devise_ldap_authenticatable", :git => "git://github.com/cschiewek/devise_ldap_authenticatable.git" 35 | ``` 36 | 37 | Setup 38 | ----- 39 | Run the rails generators for devise (please check the [devise](http://github.com/plataformatec/devise) documents for further instructions) 40 | 41 | rails generate devise:install 42 | rails generate devise MODEL_NAME 43 | 44 | Run the rails generator for `devise_ldap_authenticatable` 45 | 46 | rails generate devise_ldap_authenticatable:install [options] 47 | 48 | This will install the ldap.yml, update the devise.rb initializer, and update your user model. There are some options you can pass to it: 49 | 50 | Options: 51 | 52 | [--user-model=USER_MODEL] # Model to update 53 | # Default: user 54 | [--update-model] # Update model to change from database_authenticatable to ldap_authenticatable 55 | # Default: true 56 | [--add-rescue] # Update Application Controller with rescue_from for DeviseLdapAuthenticatable::LdapException 57 | # Default: true 58 | [--advanced] # Add advanced config options to the devise initializer 59 | 60 | Querying LDAP 61 | ------------- 62 | Given that `ldap_create_user` is set to true and you are authenticating with username, you can query an LDAP server for other attributes. 63 | 64 | in your user model you have to simply define `ldap_before_save` method: 65 | 66 | ```ruby 67 | def ldap_before_save 68 | self.email = Devise::LDAP::Adapter.get_ldap_param(self.username,"mail").first 69 | end 70 | ``` 71 | 72 | Configuration 73 | ------------- 74 | In initializer `config/initializers/devise.rb` : 75 | 76 | * `ldap_logger` _(default: true)_ 77 | * If set to true, will log LDAP queries to the Rails logger. 78 | * `ldap_create_user` _(default: false)_ 79 | * If set to true, all valid LDAP users will be allowed to login and an appropriate user record will be created. If set to false, you will have to create the user record before they will be allowed to login. 80 | * `ldap_config` _(default: #{Rails.root}/config/ldap.yml)_ 81 | * Where to find the LDAP config file. Commented out to use the default, change if needed. 82 | * `ldap_update_password` _(default: true)_ 83 | * When doing password resets, if true will update the LDAP server. Requires admin password in the ldap.yml 84 | * `ldap_check_group_membership` _(default: false)_ 85 | * When set to true, the user trying to login will be checked to make sure they are in all of groups specified in the ldap.yml file. 86 | * `ldap_check_attributes` _(default: false)_ 87 | * When set to true, the user trying to login will be checked to make sure their attributes match those specified in the ldap.yml file. 88 | * `ldap_check_attributes_presence` _(default: false)_ 89 | * When set to true, the user trying to login will be checked against all `require_attribute_presence` attributes in the ldap.yml file, either present _(attr: true)_,or not present _(attr: false)_. 90 | * `ldap_use_admin_to_bind` _(default: false)_ 91 | * When set to true, the admin user will be used to bind to the LDAP server during authentication. 92 | * `ldap_check_group_membership_without_admin` _(default: false)_ 93 | * When set to true, the group membership check is done with the user's own credentials rather than with admin credentials. Since these credentials are only available to the Devise user model during the login flow, the group check function will not work if a group check is performed when this option is true outside of the login flow (e.g., before particular actions). 94 | 95 | Advanced Configuration 96 | ---------------------- 97 | These parameters will be added to `config/initializers/devise.rb` when you pass the `--advanced` switch to the generator: 98 | 99 | * `ldap_auth_username_builder` _(default: `Proc.new() {|attribute, login, ldap| "#{attribute}=#{login},#{ldap.base}" }`)_ 100 | * You can pass a proc to the username option to explicitly specify the format that you search for a users' DN on your LDAP server. 101 | * `ldap_auth_password_build` _(default: `Proc.new() {|new_password| Net::LDAP::Password.generate(:sha, new_password) }`)_ 102 | * Optionally you can define a proc to create custom password encrption when user reset password 103 | 104 | Troubleshooting 105 | -------------- 106 | **Using a "username" instead of an "email":** The field that is used for logins is the first key that's configured in the `config/initializers/devise.rb` file under `config.authentication_keys`, which by default is email. For help changing this, please see the [Railscast](http://railscasts.com/episodes/210-customizing-devise) that goes through how to customize Devise. Also, this [documentation](https://github.com/plataformatec/devise/wiki/How-To%3a-Allow-users-to-sign-in-using-their-username-or-email-address) from Devise can be very helpful. 107 | 108 | **SSL certificate invalid:** If you're using a test LDAP server running a self-signed SSL certificate, make sure the appropriate root certificate is installed on your system. Alternately, you may temporarily disable certificate checking for SSL by modifying your system LDAP configuration (e.g., `/etc/openldap/ldap.conf` or `/etc/ldap/ldap.conf`) to read `TLS_REQCERT never`. 109 | 110 | Discussion Group 111 | ------------ 112 | 113 | For additional support, questions or discussions, please see the discussion forum on [Google Groups](https://groups.google.com/forum/#!forum/devise_ldap_authenticatable) 114 | 115 | Development guide 116 | ------------ 117 | 118 | Devise LDAP Authenticatable uses a running OpenLDAP server to do automated acceptance tests. You'll need the executables `slapd`, `ldapadd`, and `ldapmodify`. 119 | 120 | On OS X, this is available out of the box. 121 | 122 | On Ubuntu, you can install OpenLDAP with `sudo apt-get install slapd ldap-utils`. If slapd runs under AppArmor, add an exception like this to `/etc/apparmor.d/local/usr.sbin.slapd` to let slapd read our configs (reload using `sudo service apparmor reload` afterwards). 123 | 124 | /path/to/devise_ldap_authenticatable/spec/ldap/** rw, 125 | 126 | To start hacking on `devise_ldap_authentication`, clone the github repository, start the test LDAP server, and run the rake test task: 127 | 128 | git clone https://github.com/cschiewek/devise_ldap_authenticatable.git 129 | cd devise_ldap_authenticatable 130 | bundle install 131 | 132 | # in a separate console or backgrounded 133 | ./spec/ldap/run-server 134 | 135 | RAILS_ENV=test bundle exec rake db:migrate # first time only 136 | bundle exec rake spec 137 | 138 | References 139 | ---------- 140 | * [OpenLDAP](http://www.openldap.org/) 141 | * [Devise](http://github.com/plataformatec/devise) 142 | * [Warden](http://github.com/hassox/warden) 143 | 144 | Released under the MIT license 145 | 146 | Copyright (c) 2012 [Curtis Schiewek](https://github.com/cschiewek), [Daniel McNevin](https://github.com/dpmcnevin), [Steven Xu](https://github.com/cairo140) 147 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | require File.expand_path('spec/rails_app/config/environment', File.dirname(__FILE__)) 2 | require 'rdoc/task' 3 | 4 | desc 'Default: run test suite.' 5 | task :default => :spec 6 | 7 | desc 'Generate documentation for the devise_ldap_authenticatable plugin.' 8 | Rake::RDocTask.new(:rdoc) do |rdoc| 9 | rdoc.rdoc_dir = 'rdoc' 10 | rdoc.title = 'DeviseLDAPAuthenticatable' 11 | rdoc.options << '--line-numbers' << '--inline-source' 12 | rdoc.rdoc_files.include('README.md') 13 | rdoc.rdoc_files.include('lib/**/*.rb') 14 | end 15 | 16 | RailsApp::Application.load_tasks 17 | -------------------------------------------------------------------------------- /devise_ldap_authenticatable.gemspec: -------------------------------------------------------------------------------- 1 | # -*- encoding: utf-8 -*- 2 | $:.push File.expand_path("../lib", __FILE__) 3 | require "devise_ldap_authenticatable/version" 4 | 5 | Gem::Specification.new do |s| 6 | s.name = 'devise_ldap_authenticatable' 7 | s.version = DeviseLdapAuthenticatable::VERSION.dup 8 | s.platform = Gem::Platform::RUBY 9 | s.summary = 'Devise extension to allow authentication via LDAP' 10 | s.email = 'curtis.schiewek@gmail.com' 11 | s.homepage = 'https://github.com/cschiewek/devise_ldap_authenticatable' 12 | s.description = s.summary 13 | s.authors = ['Curtis Schiewek', 'Daniel McNevin', 'Steven Xu'] 14 | s.license = 'MIT' 15 | 16 | s.files = `git ls-files`.split("\n") 17 | s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") 18 | s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } 19 | s.require_paths = ["lib"] 20 | 21 | s.add_dependency 'devise', '>= 3.4.1' 22 | s.add_dependency 'net-ldap', '>= 0.16.0' 23 | 24 | s.add_development_dependency 'rake', '>= 0.9' 25 | s.add_development_dependency 'rdoc', '>= 3' 26 | s.add_development_dependency 'rails', '>= 4.0' 27 | s.add_development_dependency 'sqlite3' 28 | s.add_development_dependency 'factory_girl_rails', '~> 1.0' 29 | s.add_development_dependency 'factory_girl', '~> 2.0' 30 | s.add_development_dependency 'rspec-rails' 31 | 32 | %w{database_cleaner capybara launchy}.each do |dep| 33 | s.add_development_dependency(dep) 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /lib/devise_ldap_authenticatable.rb: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | require 'devise' 3 | require 'net/ldap' 4 | 5 | require 'devise_ldap_authenticatable/exception' 6 | require 'devise_ldap_authenticatable/logger' 7 | require 'devise_ldap_authenticatable/ldap/adapter' 8 | require 'devise_ldap_authenticatable/ldap/connection' 9 | 10 | # Get ldap information from config/ldap.yml now 11 | module Devise 12 | # Allow logging 13 | mattr_accessor :ldap_logger 14 | @@ldap_logger = true 15 | 16 | # Add valid users to database 17 | mattr_accessor :ldap_create_user 18 | @@ldap_create_user = false 19 | 20 | # A path to YAML config file or a Proc that returns a 21 | # configuration hash 22 | mattr_accessor :ldap_config 23 | # @@ldap_config = "#{Rails.root}/config/ldap.yml" 24 | 25 | mattr_accessor :ldap_update_password 26 | @@ldap_update_password = true 27 | 28 | mattr_accessor :ldap_check_group_membership 29 | @@ldap_check_group_membership = false 30 | 31 | mattr_accessor :ldap_check_group_membership_without_admin 32 | @@ldap_check_group_membership_without_admin = false 33 | 34 | mattr_accessor :ldap_check_attributes 35 | @@ldap_check_role_attribute = false 36 | 37 | mattr_accessor :ldap_check_attributes_presence 38 | @@ldap_check_attributes_presence = false 39 | 40 | mattr_accessor :ldap_use_admin_to_bind 41 | @@ldap_use_admin_to_bind = false 42 | 43 | mattr_accessor :ldap_auth_username_builder 44 | @@ldap_auth_username_builder = Proc.new() {|attribute, login, ldap| "#{attribute}=#{login},#{ldap.base}" } 45 | 46 | mattr_accessor :ldap_auth_password_builder 47 | @@ldap_auth_password_builder = Proc.new() {|new_password| Net::LDAP::Password.generate(:sha, new_password) } 48 | 49 | mattr_accessor :ldap_ad_group_check 50 | @@ldap_ad_group_check = false 51 | end 52 | 53 | # Add ldap_authenticatable strategy to defaults. 54 | # 55 | Devise.add_module(:ldap_authenticatable, 56 | :route => :session, ## This will add the routes, rather than in the routes.rb 57 | :strategy => true, 58 | :controller => :sessions, 59 | :model => 'devise_ldap_authenticatable/model') 60 | -------------------------------------------------------------------------------- /lib/devise_ldap_authenticatable/exception.rb: -------------------------------------------------------------------------------- 1 | module DeviseLdapAuthenticatable 2 | 3 | class LdapException < Exception 4 | end 5 | 6 | end 7 | -------------------------------------------------------------------------------- /lib/devise_ldap_authenticatable/ldap/adapter.rb: -------------------------------------------------------------------------------- 1 | require "net/ldap" 2 | 3 | module Devise 4 | module LDAP 5 | DEFAULT_GROUP_UNIQUE_MEMBER_LIST_KEY = 'uniqueMember' 6 | 7 | module Adapter 8 | def self.valid_credentials?(login, password_plaintext) 9 | options = {:login => login, 10 | :password => password_plaintext, 11 | :ldap_auth_username_builder => ::Devise.ldap_auth_username_builder, 12 | :admin => ::Devise.ldap_use_admin_to_bind} 13 | 14 | resource = Devise::LDAP::Connection.new(options) 15 | resource.authorized? 16 | end 17 | 18 | def self.expired_valid_credentials?(login, password_plaintext) 19 | options = {:login => login, 20 | :password => password_plaintext, 21 | :ldap_auth_username_builder => ::Devise.ldap_auth_username_builder, 22 | :admin => ::Devise.ldap_use_admin_to_bind} 23 | 24 | resource = Devise::LDAP::Connection.new(options) 25 | resource.expired_valid_credentials? 26 | end 27 | 28 | def self.update_password(login, new_password) 29 | options = {:login => login, 30 | :new_password => new_password, 31 | :ldap_auth_username_builder => ::Devise.ldap_auth_username_builder, 32 | :admin => ::Devise.ldap_use_admin_to_bind} 33 | 34 | resource = Devise::LDAP::Connection.new(options) 35 | resource.change_password! if new_password.present? 36 | end 37 | 38 | def self.update_own_password(login, new_password, current_password) 39 | set_ldap_param(login, :userPassword, ::Devise.ldap_auth_password_builder.call(new_password), current_password) 40 | end 41 | 42 | def self.ldap_connect(login) 43 | options = {:login => login, 44 | :ldap_auth_username_builder => ::Devise.ldap_auth_username_builder, 45 | :admin => ::Devise.ldap_use_admin_to_bind} 46 | 47 | Devise::LDAP::Connection.new(options) 48 | end 49 | 50 | def self.valid_login?(login) 51 | self.ldap_connect(login).valid_login? 52 | end 53 | 54 | def self.get_groups(login) 55 | self.ldap_connect(login).user_groups 56 | end 57 | 58 | def self.in_ldap_group?(login, group_name, group_attribute = nil) 59 | self.ldap_connect(login).in_group?(group_name, group_attribute) 60 | end 61 | 62 | def self.get_dn(login) 63 | self.ldap_connect(login).dn 64 | end 65 | 66 | def self.set_ldap_param(login, param, new_value, password = nil) 67 | options = {:login => login, 68 | :ldap_auth_username_builder => ::Devise.ldap_auth_username_builder, 69 | :password => password } 70 | 71 | resource = Devise::LDAP::Connection.new(options) 72 | resource.set_param(param, new_value) 73 | end 74 | 75 | def self.delete_ldap_param(login, param, password = nil) 76 | options = {:login => login, 77 | :ldap_auth_username_builder => ::Devise.ldap_auth_username_builder, 78 | :password => password } 79 | 80 | resource = Devise::LDAP::Connection.new(options) 81 | resource.delete_param(param) 82 | end 83 | 84 | def self.get_ldap_param(login,param) 85 | resource = self.ldap_connect(login) 86 | resource.ldap_param_value(param) 87 | end 88 | 89 | def self.get_ldap_entry(login) 90 | self.ldap_connect(login).search_for_login 91 | end 92 | end 93 | end 94 | end 95 | -------------------------------------------------------------------------------- /lib/devise_ldap_authenticatable/ldap/connection.rb: -------------------------------------------------------------------------------- 1 | module Devise 2 | module LDAP 3 | class Connection 4 | attr_reader :ldap, :login 5 | 6 | def initialize(params = {}) 7 | if ::Devise.ldap_config.is_a?(Proc) 8 | ldap_config = ::Devise.ldap_config.call 9 | else 10 | ldap_config = YAML.load(ERB.new(File.read(::Devise.ldap_config || "#{Rails.root}/config/ldap.yml")).result)[Rails.env] 11 | end 12 | ldap_options = params 13 | 14 | # Allow `ssl: true` shorthand in YAML, but enable more control with `encryption` 15 | ldap_config["ssl"] = :simple_tls if ldap_config["ssl"] === true 16 | ldap_options[:encryption] = ldap_config["ssl"].to_sym if ldap_config["ssl"] 17 | ldap_options[:encryption] = ldap_config["encryption"] if ldap_config["encryption"] 18 | 19 | @ldap = Net::LDAP.new(ldap_options) 20 | @ldap.host = ldap_config["host"] 21 | @ldap.port = ldap_config["port"] 22 | @ldap.base = ldap_config["base"] 23 | @attribute = ldap_config["attribute"] 24 | @allow_unauthenticated_bind = ldap_config["allow_unauthenticated_bind"] 25 | 26 | @ldap_auth_username_builder = params[:ldap_auth_username_builder] 27 | 28 | @group_base = ldap_config["group_base"] 29 | @check_group_membership = ldap_config.has_key?("check_group_membership") ? ldap_config["check_group_membership"] : ::Devise.ldap_check_group_membership 30 | @check_group_membership_without_admin = ldap_config.has_key?("check_group_membership_without_admin") ? ldap_config["check_group_membership_without_admin"] : ::Devise.ldap_check_group_membership_without_admin 31 | @required_groups = ldap_config["required_groups"] 32 | @group_membership_attribute = ldap_config.has_key?("group_membership_attribute") ? ldap_config["group_membership_attribute"] : "uniqueMember" 33 | @required_attributes = ldap_config["require_attribute"] 34 | @required_attributes_presence = ldap_config["require_attribute_presence"] 35 | 36 | @ldap.auth ldap_config["admin_user"], ldap_config["admin_password"] if params[:admin] 37 | 38 | @login = params[:login] 39 | @password = params[:password] 40 | @new_password = params[:new_password] 41 | end 42 | 43 | def delete_param(param) 44 | update_ldap [[:delete, param.to_sym, nil]] 45 | end 46 | 47 | def set_param(param, new_value) 48 | update_ldap( { param.to_sym => new_value } ) 49 | end 50 | 51 | def dn 52 | @dn ||= begin 53 | DeviseLdapAuthenticatable::Logger.send("LDAP dn lookup: #{@attribute}=#{@login}") 54 | ldap_entry = search_for_login 55 | if ldap_entry.nil? 56 | @ldap_auth_username_builder.call(@attribute,@login,@ldap) 57 | else 58 | ldap_entry.dn 59 | end 60 | end 61 | end 62 | 63 | def ldap_param_value(param) 64 | ldap_entry = search_for_login 65 | 66 | if ldap_entry 67 | unless ldap_entry[param].empty? 68 | value = ldap_entry.send(param) 69 | DeviseLdapAuthenticatable::Logger.send("Requested param #{param} has value #{value}") 70 | value 71 | else 72 | DeviseLdapAuthenticatable::Logger.send("Requested param #{param} does not exist") 73 | value = nil 74 | end 75 | else 76 | DeviseLdapAuthenticatable::Logger.send("Requested ldap entry does not exist") 77 | value = nil 78 | end 79 | end 80 | 81 | def authenticate! 82 | return false unless (@password.present? || @allow_unauthenticated_bind) 83 | @ldap.auth(dn, @password) 84 | @ldap.bind 85 | end 86 | 87 | def authenticated? 88 | authenticate! 89 | end 90 | 91 | def last_message_bad_credentials? 92 | @ldap.get_operation_result.error_message.to_s.include? 'AcceptSecurityContext error, data 52e' 93 | end 94 | 95 | def last_message_expired_credentials? 96 | @ldap.get_operation_result.error_message.to_s.include? 'AcceptSecurityContext error, data 773' 97 | end 98 | 99 | def authorized? 100 | DeviseLdapAuthenticatable::Logger.send("Authorizing user #{dn}") 101 | if !authenticated? 102 | if last_message_bad_credentials? 103 | DeviseLdapAuthenticatable::Logger.send("Not authorized because of invalid credentials.") 104 | elsif last_message_expired_credentials? 105 | DeviseLdapAuthenticatable::Logger.send("Not authorized because of expired credentials.") 106 | else 107 | DeviseLdapAuthenticatable::Logger.send("Not authorized because not authenticated.") 108 | end 109 | 110 | return false 111 | elsif !in_required_groups? 112 | DeviseLdapAuthenticatable::Logger.send("Not authorized because not in required groups.") 113 | return false 114 | elsif !has_required_attribute? 115 | DeviseLdapAuthenticatable::Logger.send("Not authorized because does not have required attribute.") 116 | return false 117 | elsif !has_required_attribute_presence? 118 | DeviseLdapAuthenticatable::Logger.send("Not authorized because does not have required attribute present.") 119 | return false 120 | else 121 | return true 122 | end 123 | end 124 | 125 | def expired_valid_credentials? 126 | DeviseLdapAuthenticatable::Logger.send("Authorizing user #{dn}") 127 | 128 | !authenticated? && last_message_expired_credentials? 129 | end 130 | 131 | def change_password! 132 | update_ldap(:userPassword => ::Devise.ldap_auth_password_builder.call(@new_password)) 133 | end 134 | 135 | def in_required_groups? 136 | return true unless @check_group_membership || @check_group_membership_without_admin 137 | 138 | ## FIXME set errors here, the ldap.yml isn't set properly. 139 | return false if @required_groups.nil? 140 | 141 | for group in @required_groups 142 | if group.is_a?(Array) 143 | return false unless in_group?(group[1], group[0]) 144 | else 145 | return false unless in_group?(group) 146 | end 147 | end 148 | return true 149 | end 150 | 151 | def in_group?(group_name, group_attribute = LDAP::DEFAULT_GROUP_UNIQUE_MEMBER_LIST_KEY) 152 | in_group = false 153 | 154 | if @check_group_membership_without_admin 155 | group_checking_ldap = @ldap 156 | else 157 | group_checking_ldap = Connection.admin 158 | end 159 | 160 | unless ::Devise.ldap_ad_group_check 161 | group_checking_ldap.search(:base => group_name, :scope => Net::LDAP::SearchScope_BaseObject) do |entry| 162 | if entry[group_attribute].include? dn 163 | in_group = true 164 | DeviseLdapAuthenticatable::Logger.send("User #{dn} IS included in group: #{group_name}") 165 | end 166 | end 167 | else 168 | # AD optimization - extension will recursively check sub-groups with one query 169 | # "(memberof:1.2.840.113556.1.4.1941:=group_name)" 170 | search_result = group_checking_ldap.search(:base => dn, 171 | :filter => Net::LDAP::Filter.ex("memberof:1.2.840.113556.1.4.1941", group_name), 172 | :scope => Net::LDAP::SearchScope_BaseObject) 173 | # Will return the user entry if belongs to group otherwise nothing 174 | if search_result.length == 1 && search_result[0].dn.eql?(dn) 175 | in_group = true 176 | DeviseLdapAuthenticatable::Logger.send("User #{dn} IS included in group: #{group_name}") 177 | end 178 | end 179 | 180 | unless in_group 181 | DeviseLdapAuthenticatable::Logger.send("User #{dn} is not in group: #{group_name}") 182 | end 183 | 184 | return in_group 185 | end 186 | 187 | def has_required_attribute? 188 | return true unless ::Devise.ldap_check_attributes 189 | 190 | admin_ldap = Connection.admin 191 | user = find_ldap_user(admin_ldap) 192 | 193 | @required_attributes.each do |key,val| 194 | matching_attributes = user[key] & Array(val) 195 | unless (matching_attributes).any? 196 | DeviseLdapAuthenticatable::Logger.send("User #{dn} did not match attribute #{key}:#{val}") 197 | return false 198 | end 199 | end 200 | 201 | return true 202 | end 203 | 204 | def has_required_attribute_presence? 205 | return true unless ::Devise.ldap_check_attributes_presence 206 | 207 | user = search_for_login 208 | 209 | @required_attributes_presence.each do |key,val| 210 | if val && !user.attribute_names.include?(key.to_sym) 211 | DeviseLdapAuthenticatable::Logger.send("User #{dn} doesn't include attribute #{key}") 212 | return false 213 | elsif !val && user.attribute_names.include?(key.to_sym) 214 | DeviseLdapAuthenticatable::Logger.send("User #{dn} includes attribute #{key}") 215 | return false 216 | end 217 | end 218 | 219 | return true 220 | end 221 | 222 | def user_groups 223 | admin_ldap = Connection.admin 224 | DeviseLdapAuthenticatable::Logger.send("Getting groups for #{dn}") 225 | filter = Net::LDAP::Filter.eq(@group_membership_attribute, dn) 226 | admin_ldap.search(:filter => filter, :base => @group_base).collect(&:dn) 227 | end 228 | 229 | def valid_login? 230 | !search_for_login.nil? 231 | end 232 | 233 | # Searches the LDAP for the login 234 | # 235 | # @return [Object] the LDAP entry found; nil if not found 236 | def search_for_login 237 | @login_ldap_entry ||= begin 238 | DeviseLdapAuthenticatable::Logger.send("LDAP search for login: #{@attribute}=#{@login}") 239 | filter = Net::LDAP::Filter.eq(@attribute.to_s, @login.to_s) 240 | ldap_entry = nil 241 | match_count = 0 242 | @ldap.search(:filter => filter) {|entry| ldap_entry = entry; match_count+=1} 243 | op_result= @ldap.get_operation_result 244 | if op_result.code!=0 then 245 | DeviseLdapAuthenticatable::Logger.send("LDAP Error #{op_result.code}: #{op_result.message}") 246 | end 247 | DeviseLdapAuthenticatable::Logger.send("LDAP search yielded #{match_count} matches") 248 | ldap_entry 249 | end 250 | end 251 | 252 | private 253 | 254 | def self.admin 255 | ldap = Connection.new(:admin => true).ldap 256 | 257 | unless ldap.bind 258 | DeviseLdapAuthenticatable::Logger.send("Cannot bind to admin LDAP user") 259 | raise DeviseLdapAuthenticatable::LdapException, "Cannot connect to admin LDAP user" 260 | end 261 | 262 | return ldap 263 | end 264 | 265 | def find_ldap_user(ldap) 266 | DeviseLdapAuthenticatable::Logger.send("Finding user: #{dn}") 267 | ldap.search(:base => dn, :scope => Net::LDAP::SearchScope_BaseObject).try(:first) 268 | end 269 | 270 | def update_ldap(ops) 271 | operations = [] 272 | if ops.is_a? Hash 273 | ops.each do |key,value| 274 | operations << [:replace,key,value] 275 | end 276 | elsif ops.is_a? Array 277 | operations = ops 278 | end 279 | 280 | if ::Devise.ldap_use_admin_to_bind 281 | privileged_ldap = Connection.admin 282 | else 283 | authenticate! 284 | privileged_ldap = self.ldap 285 | end 286 | 287 | DeviseLdapAuthenticatable::Logger.send("Modifying user #{dn}") 288 | privileged_ldap.modify(:dn => dn, :operations => operations) 289 | end 290 | end 291 | end 292 | end 293 | -------------------------------------------------------------------------------- /lib/devise_ldap_authenticatable/logger.rb: -------------------------------------------------------------------------------- 1 | module DeviseLdapAuthenticatable 2 | 3 | class Logger 4 | def self.send(message, logger = Rails.logger) 5 | if ::Devise.ldap_logger 6 | logger.add 0, " \e[36mLDAP:\e[0m #{message}" 7 | end 8 | end 9 | end 10 | 11 | end 12 | -------------------------------------------------------------------------------- /lib/devise_ldap_authenticatable/model.rb: -------------------------------------------------------------------------------- 1 | require 'devise_ldap_authenticatable/strategy' 2 | 3 | module Devise 4 | module Models 5 | # LDAP Module, responsible for validating the user credentials via LDAP. 6 | # 7 | # Examples: 8 | # 9 | # User.authenticate('email@test.com', 'password123') # returns authenticated user or nil 10 | # User.find(1).valid_password?('password123') # returns true/false 11 | # 12 | module LdapAuthenticatable 13 | extend ActiveSupport::Concern 14 | 15 | included do 16 | attr_reader :current_password, :password 17 | attr_accessor :password_confirmation 18 | end 19 | 20 | def login_with 21 | @login_with ||= Devise.mappings.find {|k,v| v.class_name == self.class.name}.last.to.authentication_keys.first 22 | self[@login_with] 23 | end 24 | 25 | def change_password!(current_password) 26 | raise "Need to set new password first" if @password.blank? 27 | 28 | Devise::LDAP::Adapter.update_own_password(login_with, @password, current_password) 29 | end 30 | 31 | def reset_password!(new_password, new_password_confirmation) 32 | if new_password == new_password_confirmation && ::Devise.ldap_update_password 33 | Devise::LDAP::Adapter.update_password(login_with, new_password) 34 | end 35 | clear_reset_password_token if valid? 36 | save 37 | end 38 | 39 | def password=(new_password) 40 | @password = new_password 41 | if defined?(password_digest) && @password.present? && respond_to?(:encrypted_password=) 42 | self.encrypted_password = password_digest(@password) 43 | end 44 | end 45 | 46 | # Checks if a resource is valid upon authentication. 47 | def valid_ldap_authentication?(password) 48 | Devise::LDAP::Adapter.valid_credentials?(login_with, password) 49 | end 50 | 51 | def ldap_entry 52 | @ldap_entry ||= Devise::LDAP::Adapter.get_ldap_entry(login_with) 53 | end 54 | 55 | def ldap_groups 56 | @ldap_groups ||= Devise::LDAP::Adapter.get_groups(login_with) 57 | end 58 | 59 | def in_ldap_group?(group_name, group_attribute = LDAP::DEFAULT_GROUP_UNIQUE_MEMBER_LIST_KEY) 60 | Devise::LDAP::Adapter.in_ldap_group?(login_with, group_name, group_attribute) 61 | end 62 | 63 | def ldap_dn 64 | ldap_entry ? ldap_entry.dn : nil 65 | end 66 | 67 | def ldap_get_param(param) 68 | if ldap_entry && !ldap_entry[param].empty? 69 | value = ldap_entry.send(param) 70 | else 71 | nil 72 | end 73 | end 74 | 75 | # 76 | # callbacks 77 | # 78 | 79 | # # Called before the ldap record is saved automatically 80 | # def ldap_before_save 81 | # end 82 | 83 | # Called after a successful LDAP authentication 84 | def after_ldap_authentication 85 | end 86 | 87 | 88 | module ClassMethods 89 | # Find a user for ldap authentication. 90 | def find_for_ldap_authentication(attributes={}) 91 | auth_key = self.authentication_keys.first 92 | return nil unless attributes[auth_key].present? 93 | 94 | auth_key_value = (self.case_insensitive_keys || []).include?(auth_key) ? attributes[auth_key].downcase : attributes[auth_key] 95 | auth_key_value = (self.strip_whitespace_keys || []).include?(auth_key) ? auth_key_value.strip : auth_key_value 96 | 97 | resource = where(auth_key => auth_key_value).first 98 | 99 | if resource.blank? 100 | resource = new 101 | resource[auth_key] = auth_key_value 102 | resource.password = attributes[:password] 103 | end 104 | 105 | if ::Devise.ldap_create_user && resource.new_record? && resource.valid_ldap_authentication?(attributes[:password]) 106 | resource.ldap_before_save if resource.respond_to?(:ldap_before_save) 107 | resource.save! 108 | end 109 | 110 | resource 111 | end 112 | 113 | def update_with_password(resource) 114 | puts "UPDATE_WITH_PASSWORD: #{resource.inspect}" 115 | end 116 | 117 | end 118 | end 119 | end 120 | end 121 | -------------------------------------------------------------------------------- /lib/devise_ldap_authenticatable/strategy.rb: -------------------------------------------------------------------------------- 1 | require 'devise/strategies/authenticatable' 2 | 3 | module Devise 4 | module Strategies 5 | class LdapAuthenticatable < Authenticatable 6 | 7 | # Tests whether the returned resource exists in the database and the 8 | # credentials are valid. If the resource is in the database and the credentials 9 | # are valid, the user is authenticated. Otherwise failure messages are returned 10 | # indicating whether the resource is not found in the database or the credentials 11 | # are invalid. 12 | def authenticate! 13 | resource = mapping.to.find_for_ldap_authentication(authentication_hash.merge(:password => password)) 14 | 15 | return fail(:invalid) unless resource 16 | 17 | if resource.persisted? 18 | if validate(resource) { resource.valid_ldap_authentication?(password) } 19 | remember_me(resource) 20 | resource.after_ldap_authentication 21 | success!(resource) 22 | else 23 | return fail(:invalid) # Invalid credentials 24 | end 25 | end 26 | 27 | if resource.new_record? 28 | if validate(resource) { resource.valid_ldap_authentication?(password) } 29 | return fail(:not_found_in_database) # Valid credentials 30 | else 31 | return fail(:invalid) # Invalid credentials 32 | end 33 | end 34 | end 35 | end 36 | end 37 | end 38 | 39 | Warden::Strategies.add(:ldap_authenticatable, Devise::Strategies::LdapAuthenticatable) 40 | -------------------------------------------------------------------------------- /lib/devise_ldap_authenticatable/version.rb: -------------------------------------------------------------------------------- 1 | module DeviseLdapAuthenticatable 2 | VERSION = "0.8.7".freeze 3 | end 4 | -------------------------------------------------------------------------------- /lib/generators/devise_ldap_authenticatable/install_generator.rb: -------------------------------------------------------------------------------- 1 | module DeviseLdapAuthenticatable 2 | class InstallGenerator < Rails::Generators::Base 3 | source_root File.expand_path("../templates", __FILE__) 4 | 5 | class_option :user_model, :type => :string, :default => "user", :desc => "Model to update" 6 | class_option :update_model, :type => :boolean, :default => true, :desc => "Update model to change from database_authenticatable to ldap_authenticatable" 7 | class_option :add_rescue, :type => :boolean, :default => true, :desc => "Update Application Controller with resuce_from for DeviseLdapAuthenticatable::LdapException" 8 | class_option :advanced, :type => :boolean, :desc => "Add advanced config options to the devise initializer" 9 | 10 | 11 | def create_ldap_config 12 | copy_file "ldap.yml", "config/ldap.yml" 13 | end 14 | 15 | def create_default_devise_settings 16 | inject_into_file "config/initializers/devise.rb", default_devise_settings, :after => "Devise.setup do |config|\n" 17 | end 18 | 19 | def update_user_model 20 | gsub_file "app/models/#{options.user_model}.rb", /:database_authenticatable/, ":ldap_authenticatable" if options.update_model? 21 | end 22 | 23 | def update_application_controller 24 | inject_into_class "app/controllers/application_controller.rb", ApplicationController, rescue_from_exception if options.add_rescue? 25 | end 26 | 27 | private 28 | 29 | def default_devise_settings 30 | settings = <<-eof 31 | # ==> LDAP Configuration 32 | # config.ldap_logger = true 33 | # config.ldap_create_user = false 34 | # config.ldap_update_password = true 35 | # config.ldap_config = "\#{Rails.root}/config/ldap.yml" 36 | # config.ldap_check_group_membership = false 37 | # config.ldap_check_group_membership_without_admin = false 38 | # config.ldap_check_attributes = false 39 | # config.ldap_check_attributes_presence = false 40 | # config.ldap_use_admin_to_bind = false 41 | # config.ldap_ad_group_check = false 42 | 43 | eof 44 | if options.advanced? 45 | settings << <<-eof 46 | # ==> Advanced LDAP Configuration 47 | # config.ldap_auth_username_builder = Proc.new() {|attribute, login, ldap| "\#{attribute}=\#{login},\#{ldap.base}" } 48 | 49 | eof 50 | end 51 | 52 | settings 53 | end 54 | 55 | def rescue_from_exception 56 | <<-eof 57 | rescue_from DeviseLdapAuthenticatable::LdapException do |exception| 58 | render :text => exception, :status => 500 59 | end 60 | eof 61 | end 62 | 63 | end 64 | end 65 | -------------------------------------------------------------------------------- /lib/generators/devise_ldap_authenticatable/templates/ldap.yml: -------------------------------------------------------------------------------- 1 | ## Authorizations 2 | # Uncomment out the merging for each environment that you'd like to include. 3 | # You can also just copy and paste the tree (do not include the "authorizations") to each 4 | # environment if you need something different per environment. 5 | authorizations: &AUTHORIZATIONS 6 | allow_unauthenticated_bind: false 7 | group_base: ou=groups,dc=test,dc=com 8 | ## Requires config.ldap_check_group_membership in devise.rb be true 9 | # Can have multiple values, must match all to be authorized 10 | required_groups: 11 | # If only a group name is given, membership will be checked against "uniqueMember" 12 | - cn=admins,ou=groups,dc=test,dc=com 13 | - cn=users,ou=groups,dc=test,dc=com 14 | # If an array is given, the first element will be the attribute to check against, the second the group name 15 | - ["moreMembers", "cn=users,ou=groups,dc=test,dc=com"] 16 | ## Requires config.ldap_check_attributes in devise.rb to be true 17 | ## Can have multiple attributes and values, must match all to be authorized 18 | require_attribute: 19 | objectClass: inetOrgPerson 20 | authorizationRole: postsAdmin 21 | ## Requires config.ldap_check_attributes_presence in devise.rb to be true 22 | ## Can have multiple attributes set to true or false to check presence, all must match all to be authorized 23 | require_attribute_presence: 24 | mail: true 25 | telephoneNumber: true 26 | serviceAccount: false 27 | 28 | ## Environment 29 | 30 | development: 31 | host: localhost 32 | port: 389 33 | attribute: cn 34 | base: ou=people,dc=test,dc=com 35 | admin_user: cn=admin,dc=test,dc=com 36 | admin_password: admin_password 37 | ssl: false 38 | # <<: *AUTHORIZATIONS 39 | 40 | test: 41 | host: localhost 42 | port: 3389 43 | attribute: cn 44 | base: ou=people,dc=test,dc=com 45 | admin_user: cn=admin,dc=test,dc=com 46 | admin_password: admin_password 47 | ssl: simple_tls 48 | # <<: *AUTHORIZATIONS 49 | 50 | production: 51 | host: localhost 52 | port: 636 53 | attribute: cn 54 | base: ou=people,dc=test,dc=com 55 | admin_user: cn=admin,dc=test,dc=com 56 | admin_password: admin_password 57 | ssl: start_tls 58 | # <<: *AUTHORIZATIONS 59 | -------------------------------------------------------------------------------- /spec/ldap/.gitignore: -------------------------------------------------------------------------------- 1 | slapd-test.conf 2 | slapd-ssl-test.conf 3 | -------------------------------------------------------------------------------- /spec/ldap/base.ldif: -------------------------------------------------------------------------------- 1 | # ldapadd -x -h localhost -p 3389 -D "cn=admin,dc=test,dc=com" -w secret -f base.ldif 2 | 3 | dn: dc=test,dc=com 4 | objectClass: dcObject 5 | objectClass: organizationalUnit 6 | dc: test 7 | ou: Test 8 | 9 | dn: ou=people,dc=test,dc=com 10 | objectClass: organizationalUnit 11 | ou: people 12 | 13 | dn: ou=others,dc=test,dc=com 14 | objectClass: organizationalUnit 15 | ou: others 16 | 17 | dn: ou=groups,dc=test,dc=com 18 | objectClass: organizationalUnit 19 | ou: groups 20 | 21 | # example.user@test.com, people, test.com 22 | dn: cn=example.user@test.com,ou=people,dc=test,dc=com 23 | objectClass: inetOrgPerson 24 | objectClass: authorizations 25 | sn: User 26 | uid: example_user 27 | mail: example.user@test.com 28 | cn: example.user@test.com 29 | authorizationRole: blogUser 30 | userPassword:: e1NTSEF9ZXRYaE9NcjRjOGFiTjlqYUxyczZKSll5MFlaZUF1NURCVWhhY0E9PQ= 31 | = 32 | 33 | # other.user@test.com 34 | dn: cn=other.user@test.com,ou=others,dc=test,dc=com 35 | objectClass: inetOrgPerson 36 | objectClass: authorizations 37 | objectClass: organizationalPerson 38 | objectClass: person 39 | objectClass: top 40 | sn: Other 41 | uid: other_user 42 | cn: other.user@test.com 43 | authorizationRole: blogUser 44 | userPassword:: e1NIQX1IQXdtdk13RGF1ZUpyZDhwakxXMzZ6Yi9jTUU9 45 | 46 | # example.admin@test.com, people, test.com 47 | dn: cn=example.admin@test.com,ou=people,dc=test,dc=com 48 | objectClass: inetOrgPerson 49 | objectClass: authorizations 50 | objectClass: organizationalPerson 51 | objectClass: person 52 | objectClass: top 53 | sn: Admin 54 | uid: example_admin 55 | cn: example.admin@test.com 56 | authorizationRole: blogAdmin 57 | userPassword:: e1NIQX0wcUNXaERISGFwWmc3ekJxZWRRanBzNW1EUDA9 58 | 59 | # users, groups, test.com 60 | dn: cn=users,ou=groups,dc=test,dc=com 61 | objectClass: authorizations 62 | objectClass: groupOfUniqueNames 63 | objectClass: top 64 | uniqueMember: cn=example.user@test.com,ou=people,dc=test,dc=com 65 | authorizationRole: cn=example.admin@test.com,ou=people,dc=test,dc=com 66 | cn: users 67 | 68 | # users, groups, test.com 69 | dn: cn=admins,ou=groups,dc=test,dc=com 70 | objectClass: groupOfUniqueNames 71 | objectClass: top 72 | uniqueMember: cn=example.admin@test.com,ou=people,dc=test,dc=com 73 | cn: admins -------------------------------------------------------------------------------- /spec/ldap/clear.ldif: -------------------------------------------------------------------------------- 1 | dn: cn=admins,ou=groups,dc=test,dc=com 2 | changetype: delete 3 | 4 | dn: cn=users,ou=groups,dc=test,dc=com 5 | changetype: delete 6 | 7 | dn: cn=example.admin@test.com,ou=people,dc=test,dc=com 8 | changetype: delete 9 | 10 | dn: cn=example.user@test.com,ou=people,dc=test,dc=com 11 | changetype: delete 12 | 13 | dn: cn=other.user@test.com,ou=others,dc=test,dc=com 14 | changetype: delete 15 | 16 | dn: ou=groups,dc=test,dc=com 17 | changetype: delete 18 | 19 | dn: ou=people,dc=test,dc=com 20 | changetype: delete 21 | 22 | dn: ou=others,dc=test,dc=com 23 | changetype: delete 24 | 25 | dn: dc=test,dc=com 26 | changetype: delete 27 | -------------------------------------------------------------------------------- /spec/ldap/local.schema: -------------------------------------------------------------------------------- 1 | attributetype ( 1.1.2.2.5 NAME 'authorizationRole' SUP name ) 2 | 3 | objectclass ( 1.1.2.2.1 NAME 'authorizations' 4 | DESC 'mixin authorizations' 5 | AUXILIARY 6 | MAY authorizationRole ) -------------------------------------------------------------------------------- /spec/ldap/openldap-data/.gitignore: -------------------------------------------------------------------------------- 1 | dc=test,dc=com 2 | dc=test,dc=com.ldif 3 | -------------------------------------------------------------------------------- /spec/ldap/openldap-data/run/.gitignore: -------------------------------------------------------------------------------- 1 | slapd.pid 2 | slapd.args 3 | -------------------------------------------------------------------------------- /spec/ldap/openldap-data/run/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cschiewek/devise_ldap_authenticatable/6ef2131e79ff3421429f8d1b0645c6e113db4dc7/spec/ldap/openldap-data/run/.gitkeep -------------------------------------------------------------------------------- /spec/ldap/run-server: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | require 'erb' 4 | require 'fileutils' 5 | 6 | FileUtils.chdir(File.dirname(__FILE__)) 7 | 8 | ## For OSX: 9 | ENV['PATH'] = "#{ENV['PATH']}:/usr/libexec" 10 | 11 | template = File.read('slapd-test.conf.erb') 12 | normal_out = 'slapd-test.conf' 13 | ssl_out = 'slapd-ssl-test.conf' 14 | 15 | File.open(normal_out, 'w') do |f| 16 | @ssl = false 17 | f.write ERB.new(template).result(binding) 18 | end 19 | File.open(ssl_out, 'w') do |f| 20 | @ssl = true 21 | f.write ERB.new(template).result(binding) 22 | end 23 | 24 | if ARGV.first == '--ssl' 25 | cmd = "slapd -d 1 -f #{ssl_out} -h ldaps://localhost:3389" 26 | else 27 | cmd = "slapd -d 1 -f #{normal_out} -h ldap://localhost:3389" 28 | end 29 | 30 | puts(cmd) 31 | exec(cmd) 32 | -------------------------------------------------------------------------------- /spec/ldap/server.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | MIICXQIBAAKBgQC/hxFetCTh++3sEwchxuscH5TID0Wj2S/heBjY6RuK5rPrAcUg 3 | rA7jFEFilEQYpfGe3LIMBkr5pP4aR1NrLuvKZaHuBvRLwOcU7SbuFQ3FQLaJA3UK 4 | E2IOH9wMg1BMcG1WbzB1nKc650omKo7KqOAIYFFVq3gzlDRUmHF6dCAnvwIDAQAB 5 | AoGAcOBJfGbu1cCEF/2e1mlFZu214bIeeNInRdphynSXpuUQZBBG/Vpp66qkXlTD 6 | TUN/gwDObgfHaBm1KAehQioFC9ys1Iymlt8IeRYXH9Tkl7URe30QGAGjdIPohWpZ 7 | xl/aMrpQVvQukaStRNoJXA32j+tuR2KbxAK6bu9iLzXvCQECQQD6AOzHVDB06ZjF 8 | iJYB1/CyZBg0Q2aIOwGXwle1t1O7q6nJ6UWkurQF/inBdJdE5SWNEzYsI1tEP0n2 9 | 1ZBIWQxtAkEAxB8WgFjRqYdmUYGQ1k8yxMUTLbZFd6t2UZyB/LAw9CtjH9lrU0z9 10 | 81UK/ywVHkoDDPHbFyvd1jludqbz+suRWwJBAPEL9UCXfwUquf8zm5b5cv09n0y8 11 | 895ELlv5qQHvWg+oC1Q/08NptOvWTMJXPQbTfepQ7LmP+Y6LCzCwZ6YqHd0CQFiW 12 | flB9Tj9YhNQ+RVE4twMAzhfw5FIY5joZCvI8F/DDBGRnjj4zYeafPHdkzyk+X0Bi 13 | owdFblAM4yO/aCeZ+k8CQQDdBi+WnpaaSL0NXmAb6+7aQRZ/Gc2O9S2JL/Fxw4EQ 14 | i7KTRdH/d6Db9SeQEc/uCbJW7fM4KbZcjFdncHFytakt 15 | -----END RSA PRIVATE KEY----- 16 | -----BEGIN CERTIFICATE----- 17 | MIIDwjCCAyugAwIBAgIJAP+plC/uCHKkMA0GCSqGSIb3DQEBBQUAMIGdMQswCQYD 18 | VQQGEwJVUzERMA8GA1UECBMIVmlyZ2luaWExEzARBgNVBAcTCkFsZXhhbmRyaWEx 19 | DTALBgNVBAoTBFRlc3QxDTALBgNVBAsTBFRlc3QxJDAiBgNVBAMUG2RldmlzZV9s 20 | ZGFwX2F1dGhlbnRpY2F0YWJsZTEiMCAGCSqGSIb3DQEJARYTZHBtY25ldmluQGdt 21 | YWlsLmNvbTAeFw0xMDA4MDUyMTU1MDVaFw0xMTA4MDUyMTU1MDVaMIGdMQswCQYD 22 | VQQGEwJVUzERMA8GA1UECBMIVmlyZ2luaWExEzARBgNVBAcTCkFsZXhhbmRyaWEx 23 | DTALBgNVBAoTBFRlc3QxDTALBgNVBAsTBFRlc3QxJDAiBgNVBAMUG2RldmlzZV9s 24 | ZGFwX2F1dGhlbnRpY2F0YWJsZTEiMCAGCSqGSIb3DQEJARYTZHBtY25ldmluQGdt 25 | YWlsLmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAv4cRXrQk4fvt7BMH 26 | IcbrHB+UyA9Fo9kv4XgY2Okbiuaz6wHFIKwO4xRBYpREGKXxntyyDAZK+aT+GkdT 27 | ay7rymWh7gb0S8DnFO0m7hUNxUC2iQN1ChNiDh/cDINQTHBtVm8wdZynOudKJiqO 28 | yqjgCGBRVat4M5Q0VJhxenQgJ78CAwEAAaOCAQYwggECMB0GA1UdDgQWBBRcCNxq 29 | 0PNXgMfYN2RQ2uIrBY03ADCB0gYDVR0jBIHKMIHHgBRcCNxq0PNXgMfYN2RQ2uIr 30 | BY03AKGBo6SBoDCBnTELMAkGA1UEBhMCVVMxETAPBgNVBAgTCFZpcmdpbmlhMRMw 31 | EQYDVQQHEwpBbGV4YW5kcmlhMQ0wCwYDVQQKEwRUZXN0MQ0wCwYDVQQLEwRUZXN0 32 | MSQwIgYDVQQDFBtkZXZpc2VfbGRhcF9hdXRoZW50aWNhdGFibGUxIjAgBgkqhkiG 33 | 9w0BCQEWE2RwbWNuZXZpbkBnbWFpbC5jb22CCQD/qZQv7ghypDAMBgNVHRMEBTAD 34 | AQH/MA0GCSqGSIb3DQEBBQUAA4GBABjztpAgr6QxVCNxhgklrILH+RLxww3dgdra 35 | J6C6pXl9lbM+XIWiUtzD3Y8z2+tkJtjWCCN7peM2OYFvdChIvRz8XoxHqNB9W8wj 36 | xZOqBHN8MdI1g6PCD5Z8lK1TDvchTeskqCulE6tMHKaslByhfZS94uWY+NG5JY/Z 37 | traWmtWh 38 | -----END CERTIFICATE----- 39 | -------------------------------------------------------------------------------- /spec/ldap/slapd-test.conf.erb: -------------------------------------------------------------------------------- 1 | # 2 | # See slapd.conf(5) for details on configuration options. 3 | # This file should NOT be world readable. 4 | # 5 | <% ldapdir = RUBY_PLATFORM.match(/linux/) ? 'ldap' : 'openldap' %> 6 | include /etc/<%= ldapdir %>/schema/core.schema 7 | include /etc/<%= ldapdir %>/schema/cosine.schema 8 | include /etc/<%= ldapdir %>/schema/inetorgperson.schema 9 | include /etc/<%= ldapdir %>/schema/nis.schema 10 | 11 | ## Local definitions 12 | # include /etc/<%= ldapdir %>/schema/local.schema 13 | include <%= File.expand_path('local.schema', @conf_root) %> 14 | 15 | # Allow LDAPv2 client connections. This is NOT the default. 16 | allow bind_v2 17 | 18 | # Do not enable referrals until AFTER you have a working directory 19 | # service AND an understanding of referrals. 20 | #referral ldap://root.openldap.org 21 | 22 | pidfile <%= File.expand_path('openldap-data/run/slapd.pid', @conf_root) %> 23 | argsfile <%= File.expand_path('openldap-data/run/slapd.args', @conf_root) %> 24 | 25 | # Load dynamic backend modules: 26 | modulepath /usr/lib/openldap 27 | 28 | # modules available in openldap-servers-overlays RPM package: 29 | # moduleload accesslog.la 30 | # moduleload auditlog.la 31 | # moduleload denyop.la 32 | # moduleload dyngroup.la 33 | # moduleload dynlist.la 34 | # moduleload lastmod.la 35 | # moduleload pcache.la 36 | # moduleload ppolicy.la 37 | # moduleload refint.la 38 | # moduleload retcode.la 39 | # moduleload rwm.la 40 | # moduleload smbk5pwd.la 41 | # moduleload syncprov.la 42 | # moduleload translucent.la 43 | # moduleload unique.la 44 | # moduleload valsort.la 45 | 46 | # modules available in openldap-servers-sql RPM package: 47 | # moduleload back_sql.la 48 | 49 | # The next three lines allow use of TLS for encrypting connections using a 50 | # dummy test certificate which you can generate by changing to 51 | # /etc/pki/tls/certs, running "make slapd.pem", and fixing permissions on 52 | # slapd.pem so that the ldap user or group can read it. Your client software 53 | # may balk at self-signed certificates, however. 54 | 55 | # ## For LDAPS 56 | <% if @ssl %> 57 | TLSCACertificateFile <%= File.expand_path('server.pem', @conf_root) %> 58 | TLSCertificateFile <%= File.expand_path('server.pem', @conf_root) %> 59 | TLSCertificateKeyFile <%= File.expand_path('server.pem', @conf_root) %> 60 | <% else %> 61 | # TLSCACertificateFile server.pem 62 | # TLSCertificateFile server.pem 63 | # TLSCertificateKeyFile server.pem 64 | <% end %> 65 | # 66 | # TLSVerifyClient demand 67 | 68 | # Sample security restrictions 69 | # Require integrity protection (prevent hijacking) 70 | # Require 112-bit (3DES or better) encryption for updates 71 | # Require 63-bit encryption for simple bind 72 | # security ssf=1 update_ssf=112 simple_bind=64 73 | 74 | # Sample access control policy: 75 | # Root DSE: allow anyone to read it 76 | # Subschema (sub)entry DSE: allow anyone to read it 77 | # Other DSEs: 78 | # Allow self write access 79 | # Allow authenticated users read access 80 | # Allow anonymous users to authenticate 81 | # Directives needed to implement policy: 82 | 83 | # access to dn.base="dc=esc" by * read 84 | # access to dn.base="cn=Subschema" by * read 85 | access to * 86 | by self write 87 | by * read 88 | by anonymous auth 89 | 90 | # 91 | # if no access controls are present, the default policy 92 | # allows anyone and everyone to read anything but restricts 93 | # updates to rootdn. (e.g., "access to * by * read") 94 | # 95 | # rootdn can always read and write EVERYTHING! 96 | 97 | ####################################################################### 98 | # ldbm and/or bdb database definitions 99 | ####################################################################### 100 | 101 | database ldif 102 | 103 | suffix "dc=test,dc=com" 104 | directory openldap-data 105 | rootdn "cn=admin,dc=test,dc=com" 106 | ## rootpw = secret 107 | rootpw {SSHA}fFjKcZb4cfOAcwSjJer8nCGOEVRUnwCC 108 | -------------------------------------------------------------------------------- /spec/rails_app/Rakefile: -------------------------------------------------------------------------------- 1 | # Add your own tasks in files placed in lib/tasks ending in .rake, 2 | # for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. 3 | 4 | require File.expand_path('../config/application', __FILE__) 5 | require 'rake' 6 | 7 | RailsApp::Application.load_tasks 8 | -------------------------------------------------------------------------------- /spec/rails_app/app/controllers/application_controller.rb: -------------------------------------------------------------------------------- 1 | class ApplicationController < ActionController::Base 2 | rescue_from DeviseLdapAuthenticatable::LdapException do |exception| 3 | render :text => exception, :status => 500 4 | end 5 | protect_from_forgery 6 | layout 'application' 7 | end 8 | -------------------------------------------------------------------------------- /spec/rails_app/app/controllers/posts_controller.rb: -------------------------------------------------------------------------------- 1 | class PostsController < ApplicationController 2 | 3 | before_filter :authenticate_user!, :except => [:index] 4 | 5 | def index 6 | # render :inline => "posts#index", :layout => "application" 7 | render :text => "posts#index" 8 | end 9 | 10 | def new 11 | # render :inline => "posts#new", :layout => "application" 12 | render :text => "posts#new" 13 | end 14 | 15 | end 16 | -------------------------------------------------------------------------------- /spec/rails_app/app/helpers/application_helper.rb: -------------------------------------------------------------------------------- 1 | module ApplicationHelper 2 | end 3 | -------------------------------------------------------------------------------- /spec/rails_app/app/helpers/posts_helper.rb: -------------------------------------------------------------------------------- 1 | module PostsHelper 2 | end 3 | -------------------------------------------------------------------------------- /spec/rails_app/app/models/post.rb: -------------------------------------------------------------------------------- 1 | class Post < ActiveRecord::Base 2 | end 3 | -------------------------------------------------------------------------------- /spec/rails_app/app/models/user.rb: -------------------------------------------------------------------------------- 1 | class User < ActiveRecord::Base 2 | 3 | # Include default devise modules. Others available are: 4 | # :token_authenticatable, :confirmable, :lockable and :timeoutable 5 | devise :ldap_authenticatable, :registerable, 6 | :recoverable, :rememberable, :trackable# , :validatable 7 | end -------------------------------------------------------------------------------- /spec/rails_app/app/views/layouts/application.html.erb: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | RailsApp 5 | <%= stylesheet_link_tag :all %> 6 | <%= javascript_include_tag :defaults %> 7 | <%= csrf_meta_tag %> 8 | 9 | 10 | 11 | <% if user_signed_in? %> 12 | <%= link_to "sign out", destroy_user_session_path %> 13 | <% else %> 14 | <%= link_to "sign in", new_user_session_path %> 15 | <% end %> 16 | 17 |

18 | 19 | <% flash.each do |name, message| %> 20 |

<%= message %>

21 | <% end %> 22 | 23 | <%= yield %> 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /spec/rails_app/app/views/posts/index.html.erb: -------------------------------------------------------------------------------- 1 |

Posts#index

2 |

Find me in app/views/posts/index.html.erb

3 | -------------------------------------------------------------------------------- /spec/rails_app/config.ru: -------------------------------------------------------------------------------- 1 | # This file is used by Rack-based servers to start the application. 2 | 3 | require ::File.expand_path('../config/environment', __FILE__) 4 | run RailsApp::Application 5 | -------------------------------------------------------------------------------- /spec/rails_app/config/application.rb: -------------------------------------------------------------------------------- 1 | require File.expand_path('../boot', __FILE__) 2 | 3 | require 'rails/all' 4 | 5 | # If you have a Gemfile, require the gems listed there, including any gems 6 | # you've limited to :test, :development, or :production. 7 | Bundler.require(:default, Rails.env) if defined?(Bundler) 8 | 9 | module RailsApp 10 | class Application < Rails::Application 11 | # Settings in config/environments/* take precedence over those specified here. 12 | # Application configuration should go into files in config/initializers 13 | # -- all .rb files in that directory are automatically loaded. 14 | 15 | # Add additional load paths for your own custom dirs 16 | # config.load_paths += %W( #{config.root}/extras ) 17 | 18 | # Only load the plugins named here, in the order given (default is alphabetical). 19 | # :all can be used as a placeholder for all plugins not explicitly named 20 | # config.plugins = [ :exception_notification, :ssl_requirement, :all ] 21 | 22 | # Activate observers that should always be running 23 | # config.active_record.observers = :cacher, :garbage_collector, :forum_observer 24 | 25 | # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. 26 | # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. 27 | # config.time_zone = 'Central Time (US & Canada)' 28 | 29 | # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. 30 | # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] 31 | # config.i18n.default_locale = :de 32 | 33 | # Configure generators values. Many other options are available, be sure to check the documentation. 34 | # config.generators do |g| 35 | # g.orm :active_record 36 | # g.template_engine :erb 37 | # g.test_framework :test_unit, :fixture => true 38 | # end 39 | 40 | # Configure the default encoding used in templates for Ruby 1.9. 41 | config.encoding = "utf-8" 42 | 43 | # Configure sensitive parameters which will be filtered from the log file. 44 | config.filter_parameters += [:password] 45 | end 46 | end 47 | -------------------------------------------------------------------------------- /spec/rails_app/config/boot.rb: -------------------------------------------------------------------------------- 1 | require 'rubygems' 2 | 3 | # Set up gems listed in the Gemfile. 4 | gemfile = File.expand_path('../../../../Gemfile', __FILE__) 5 | begin 6 | ENV['BUNDLE_GEMFILE'] = gemfile 7 | require 'bundler' 8 | Bundler.setup 9 | rescue Bundler::GemNotFound => e 10 | STDERR.puts e.message 11 | STDERR.puts "Try running `bundle install`." 12 | exit! 13 | end if File.exist?(gemfile) 14 | -------------------------------------------------------------------------------- /spec/rails_app/config/cucumber.yml: -------------------------------------------------------------------------------- 1 | <% 2 | rerun = File.file?('rerun.txt') ? IO.read('rerun.txt') : "" 3 | rerun_opts = rerun.to_s.strip.empty? ? "--format #{ENV['CUCUMBER_FORMAT'] || 'progress'} features" : "--format #{ENV['CUCUMBER_FORMAT'] || 'pretty'} #{rerun}" 4 | std_opts = "--format #{ENV['CUCUMBER_FORMAT'] || 'progress'} --strict --tags ~@wip" 5 | %> 6 | default: <%= std_opts %> features 7 | wip: --tags @wip:3 --wip features 8 | rerun: <%= rerun_opts %> --format rerun --out rerun.txt --strict --tags ~@wip 9 | -------------------------------------------------------------------------------- /spec/rails_app/config/database.yml: -------------------------------------------------------------------------------- 1 | # SQLite version 3.x 2 | # gem install sqlite3-ruby (not necessary on OS X Leopard) 3 | development: 4 | adapter: sqlite3 5 | database: db/development.sqlite3 6 | pool: 5 7 | timeout: 5000 8 | 9 | # Warning: The database defined as "test" will be erased and 10 | # re-generated from your development database when you run "rake". 11 | # Do not set this db to the same as development or production. 12 | test: &test 13 | adapter: sqlite3 14 | database: db/test.sqlite3 15 | pool: 5 16 | timeout: 5000 17 | 18 | production: 19 | adapter: sqlite3 20 | database: db/production.sqlite3 21 | pool: 5 22 | timeout: 5000 23 | 24 | cucumber: 25 | <<: *test -------------------------------------------------------------------------------- /spec/rails_app/config/environment.rb: -------------------------------------------------------------------------------- 1 | # Load the rails application 2 | require File.expand_path('../application', __FILE__) 3 | 4 | # Initialize the rails application 5 | RailsApp::Application.initialize! 6 | -------------------------------------------------------------------------------- /spec/rails_app/config/environments/development.rb: -------------------------------------------------------------------------------- 1 | RailsApp::Application.configure do 2 | # Settings specified here will take precedence over those in config/environment.rb 3 | 4 | # In the development environment your application's code is reloaded on 5 | # every request. This slows down response time but is perfect for development 6 | # since you don't have to restart the webserver when you make code changes. 7 | config.cache_classes = false 8 | 9 | # Do not eager load code on boot. 10 | config.eager_load = false 11 | 12 | # Show full error reports and disable caching 13 | config.consider_all_requests_local = true 14 | config.action_controller.perform_caching = false 15 | 16 | # Don't care if the mailer can't send 17 | config.action_mailer.raise_delivery_errors = false 18 | config.active_support.deprecation = :log 19 | 20 | config.action_mailer.default_url_options = { :host => 'localhost:3000' } 21 | end 22 | -------------------------------------------------------------------------------- /spec/rails_app/config/environments/production.rb: -------------------------------------------------------------------------------- 1 | RailsApp::Application.configure do 2 | # Settings specified here will take precedence over those in config/environment.rb 3 | 4 | # The production environment is meant for finished, "live" apps. 5 | # Code is not reloaded between requests 6 | config.cache_classes = true 7 | 8 | # Full error reports are disabled and caching is turned on 9 | config.consider_all_requests_local = false 10 | config.action_controller.perform_caching = true 11 | 12 | # Specifies the header that your server uses for sending files 13 | config.action_dispatch.x_sendfile_header = "X-Sendfile" 14 | 15 | # For nginx: 16 | # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' 17 | 18 | # If you have no front-end server that supports something like X-Sendfile, 19 | # just comment this out and Rails will serve the files 20 | 21 | # See everything in the log (default is :info) 22 | # config.log_level = :debug 23 | 24 | # Use a different logger for distributed setups 25 | # config.logger = SyslogLogger.new 26 | 27 | # Use a different cache store in production 28 | # config.cache_store = :mem_cache_store 29 | 30 | # Disable Rails's static asset server 31 | # In production, Apache or nginx will already do this 32 | config.serve_static_assets = false 33 | 34 | # Enable serving of images, stylesheets, and javascripts from an asset server 35 | # config.action_controller.asset_host = "http://assets.example.com" 36 | 37 | # Disable delivery errors, bad email addresses will be ignored 38 | # config.action_mailer.raise_delivery_errors = false 39 | 40 | # Enable threaded mode 41 | # config.threadsafe! 42 | 43 | # Enable locale fallbacks for I18n (makes lookups for any locale fall back to 44 | # the I18n.default_locale when a translation can not be found) 45 | config.i18n.fallbacks = true 46 | end 47 | -------------------------------------------------------------------------------- /spec/rails_app/config/environments/test.rb: -------------------------------------------------------------------------------- 1 | RailsApp::Application.configure do 2 | # Settings specified here will take precedence over those in config/environment.rb 3 | 4 | # The test environment is used exclusively to run your application's 5 | # test suite. You never need to work with it otherwise. Remember that 6 | # your test database is "scratch space" for the test suite and is wiped 7 | # and recreated between test runs. Don't rely on the data there! 8 | config.cache_classes = true 9 | 10 | # Do not eager load code on boot. 11 | config.eager_load = false 12 | 13 | # Show full error reports and disable caching 14 | config.consider_all_requests_local = true 15 | config.action_controller.perform_caching = false 16 | 17 | # Raise exceptions instead of rendering exception templates 18 | config.action_dispatch.show_exceptions = false 19 | 20 | # Disable request forgery protection in test environment 21 | config.action_controller.allow_forgery_protection = false 22 | 23 | # Tell Action Mailer not to deliver emails to the real world. 24 | # The :test delivery method accumulates sent emails in the 25 | # ActionMailer::Base.deliveries array. 26 | config.action_mailer.delivery_method = :test 27 | 28 | config.active_support.deprecation = :stderr 29 | 30 | # Use SQL instead of Active Record's schema dumper when creating the test database. 31 | # This is necessary if your schema can't be completely dumped by the schema dumper, 32 | # like if you have constraints or database-specific column types 33 | # config.active_record.schema_format = :sql 34 | end 35 | -------------------------------------------------------------------------------- /spec/rails_app/config/initializers/backtrace_silencers.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. 4 | # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } 5 | 6 | # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. 7 | # Rails.backtrace_cleaner.remove_silencers! 8 | -------------------------------------------------------------------------------- /spec/rails_app/config/initializers/devise.rb: -------------------------------------------------------------------------------- 1 | # Use this hook to configure devise mailer, warden hooks and so forth. 2 | # Many of these configuration options can be set straight in your model. 3 | Devise.setup do |config| 4 | # ==> LDAP Configuration 5 | # config.ldap_logger = true 6 | # config.ldap_create_user = false 7 | # config.ldap_update_password = true 8 | # config.ldap_config = "#{Rails.root}/config/ldap.yml" 9 | # config.ldap_check_group_membership = false 10 | # config.ldap_check_attributes = false 11 | # config.ldap_use_admin_to_bind = false 12 | # config.ldap_ad_group_check = false 13 | 14 | # ==> Mailer Configuration 15 | # Configure the e-mail address which will be shown in Devise::Mailer, 16 | # note that it will be overwritten if you use your own mailer class with default "from" parameter. 17 | config.mailer_sender = "please-change-me-at-config-initializers-devise@example.com" 18 | 19 | 20 | if ::Devise.respond_to?(:secret_key) 21 | ::Devise.secret_key = '012a16191a7f61e84e55704e34b73db991a23ba396b6b7760596a3e80073e4464c55421c42a1a34327dee44828bec6745c48eba10cc0866799ec95c09ea27ada' 22 | end 23 | 24 | # Configure the class responsible to send e-mails. 25 | # config.mailer = "Devise::Mailer" 26 | 27 | # ==> ORM configuration 28 | # Load and configure the ORM. Supports :active_record (default) and 29 | # :mongoid (bson_ext recommended) by default. Other ORMs may be 30 | # available as additional gems. 31 | require 'devise/orm/active_record' 32 | 33 | # ==> Configuration for any authentication mechanism 34 | # Configure which keys are used when authenticating a user. The default is 35 | # just :email. You can configure it to use [:username, :subdomain], so for 36 | # authenticating a user, both parameters are required. Remember that those 37 | # parameters are used only when authenticating and not when retrieving from 38 | # session. If you need permissions, you should implement that in a before filter. 39 | # You can also supply a hash where the value is a boolean determining whether 40 | # or not authentication should be aborted when the value is not present. 41 | # config.authentication_keys = [ :email ] 42 | 43 | # Configure parameters from the request object used for authentication. Each entry 44 | # given should be a request method and it will automatically be passed to the 45 | # find_for_authentication method and considered in your model lookup. For instance, 46 | # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. 47 | # The same considerations mentioned for authentication_keys also apply to request_keys. 48 | # config.request_keys = [] 49 | 50 | # Configure which authentication keys should be case-insensitive. 51 | # These keys will be downcased upon creating or modifying a user and when used 52 | # to authenticate or find a user. Default is :email. 53 | config.case_insensitive_keys = [ :email ] 54 | 55 | # Configure which authentication keys should have whitespace stripped. 56 | # These keys will have whitespace before and after removed upon creating or 57 | # modifying a user and when used to authenticate or find a user. Default is :email. 58 | config.strip_whitespace_keys = [ :email ] 59 | 60 | # Tell if authentication through request.params is enabled. True by default. 61 | # It can be set to an array that will enable params authentication only for the 62 | # given strategies, for example, `config.params_authenticatable = [:database]` will 63 | # enable it only for database (email + password) authentication. 64 | # config.params_authenticatable = true 65 | 66 | # Tell if authentication through HTTP Basic Auth is enabled. False by default. 67 | # It can be set to an array that will enable http authentication only for the 68 | # given strategies, for example, `config.http_authenticatable = [:token]` will 69 | # enable it only for token authentication. 70 | # config.http_authenticatable = false 71 | 72 | # If http headers should be returned for AJAX requests. True by default. 73 | # config.http_authenticatable_on_xhr = true 74 | 75 | # The realm used in Http Basic Authentication. "Application" by default. 76 | # config.http_authentication_realm = "Application" 77 | 78 | # It will change confirmation, password recovery and other workflows 79 | # to behave the same regardless if the e-mail provided was right or wrong. 80 | # Does not affect registerable. 81 | # config.paranoid = true 82 | 83 | # By default Devise will store the user in session. You can skip storage for 84 | # :http_auth and :token_auth by adding those symbols to the array below. 85 | # Notice that if you are skipping storage for all authentication paths, you 86 | # may want to disable generating routes to Devise's sessions controller by 87 | # passing :skip => :sessions to `devise_for` in your config/routes.rb 88 | config.skip_session_storage = [:http_auth] 89 | 90 | # ==> Configuration for :database_authenticatable 91 | # For bcrypt, this is the cost for hashing the password and defaults to 10. If 92 | # using other encryptors, it sets how many times you want the password re-encrypted. 93 | # 94 | # Limiting the stretches to just one in testing will increase the performance of 95 | # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use 96 | # a value less than 10 in other environments. 97 | config.stretches = Rails.env.test? ? 1 : 10 98 | 99 | # Setup a pepper to generate the encrypted password. 100 | # config.pepper = "589f0e9c372367e7176cf1617494a99b3f26c2dd2a3ca617b2aa9fe7d9a9066b6a04489f985f2e15f3a3f32f770f36d0a0c3d42ea846562d0bb0f99662c0add1" 101 | 102 | # ==> Configuration for :confirmable 103 | # A period that the user is allowed to access the website even without 104 | # confirming his account. For instance, if set to 2.days, the user will be 105 | # able to access the website for two days without confirming his account, 106 | # access will be blocked just in the third day. Default is 0.days, meaning 107 | # the user cannot access the website without confirming his account. 108 | # config.allow_unconfirmed_access_for = 2.days 109 | 110 | # If true, requires any email changes to be confirmed (exactly the same way as 111 | # initial account confirmation) to be applied. Requires additional unconfirmed_email 112 | # db field (see migrations). Until confirmed new email is stored in 113 | # unconfirmed email column, and copied to email column on successful confirmation. 114 | config.reconfirmable = true 115 | 116 | # Defines which key will be used when confirming an account 117 | # config.confirmation_keys = [ :email ] 118 | 119 | # ==> Configuration for :rememberable 120 | # The time the user will be remembered without asking for credentials again. 121 | # config.remember_for = 2.weeks 122 | 123 | # If true, extends the user's remember period when remembered via cookie. 124 | # config.extend_remember_period = false 125 | 126 | # Options to be passed to the created cookie. For instance, you can set 127 | # :secure => true in order to force SSL only cookies. 128 | # config.rememberable_options = {} 129 | 130 | # ==> Configuration for :validatable 131 | # Range for password length. Default is 6..128. 132 | # config.password_length = 6..128 133 | 134 | # Email regex used to validate email formats. It simply asserts that 135 | # an one (and only one) @ exists in the given string. This is mainly 136 | # to give user feedback and not to assert the e-mail validity. 137 | # config.email_regexp = /\A[^@]+@[^@]+\z/ 138 | 139 | # ==> Configuration for :timeoutable 140 | # The time you want to timeout the user session without activity. After this 141 | # time the user will be asked for credentials again. Default is 30 minutes. 142 | # config.timeout_in = 30.minutes 143 | 144 | # If true, expires auth token on session timeout. 145 | # config.expire_auth_token_on_timeout = false 146 | 147 | # ==> Configuration for :lockable 148 | # Defines which strategy will be used to lock an account. 149 | # :failed_attempts = Locks an account after a number of failed attempts to sign in. 150 | # :none = No lock strategy. You should handle locking by yourself. 151 | # config.lock_strategy = :failed_attempts 152 | 153 | # Defines which key will be used when locking and unlocking an account 154 | # config.unlock_keys = [ :email ] 155 | 156 | # Defines which strategy will be used to unlock an account. 157 | # :email = Sends an unlock link to the user email 158 | # :time = Re-enables login after a certain amount of time (see :unlock_in below) 159 | # :both = Enables both strategies 160 | # :none = No unlock strategy. You should handle unlocking by yourself. 161 | # config.unlock_strategy = :both 162 | 163 | # Number of authentication tries before locking an account if lock_strategy 164 | # is failed attempts. 165 | # config.maximum_attempts = 20 166 | 167 | # Time interval to unlock the account if :time is enabled as unlock_strategy. 168 | # config.unlock_in = 1.hour 169 | 170 | # ==> Configuration for :recoverable 171 | # 172 | # Defines which key will be used when recovering the password for an account 173 | # config.reset_password_keys = [ :email ] 174 | 175 | # Time interval you can reset your password with a reset password key. 176 | # Don't put a too small interval or your users won't have the time to 177 | # change their passwords. 178 | config.reset_password_within = 6.hours 179 | 180 | # ==> Configuration for :encryptable 181 | # Allow you to use another encryption algorithm besides bcrypt (default). You can use 182 | # :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1, 183 | # :authlogic_sha512 (then you should set stretches above to 20 for default behavior) 184 | # and :restful_authentication_sha1 (then you should set stretches to 10, and copy 185 | # REST_AUTH_SITE_KEY to pepper) 186 | # config.encryptor = :sha512 187 | 188 | # ==> Configuration for :token_authenticatable 189 | # Defines name of the authentication token params key 190 | # config.token_authentication_key = :auth_token 191 | 192 | # ==> Scopes configuration 193 | # Turn scoped views on. Before rendering "sessions/new", it will first check for 194 | # "users/sessions/new". It's turned off by default because it's slower if you 195 | # are using only default views. 196 | # config.scoped_views = false 197 | 198 | # Configure the default scope given to Warden. By default it's the first 199 | # devise role declared in your routes (usually :user). 200 | # config.default_scope = :user 201 | 202 | # Set this configuration to false if you want /users/sign_out to sign out 203 | # only the current scope. By default, Devise signs out all scopes. 204 | # config.sign_out_all_scopes = true 205 | 206 | # ==> Navigation configuration 207 | # Lists the formats that should be treated as navigational. Formats like 208 | # :html, should redirect to the sign in page when the user does not have 209 | # access, but formats like :xml or :json, should return 401. 210 | # 211 | # If you have any extra navigational formats, like :iphone or :mobile, you 212 | # should add them to the navigational formats lists. 213 | # 214 | # The "*/*" below is required to match Internet Explorer requests. 215 | # config.navigational_formats = ["*/*", :html] 216 | 217 | # The default HTTP method used to sign out a resource. Default is :delete. 218 | config.sign_out_via = :delete 219 | 220 | # ==> OmniAuth 221 | # Add a new OmniAuth provider. Check the wiki for more information on setting 222 | # up on your models and hooks. 223 | # config.omniauth :github, 'APP_ID', 'APP_SECRET', :scope => 'user,public_repo' 224 | 225 | # ==> Warden configuration 226 | # If you want to use other strategies, that are not supported by Devise, or 227 | # change the failure app, you can configure them inside the config.warden block. 228 | # 229 | # config.warden do |manager| 230 | # manager.intercept_401 = false 231 | # manager.default_strategies(:scope => :user).unshift :some_external_strategy 232 | # end 233 | 234 | # ==> Mountable engine configurations 235 | # When using Devise inside an engine, let's call it `MyEngine`, and this engine 236 | # is mountable, there are some extra configurations to be taken into account. 237 | # The following options are available, assuming the engine is mounted as: 238 | # 239 | # mount MyEngine, at: "/my_engine" 240 | # 241 | # The router that invoked `devise_for`, in the example above, would be: 242 | # config.router_name = :my_engine 243 | # 244 | # When using omniauth, Devise cannot automatically set Omniauth path, 245 | # so you need to do it manually. For the users scope, it would be: 246 | # config.omniauth_path_prefix = "/my_engine/users/auth" 247 | end -------------------------------------------------------------------------------- /spec/rails_app/config/initializers/inflections.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new inflection rules using the following format 4 | # (all these examples are active by default): 5 | # ActiveSupport::Inflector.inflections do |inflect| 6 | # inflect.plural /^(ox)$/i, '\1en' 7 | # inflect.singular /^(ox)en/i, '\1' 8 | # inflect.irregular 'person', 'people' 9 | # inflect.uncountable %w( fish sheep ) 10 | # end 11 | -------------------------------------------------------------------------------- /spec/rails_app/config/initializers/mime_types.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Add new mime types for use in respond_to blocks: 4 | # Mime::Type.register "text/richtext", :rtf 5 | # Mime::Type.register_alias "text/html", :iphone 6 | -------------------------------------------------------------------------------- /spec/rails_app/config/initializers/secret_token.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | # Your secret key for verifying the integrity of signed cookies. 4 | # If you change this key, all old signed cookies will become invalid! 5 | # Make sure the secret is at least 30 characters and all random, 6 | # no regular words or you'll be exposed to dictionary attacks. 7 | Rails.application.config.secret_token = '91f200017212d5529ed7dea1959a9bb36b937bdbddab9180114119a36dd9283c7f8c8d22cd299ce6c6f40e6b8121972953658ef357991b4716b7749a9b215402' 8 | -------------------------------------------------------------------------------- /spec/rails_app/config/initializers/session_store.rb: -------------------------------------------------------------------------------- 1 | # Be sure to restart your server when you modify this file. 2 | 3 | Rails.application.config.session_store :cookie_store, :key => '_rails_app_session' 4 | 5 | # Use the database for sessions instead of the cookie-based default, 6 | # which shouldn't be used to store highly confidential information 7 | # (create the session table with "rake db:sessions:create") 8 | # Rails.application.config.session_store :active_record_store 9 | -------------------------------------------------------------------------------- /spec/rails_app/config/ldap.yml: -------------------------------------------------------------------------------- 1 | authorizations: &AUTHORIZATIONS 2 | ## Authorization 3 | group_base: ou=groups,dc=test,dc=com 4 | required_groups: 5 | - cn=admins,ou=groups,dc=test,dc=com 6 | - ["authorizationRole", "cn=users,ou=groups,dc=test,dc=com"] 7 | require_attribute: 8 | objectClass: inetOrgPerson 9 | authorizationRole: blogAdmin 10 | require_attribute_presence: 11 | mail: true 12 | 13 | test: &TEST 14 | host: localhost 15 | port: 3389 16 | attribute: cn 17 | base: ou=people,dc=test,dc=com 18 | admin_user: cn=admin,dc=test,dc=com 19 | admin_password: secret 20 | ssl: false 21 | <<: *AUTHORIZATIONS 22 | 23 | development: 24 | <<: *TEST 25 | -------------------------------------------------------------------------------- /spec/rails_app/config/ldap_with_boolean_ssl.yml: -------------------------------------------------------------------------------- 1 | authorizations: &AUTHORIZATIONS 2 | ## Authorization 3 | group_base: ou=groups,dc=test,dc=com 4 | required_groups: 5 | - cn=admins,ou=groups,dc=test,dc=com 6 | - ["authorizationRole", "cn=users,ou=groups,dc=test,dc=com"] 7 | require_attribute: 8 | objectClass: inetOrgPerson 9 | authorizationRole: blogAdmin 10 | 11 | test: &TEST 12 | host: localhost 13 | port: 3389 14 | attribute: cn 15 | base: ou=people,dc=test,dc=com 16 | admin_user: cn=admin,dc=test,dc=com 17 | admin_password: secret 18 | ssl: true 19 | <<: *AUTHORIZATIONS 20 | 21 | development: 22 | <<: *TEST 23 | -------------------------------------------------------------------------------- /spec/rails_app/config/ldap_with_erb.yml: -------------------------------------------------------------------------------- 1 | <% @base = "dc=test,dc=com" %> 2 | 3 | authorizations: &AUTHORIZATIONS 4 | ## Authorization 5 | group_base: <%= "ou=groups,#{@base}" %> 6 | required_groups: 7 | - cn=admins,<%= "ou=groups,#{@base}" %> 8 | require_attribute: 9 | objectClass: 10 | - inetOrgPerson 11 | - organizationalPerson 12 | authorizationRole: blogAdmin 13 | 14 | test: &TEST 15 | host: <%= "localhost" %> 16 | port: 3389 17 | attribute: cn 18 | base: <%= "ou=people,#{@base}" %> 19 | admin_user: <%= "cn=admin,#{@base}" %> 20 | admin_password: secret 21 | ssl: false 22 | <<: *AUTHORIZATIONS 23 | 24 | development: 25 | <<: *TEST 26 | -------------------------------------------------------------------------------- /spec/rails_app/config/ldap_with_uid.yml: -------------------------------------------------------------------------------- 1 | authorizations: &AUTHORIZATIONS 2 | ## Authorization 3 | group_base: ou=groups,dc=test,dc=com 4 | required_groups: 5 | - cn=admins,ou=groups,dc=test,dc=com 6 | require_attribute: 7 | objectClass: inetOrgPerson 8 | authorizationRole: blogAdmin 9 | 10 | test: 11 | host: localhost 12 | port: 3389 13 | attribute: uid 14 | base: ou=people,dc=test,dc=com 15 | admin_user: cn=admin,dc=test,dc=com 16 | admin_password: secret 17 | ssl: false 18 | <<: *AUTHORIZATIONS -------------------------------------------------------------------------------- /spec/rails_app/config/locales/devise.en.yml: -------------------------------------------------------------------------------- 1 | # Additional translations at https://github.com/plataformatec/devise/wiki/I18n 2 | 3 | en: 4 | errors: 5 | messages: 6 | expired: "has expired, please request a new one" 7 | not_found: "not found" 8 | already_confirmed: "was already confirmed, please try signing in" 9 | not_locked: "was not locked" 10 | not_saved: 11 | one: "1 error prohibited this %{resource} from being saved:" 12 | other: "%{count} errors prohibited this %{resource} from being saved:" 13 | 14 | devise: 15 | failure: 16 | already_authenticated: 'You are already signed in.' 17 | unauthenticated: 'You need to sign in or sign up before continuing.' 18 | unconfirmed: 'You have to confirm your account before continuing.' 19 | locked: 'Your account is locked.' 20 | not_found_in_database: "Your account is not present in this application's database." 21 | invalid: 'Invalid email or password.' 22 | invalid_token: 'Invalid authentication token.' 23 | timeout: 'Your session expired, please sign in again to continue.' 24 | inactive: 'Your account was not activated yet.' 25 | sessions: 26 | signed_in: 'Signed in successfully.' 27 | signed_out: 'Signed out successfully.' 28 | passwords: 29 | send_instructions: 'You will receive an email with instructions about how to reset your password in a few minutes.' 30 | updated: 'Your password was changed successfully. You are now signed in.' 31 | updated_not_active: 'Your password was changed successfully.' 32 | send_paranoid_instructions: "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes." 33 | no_token: "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided." 34 | confirmations: 35 | send_instructions: 'You will receive an email with instructions about how to confirm your account in a few minutes.' 36 | send_paranoid_instructions: 'If your email address exists in our database, you will receive an email with instructions about how to confirm your account in a few minutes.' 37 | confirmed: 'Your account was successfully confirmed. You are now signed in.' 38 | registrations: 39 | signed_up: 'Welcome! You have signed up successfully.' 40 | signed_up_but_unconfirmed: 'A message with a confirmation link has been sent to your email address. Please open the link to activate your account.' 41 | signed_up_but_inactive: 'You have signed up successfully. However, we could not sign you in because your account is not yet activated.' 42 | signed_up_but_locked: 'You have signed up successfully. However, we could not sign you in because your account is locked.' 43 | updated: 'You updated your account successfully.' 44 | update_needs_confirmation: "You updated your account successfully, but we need to verify your new email address. Please check your email and click on the confirm link to finalize confirming your new email address." 45 | destroyed: 'Bye! Your account was successfully cancelled. We hope to see you again soon.' 46 | unlocks: 47 | send_instructions: 'You will receive an email with instructions about how to unlock your account in a few minutes.' 48 | unlocked: 'Your account has been unlocked successfully. Please sign in to continue.' 49 | send_paranoid_instructions: 'If your account exists, you will receive an email with instructions about how to unlock it in a few minutes.' 50 | omniauth_callbacks: 51 | success: 'Successfully authenticated from %{kind} account.' 52 | failure: 'Could not authenticate you from %{kind} because "%{reason}".' 53 | mailer: 54 | confirmation_instructions: 55 | subject: 'Confirmation instructions' 56 | reset_password_instructions: 57 | subject: 'Reset password instructions' 58 | unlock_instructions: 59 | subject: 'Unlock Instructions' 60 | -------------------------------------------------------------------------------- /spec/rails_app/config/locales/en.yml: -------------------------------------------------------------------------------- 1 | # Sample localization file for English. Add more files in this directory for other locales. 2 | # See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points. 3 | 4 | en: 5 | hello: "Hello world" 6 | -------------------------------------------------------------------------------- /spec/rails_app/config/routes.rb: -------------------------------------------------------------------------------- 1 | RailsApp::Application.routes.draw do 2 | devise_for :users 3 | 4 | resources :posts 5 | 6 | root :to => "posts#index" 7 | 8 | # The priority is based upon order of creation: 9 | # first created -> highest priority. 10 | 11 | # Sample of regular route: 12 | # match 'products/:id' => 'catalog#view' 13 | # Keep in mind you can assign values other than :controller and :action 14 | 15 | # Sample of named route: 16 | # match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase 17 | # This route can be invoked with purchase_url(:id => product.id) 18 | 19 | # Sample resource route (maps HTTP verbs to controller actions automatically): 20 | # resources :products 21 | 22 | # Sample resource route with options: 23 | # resources :products do 24 | # member do 25 | # get :short 26 | # post :toggle 27 | # end 28 | # 29 | # collection do 30 | # get :sold 31 | # end 32 | # end 33 | 34 | # Sample resource route with sub-resources: 35 | # resources :products do 36 | # resources :comments, :sales 37 | # resource :seller 38 | # end 39 | 40 | # Sample resource route with more complex sub-resources 41 | # resources :products do 42 | # resources :comments 43 | # resources :sales do 44 | # get :recent, :on => :collection 45 | # end 46 | # end 47 | 48 | # Sample resource route within a namespace: 49 | # namespace :admin do 50 | # # Directs /admin/products/* to Admin::ProductsController 51 | # # (app/controllers/admin/products_controller.rb) 52 | # resources :products 53 | # end 54 | 55 | # You can have the root of your site routed with "root" 56 | # just remember to delete public/index.html. 57 | # root :to => "welcome#index" 58 | 59 | # See how all your routes lay out with "rake routes" 60 | 61 | # This is a legacy wild controller route that's not recommended for RESTful applications. 62 | # Note: This route will make all actions in every controller accessible via GET requests. 63 | # match ':controller(/:action(/:id(.:format)))' 64 | end 65 | -------------------------------------------------------------------------------- /spec/rails_app/config/ssl_ldap.yml: -------------------------------------------------------------------------------- 1 | authorizations: &AUTHORIZATIONS 2 | ## Authorization 3 | group_base: ou=groups,dc=test,dc=com 4 | required_groups: 5 | - cn=admins,ou=groups,dc=test,dc=com 6 | require_attribute: 7 | objectClass: inetOrgPerson 8 | authorizationRole: blogAdmin 9 | 10 | test: &TEST 11 | host: localhost 12 | port: 3389 13 | attribute: cn 14 | base: ou=people,dc=test,dc=com 15 | admin_user: cn=admin,dc=test,dc=com 16 | admin_password: secret 17 | ssl: true 18 | <<: *AUTHORIZATIONS 19 | 20 | development: 21 | <<: *TEST 22 | -------------------------------------------------------------------------------- /spec/rails_app/config/ssl_ldap_with_erb.yml: -------------------------------------------------------------------------------- 1 | <% @base = "dc=test,dc=com" %> 2 | 3 | authorizations: &AUTHORIZATIONS 4 | ## Authorization 5 | group_base: <%= "ou=groups,#{@base}" %> 6 | required_groups: 7 | - cn=admins,<%= "ou=groups,#{@base}" %> 8 | require_attribute: 9 | objectClass: inetOrgPerson 10 | authorizationRole: blogAdmin 11 | 12 | test: &TEST 13 | host: <%= "localhost" %> 14 | port: 3389 15 | attribute: cn 16 | base: <%= "ou=people,#{@base}" %> 17 | admin_user: <%= "cn=admin,#{@base}" %> 18 | admin_password: secret 19 | ssl: true 20 | <<: *AUTHORIZATIONS 21 | 22 | development: 23 | <<: *TEST 24 | -------------------------------------------------------------------------------- /spec/rails_app/config/ssl_ldap_with_uid.yml: -------------------------------------------------------------------------------- 1 | authorizations: &AUTHORIZATIONS 2 | ## Authorization 3 | group_base: ou=groups,dc=test,dc=com 4 | required_groups: 5 | - cn=admins,ou=groups,dc=test,dc=com 6 | require_attribute: 7 | objectClass: inetOrgPerson 8 | authorizationRole: blogAdmin 9 | 10 | test: 11 | host: localhost 12 | port: 3389 13 | attribute: uid 14 | base: ou=people,dc=test,dc=com 15 | admin_user: cn=admin,dc=test,dc=com 16 | admin_password: secret 17 | ssl: true 18 | <<: *AUTHORIZATIONS -------------------------------------------------------------------------------- /spec/rails_app/db/migrate/20100708120448_devise_create_users.rb: -------------------------------------------------------------------------------- 1 | class DeviseCreateUsers < ActiveRecord::Migration[5.1] 2 | def self.up 3 | create_table(:users) do |t| 4 | ## Database authenticatable 5 | t.string :email, :null => false, :default => "" 6 | t.string :encrypted_password, :null => false, :default => "" 7 | 8 | ## Recoverable 9 | t.string :reset_password_token 10 | t.datetime :reset_password_sent_at 11 | 12 | ## Rememberable 13 | t.datetime :remember_created_at 14 | 15 | ## Trackable 16 | t.integer :sign_in_count, :default => 0 17 | t.datetime :current_sign_in_at 18 | t.datetime :last_sign_in_at 19 | t.string :current_sign_in_ip 20 | t.string :last_sign_in_ip 21 | 22 | t.string :uid 23 | 24 | # t.confirmable 25 | # t.lockable :lock_strategy => :failed_attempts, :unlock_strategy => :both 26 | # t.token_authenticatable 27 | 28 | t.timestamps 29 | end 30 | 31 | add_index :users, :email, :unique => true 32 | add_index :users, :reset_password_token, :unique => true 33 | # add_index :users, :confirmation_token, :unique => true 34 | # add_index :users, :unlock_token, :unique => true 35 | end 36 | 37 | def self.down 38 | drop_table :users 39 | end 40 | end 41 | -------------------------------------------------------------------------------- /spec/rails_app/db/schema.rb: -------------------------------------------------------------------------------- 1 | # This file is auto-generated from the current state of the database. Instead 2 | # of editing this file, please use the migrations feature of Active Record to 3 | # incrementally modify your database, and then regenerate this schema definition. 4 | # 5 | # Note that this schema.rb definition is the authoritative source for your 6 | # database schema. If you need to create the application database on another 7 | # system, you should be using db:schema:load, not running all the migrations 8 | # from scratch. The latter is a flawed and unsustainable approach (the more migrations 9 | # you'll amass, the slower it'll run and the greater likelihood for issues). 10 | # 11 | # It's strongly recommended that you check this file into your version control system. 12 | 13 | ActiveRecord::Schema.define(version: 20100708120448) do 14 | 15 | create_table "users", force: :cascade do |t| 16 | t.string "email", default: "", null: false 17 | t.string "encrypted_password", default: "", null: false 18 | t.string "reset_password_token" 19 | t.datetime "reset_password_sent_at" 20 | t.datetime "remember_created_at" 21 | t.integer "sign_in_count", default: 0 22 | t.datetime "current_sign_in_at" 23 | t.datetime "last_sign_in_at" 24 | t.string "current_sign_in_ip" 25 | t.string "last_sign_in_ip" 26 | t.string "uid" 27 | t.datetime "created_at", null: false 28 | t.datetime "updated_at", null: false 29 | t.index ["email"], name: "index_users_on_email", unique: true 30 | t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true 31 | end 32 | 33 | end 34 | -------------------------------------------------------------------------------- /spec/rails_app/features/manage_logins.feature: -------------------------------------------------------------------------------- 1 | Feature: Manage logins 2 | In order to login with Devise LDAP Authenticatable 3 | As a user 4 | I want to login with LDAP 5 | 6 | Background: 7 | Given I check for SSL 8 | Given the following logins: 9 | | email | password | 10 | | example.user@test.com | secret | 11 | 12 | Scenario: Login with valid user 13 | Given I am on the login page 14 | When I fill in "Email" with "example.user@test.com" 15 | And I fill in "Password" with "secret" 16 | And I press "Sign in" 17 | Then I should see "posts#index" 18 | 19 | Scenario: Login with invalid user 20 | Given I am on the login page 21 | When I fill in "Email" with "example.user@test.com" 22 | And I fill in "Password" with "wrong" 23 | And I press "Sign in" 24 | Then I should see "Invalid email or password" 25 | 26 | Scenario: Get redirected to the login page and then login 27 | When I go to the new post page 28 | Then I should be on the login page 29 | When I fill in "Email" with "example.user@test.com" 30 | And I fill in "Password" with "secret" 31 | And I press "Sign in" 32 | Then I should be on the new post page 33 | 34 | 35 | -------------------------------------------------------------------------------- /spec/rails_app/features/step_definitions/login_steps.rb: -------------------------------------------------------------------------------- 1 | Given /^the following logins:$/ do |logins| 2 | logins.hashes.each do |user| 3 | User.create(:email => user["email"], :password => user["password"]) 4 | end 5 | end 6 | 7 | Given /^I check for SSL$/ do 8 | ::Devise.ldap_config = "#{Rails.root}/config/ssl_ldap.yml" if ENV["LDAP_SSL"] 9 | end 10 | 11 | When /^I delete the (\d+)(?:st|nd|rd|th) login$/ do |pos| 12 | visit logins_path 13 | within("table tr:nth-child(#{pos.to_i+1})") do 14 | click_link "Destroy" 15 | end 16 | end 17 | 18 | Then /^I should see the following logins:$/ do |expected_logins_table| 19 | expected_logins_table.diff!(tableish('table tr', 'td,th')) 20 | end 21 | 22 | -------------------------------------------------------------------------------- /spec/rails_app/features/step_definitions/web_steps.rb: -------------------------------------------------------------------------------- 1 | # IMPORTANT: This file is generated by cucumber-rails - edit at your own peril. 2 | # It is recommended to regenerate this file in the future when you upgrade to a 3 | # newer version of cucumber-rails. Consider adding your own code to a new file 4 | # instead of editing this one. Cucumber will automatically load all features/**/*.rb 5 | # files. 6 | 7 | 8 | require 'uri' 9 | require 'cgi' 10 | require File.expand_path(File.join(File.dirname(__FILE__), "..", "support", "paths")) 11 | 12 | module WithinHelpers 13 | def with_scope(locator) 14 | locator ? within(locator) { yield } : yield 15 | end 16 | end 17 | World(WithinHelpers) 18 | 19 | Given /^(?:|I )am on (.+)$/ do |page_name| 20 | visit path_to(page_name) 21 | end 22 | 23 | When /^(?:|I )go to (.+)$/ do |page_name| 24 | visit path_to(page_name) 25 | end 26 | 27 | When /^(?:|I )press "([^"]*)"(?: within "([^"]*)")?$/ do |button, selector| 28 | with_scope(selector) do 29 | click_button(button) 30 | end 31 | end 32 | 33 | When /^(?:|I )follow "([^"]*)"(?: within "([^"]*)")?$/ do |link, selector| 34 | with_scope(selector) do 35 | click_link(link) 36 | end 37 | end 38 | 39 | When /^(?:|I )fill in "([^"]*)" with "([^"]*)"(?: within "([^"]*)")?$/ do |field, value, selector| 40 | with_scope(selector) do 41 | fill_in(field, :with => value) 42 | end 43 | end 44 | 45 | When /^(?:|I )fill in "([^"]*)" for "([^"]*)"(?: within "([^"]*)")?$/ do |value, field, selector| 46 | with_scope(selector) do 47 | fill_in(field, :with => value) 48 | end 49 | end 50 | 51 | # Use this to fill in an entire form with data from a table. Example: 52 | # 53 | # When I fill in the following: 54 | # | Account Number | 5002 | 55 | # | Expiry date | 2009-11-01 | 56 | # | Note | Nice guy | 57 | # | Wants Email? | | 58 | # 59 | # TODO: Add support for checkbox, select og option 60 | # based on naming conventions. 61 | # 62 | When /^(?:|I )fill in the following(?: within "([^"]*)")?:$/ do |selector, fields| 63 | with_scope(selector) do 64 | fields.rows_hash.each do |name, value| 65 | When %{I fill in "#{name}" with "#{value}"} 66 | end 67 | end 68 | end 69 | 70 | When /^(?:|I )select "([^"]*)" from "([^"]*)"(?: within "([^"]*)")?$/ do |value, field, selector| 71 | with_scope(selector) do 72 | select(value, :from => field) 73 | end 74 | end 75 | 76 | When /^(?:|I )check "([^"]*)"(?: within "([^"]*)")?$/ do |field, selector| 77 | with_scope(selector) do 78 | check(field) 79 | end 80 | end 81 | 82 | When /^(?:|I )uncheck "([^"]*)"(?: within "([^"]*)")?$/ do |field, selector| 83 | with_scope(selector) do 84 | uncheck(field) 85 | end 86 | end 87 | 88 | When /^(?:|I )choose "([^"]*)"(?: within "([^"]*)")?$/ do |field, selector| 89 | with_scope(selector) do 90 | choose(field) 91 | end 92 | end 93 | 94 | When /^(?:|I )attach the file "([^"]*)" to "([^"]*)"(?: within "([^"]*)")?$/ do |path, field, selector| 95 | with_scope(selector) do 96 | attach_file(field, path) 97 | end 98 | end 99 | 100 | Then /^(?:|I )should see JSON:$/ do |expected_json| 101 | require 'json' 102 | expected = JSON.pretty_generate(JSON.parse(expected_json)) 103 | actual = JSON.pretty_generate(JSON.parse(response.body)) 104 | expected.should == actual 105 | end 106 | 107 | Then /^(?:|I )should see "([^"]*)"(?: within "([^"]*)")?$/ do |text, selector| 108 | with_scope(selector) do 109 | if page.respond_to? :should 110 | page.should have_content(text) 111 | else 112 | assert page.has_content?(text) 113 | end 114 | end 115 | end 116 | 117 | Then /^(?:|I )should see \/([^\/]*)\/(?: within "([^"]*)")?$/ do |regexp, selector| 118 | regexp = Regexp.new(regexp) 119 | with_scope(selector) do 120 | if page.respond_to? :should 121 | page.should have_xpath('//*', :text => regexp) 122 | else 123 | assert page.has_xpath?('//*', :text => regexp) 124 | end 125 | end 126 | end 127 | 128 | Then /^(?:|I )should not see "([^"]*)"(?: within "([^"]*)")?$/ do |text, selector| 129 | with_scope(selector) do 130 | if page.respond_to? :should 131 | page.should have_no_content(text) 132 | else 133 | assert page.has_no_content?(text) 134 | end 135 | end 136 | end 137 | 138 | Then /^(?:|I )should not see \/([^\/]*)\/(?: within "([^"]*)")?$/ do |regexp, selector| 139 | regexp = Regexp.new(regexp) 140 | with_scope(selector) do 141 | if page.respond_to? :should 142 | page.should have_no_xpath('//*', :text => regexp) 143 | else 144 | assert page.has_no_xpath?('//*', :text => regexp) 145 | end 146 | end 147 | end 148 | 149 | Then /^the "([^"]*)" field(?: within "([^"]*)")? should contain "([^"]*)"$/ do |field, selector, value| 150 | with_scope(selector) do 151 | field = find_field(field) 152 | field_value = (field.tag_name == 'textarea') ? field.text : field.value 153 | if field_value.respond_to? :should 154 | field_value.should =~ /#{value}/ 155 | else 156 | assert_match(/#{value}/, field_value) 157 | end 158 | end 159 | end 160 | 161 | Then /^the "([^"]*)" field(?: within "([^"]*)")? should not contain "([^"]*)"$/ do |field, selector, value| 162 | with_scope(selector) do 163 | field = find_field(field) 164 | field_value = (field.tag_name == 'textarea') ? field.text : field.value 165 | if field_value.respond_to? :should_not 166 | field_value.should_not =~ /#{value}/ 167 | else 168 | assert_no_match(/#{value}/, field_value) 169 | end 170 | end 171 | end 172 | 173 | Then /^the "([^"]*)" checkbox(?: within "([^"]*)")? should be checked$/ do |label, selector| 174 | with_scope(selector) do 175 | field_checked = find_field(label)['checked'] 176 | if field_checked.respond_to? :should 177 | field_checked.should be_true 178 | else 179 | assert field_checked 180 | end 181 | end 182 | end 183 | 184 | Then /^the "([^"]*)" checkbox(?: within "([^"]*)")? should not be checked$/ do |label, selector| 185 | with_scope(selector) do 186 | field_checked = find_field(label)['checked'] 187 | if field_checked.respond_to? :should 188 | field_checked.should be_false 189 | else 190 | assert !field_checked 191 | end 192 | end 193 | end 194 | 195 | Then /^(?:|I )should be on (.+)$/ do |page_name| 196 | current_path = URI.parse(current_url).path 197 | if current_path.respond_to? :should 198 | current_path.should == path_to(page_name) 199 | else 200 | assert_equal path_to(page_name), current_path 201 | end 202 | end 203 | 204 | Then /^(?:|I )should have the following query string:$/ do |expected_pairs| 205 | query = URI.parse(current_url).query 206 | actual_params = query ? CGI.parse(query) : {} 207 | expected_params = {} 208 | expected_pairs.rows_hash.each_pair{|k,v| expected_params[k] = v.split(',')} 209 | 210 | if actual_params.respond_to? :should 211 | actual_params.should == expected_params 212 | else 213 | assert_equal expected_params, actual_params 214 | end 215 | end 216 | 217 | Then /^show me the page$/ do 218 | save_and_open_page 219 | end 220 | -------------------------------------------------------------------------------- /spec/rails_app/features/support/env.rb: -------------------------------------------------------------------------------- 1 | # IMPORTANT: This file is generated by cucumber-rails - edit at your own peril. 2 | # It is recommended to regenerate this file in the future when you upgrade to a 3 | # newer version of cucumber-rails. Consider adding your own code to a new file 4 | # instead of editing this one. Cucumber will automatically load all features/**/*.rb 5 | # files. 6 | 7 | ENV["RAILS_ENV"] ||= "test" 8 | require File.expand_path(File.dirname(__FILE__) + '/../../config/environment') 9 | 10 | require 'cucumber/formatter/unicode' # Remove this line if you don't want Cucumber Unicode support 11 | require 'cucumber/rails/world' 12 | require 'cucumber/rails/active_record' 13 | require 'cucumber/web/tableish' 14 | 15 | require 'capybara/rails' 16 | require 'capybara/cucumber' 17 | require 'capybara/session' 18 | require 'cucumber/rails/capybara_javascript_emulation' # Lets you click links with onclick javascript handlers without using @culerity or @javascript 19 | # Capybara defaults to XPath selectors rather than Webrat's default of CSS3. In 20 | # order to ease the transition to Capybara we set the default here. If you'd 21 | # prefer to use XPath just remove this line and adjust any selectors in your 22 | # steps to use the XPath syntax. 23 | Capybara.default_selector = :css 24 | Capybara.save_and_open_page_path = File.join('/tmp') 25 | 26 | # If you set this to false, any error raised from within your app will bubble 27 | # up to your step definition and out to cucumber unless you catch it somewhere 28 | # on the way. You can make Rails rescue errors and render error pages on a 29 | # per-scenario basis by tagging a scenario or feature with the @allow-rescue tag. 30 | # 31 | # If you set this to true, Rails will rescue all errors and render error 32 | # pages, more or less in the same way your application would behave in the 33 | # default production environment. It's not recommended to do this for all 34 | # of your scenarios, as this makes it hard to discover errors in your application. 35 | ActionController::Base.allow_rescue = false 36 | 37 | # If you set this to true, each scenario will run in a database transaction. 38 | # You can still turn off transactions on a per-scenario basis, simply tagging 39 | # a feature or scenario with the @no-txn tag. If you are using Capybara, 40 | # tagging with @culerity or @javascript will also turn transactions off. 41 | # 42 | # If you set this to false, transactions will be off for all scenarios, 43 | # regardless of whether you use @no-txn or not. 44 | # 45 | # Beware that turning transactions off will leave data in your database 46 | # after each scenario, which can lead to hard-to-debug failures in 47 | # subsequent scenarios. If you do this, we recommend you create a Before 48 | # block that will explicitly put your database in a known state. 49 | Cucumber::Rails::World.use_transactional_fixtures = true 50 | # How to clean your database when transactions are turned off. See 51 | # http://github.com/bmabey/database_cleaner for more info. 52 | if defined?(ActiveRecord::Base) 53 | begin 54 | require 'database_cleaner' 55 | DatabaseCleaner.strategy = :truncation 56 | rescue LoadError => ignore_if_database_cleaner_not_present 57 | end 58 | end 59 | -------------------------------------------------------------------------------- /spec/rails_app/features/support/paths.rb: -------------------------------------------------------------------------------- 1 | module NavigationHelpers 2 | # Maps a name to a path. Used by the 3 | # 4 | # When /^I go to (.+)$/ do |page_name| 5 | # 6 | # step definition in web_steps.rb 7 | # 8 | def path_to(page_name) 9 | case page_name 10 | 11 | when /the home\s?page/ 12 | '/' 13 | when /the login page/ 14 | new_user_session_path 15 | 16 | when /the new post page/ 17 | new_post_path 18 | 19 | # Add more mappings here. 20 | # Here is an example that pulls values out of the Regexp: 21 | # 22 | # when /^(.*)'s profile page$/i 23 | # user_profile_path(User.find_by_login($1)) 24 | 25 | else 26 | begin 27 | page_name =~ /the (.*) page/ 28 | path_components = $1.split(/\s+/) 29 | self.send(path_components.push('path').join('_').to_sym) 30 | rescue Object => e 31 | raise "Can't find mapping from \"#{page_name}\" to a path.\n" + 32 | "Now, go and add a mapping in #{__FILE__}" 33 | end 34 | end 35 | end 36 | end 37 | 38 | World(NavigationHelpers) 39 | -------------------------------------------------------------------------------- /spec/rails_app/lib/tasks/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cschiewek/devise_ldap_authenticatable/6ef2131e79ff3421429f8d1b0645c6e113db4dc7/spec/rails_app/lib/tasks/.gitkeep -------------------------------------------------------------------------------- /spec/rails_app/lib/tasks/cucumber.rake: -------------------------------------------------------------------------------- 1 | # IMPORTANT: This file is generated by cucumber-rails - edit at your own peril. 2 | # It is recommended to regenerate this file in the future when you upgrade to a 3 | # newer version of cucumber-rails. Consider adding your own code to a new file 4 | # instead of editing this one. Cucumber will automatically load all features/**/*.rb 5 | # files. 6 | 7 | 8 | unless ARGV.any? {|a| a =~ /^gems/} # Don't load anything when running the gems:* tasks 9 | 10 | vendored_cucumber_bin = Dir["#{Rails.root}/vendor/{gems,plugins}/cucumber*/bin/cucumber"].first 11 | $LOAD_PATH.unshift(File.dirname(vendored_cucumber_bin) + '/../lib') unless vendored_cucumber_bin.nil? 12 | 13 | begin 14 | require 'cucumber/rake/task' 15 | 16 | namespace :cucumber do 17 | Cucumber::Rake::Task.new({:ok => 'db:test:prepare'}, 'Run features that should pass') do |t| 18 | t.binary = vendored_cucumber_bin # If nil, the gem's binary is used. 19 | t.fork = true # You may get faster startup if you set this to false 20 | t.profile = 'default' 21 | end 22 | 23 | Cucumber::Rake::Task.new({:wip => 'db:test:prepare'}, 'Run features that are being worked on') do |t| 24 | t.binary = vendored_cucumber_bin 25 | t.fork = true # You may get faster startup if you set this to false 26 | t.profile = 'wip' 27 | end 28 | 29 | Cucumber::Rake::Task.new({:rerun => 'db:test:prepare'}, 'Record failing features and run only them if any exist') do |t| 30 | t.binary = vendored_cucumber_bin 31 | t.fork = true # You may get faster startup if you set this to false 32 | t.profile = 'rerun' 33 | end 34 | 35 | desc 'Run all features' 36 | task :all => [:ok, :wip] 37 | end 38 | desc 'Alias for cucumber:ok' 39 | task :cucumber => 'cucumber:ok' 40 | 41 | task :default => :cucumber 42 | 43 | task :features => :cucumber do 44 | STDERR.puts "*** The 'features' task is deprecated. See rake -T cucumber ***" 45 | end 46 | rescue LoadError 47 | desc 'cucumber rake task not available (cucumber not installed)' 48 | task :cucumber do 49 | abort 'Cucumber rake task is not available. Be sure to install cucumber as a gem or plugin' 50 | end 51 | end 52 | 53 | end 54 | -------------------------------------------------------------------------------- /spec/rails_app/public/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The page you were looking for doesn't exist (404) 5 | 17 | 18 | 19 | 20 | 21 |
22 |

The page you were looking for doesn't exist.

23 |

You may have mistyped the address or the page may have moved.

24 |
25 | 26 | 27 | -------------------------------------------------------------------------------- /spec/rails_app/public/422.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | The change you wanted was rejected (422) 5 | 17 | 18 | 19 | 20 | 21 |
22 |

The change you wanted was rejected.

23 |

Maybe you tried to change something you didn't have access to.

24 |
25 | 26 | 27 | -------------------------------------------------------------------------------- /spec/rails_app/public/500.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | We're sorry, but something went wrong (500) 5 | 17 | 18 | 19 | 20 | 21 |
22 |

We're sorry, but something went wrong.

23 |

We've been notified about this issue and we'll take a look at it shortly.

24 |
25 | 26 | 27 | -------------------------------------------------------------------------------- /spec/rails_app/public/images/rails.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cschiewek/devise_ldap_authenticatable/6ef2131e79ff3421429f8d1b0645c6e113db4dc7/spec/rails_app/public/images/rails.png -------------------------------------------------------------------------------- /spec/rails_app/public/javascripts/application.js: -------------------------------------------------------------------------------- 1 | // Place your application-specific JavaScript functions and classes here 2 | // This file is automatically included by javascript_include_tag :defaults 3 | -------------------------------------------------------------------------------- /spec/rails_app/public/javascripts/controls.js: -------------------------------------------------------------------------------- 1 | // script.aculo.us controls.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009 2 | 3 | // Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) 4 | // (c) 2005-2009 Ivan Krstic (http://blogs.law.harvard.edu/ivan) 5 | // (c) 2005-2009 Jon Tirsen (http://www.tirsen.com) 6 | // Contributors: 7 | // Richard Livsey 8 | // Rahul Bhargava 9 | // Rob Wills 10 | // 11 | // script.aculo.us is freely distributable under the terms of an MIT-style license. 12 | // For details, see the script.aculo.us web site: http://script.aculo.us/ 13 | 14 | // Autocompleter.Base handles all the autocompletion functionality 15 | // that's independent of the data source for autocompletion. This 16 | // includes drawing the autocompletion menu, observing keyboard 17 | // and mouse events, and similar. 18 | // 19 | // Specific autocompleters need to provide, at the very least, 20 | // a getUpdatedChoices function that will be invoked every time 21 | // the text inside the monitored textbox changes. This method 22 | // should get the text for which to provide autocompletion by 23 | // invoking this.getToken(), NOT by directly accessing 24 | // this.element.value. This is to allow incremental tokenized 25 | // autocompletion. Specific auto-completion logic (AJAX, etc) 26 | // belongs in getUpdatedChoices. 27 | // 28 | // Tokenized incremental autocompletion is enabled automatically 29 | // when an autocompleter is instantiated with the 'tokens' option 30 | // in the options parameter, e.g.: 31 | // new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' }); 32 | // will incrementally autocomplete with a comma as the token. 33 | // Additionally, ',' in the above example can be replaced with 34 | // a token array, e.g. { tokens: [',', '\n'] } which 35 | // enables autocompletion on multiple tokens. This is most 36 | // useful when one of the tokens is \n (a newline), as it 37 | // allows smart autocompletion after linebreaks. 38 | 39 | if(typeof Effect == 'undefined') 40 | throw("controls.js requires including script.aculo.us' effects.js library"); 41 | 42 | var Autocompleter = { }; 43 | Autocompleter.Base = Class.create({ 44 | baseInitialize: function(element, update, options) { 45 | element = $(element); 46 | this.element = element; 47 | this.update = $(update); 48 | this.hasFocus = false; 49 | this.changed = false; 50 | this.active = false; 51 | this.index = 0; 52 | this.entryCount = 0; 53 | this.oldElementValue = this.element.value; 54 | 55 | if(this.setOptions) 56 | this.setOptions(options); 57 | else 58 | this.options = options || { }; 59 | 60 | this.options.paramName = this.options.paramName || this.element.name; 61 | this.options.tokens = this.options.tokens || []; 62 | this.options.frequency = this.options.frequency || 0.4; 63 | this.options.minChars = this.options.minChars || 1; 64 | this.options.onShow = this.options.onShow || 65 | function(element, update){ 66 | if(!update.style.position || update.style.position=='absolute') { 67 | update.style.position = 'absolute'; 68 | Position.clone(element, update, { 69 | setHeight: false, 70 | offsetTop: element.offsetHeight 71 | }); 72 | } 73 | Effect.Appear(update,{duration:0.15}); 74 | }; 75 | this.options.onHide = this.options.onHide || 76 | function(element, update){ new Effect.Fade(update,{duration:0.15}) }; 77 | 78 | if(typeof(this.options.tokens) == 'string') 79 | this.options.tokens = new Array(this.options.tokens); 80 | // Force carriage returns as token delimiters anyway 81 | if (!this.options.tokens.include('\n')) 82 | this.options.tokens.push('\n'); 83 | 84 | this.observer = null; 85 | 86 | this.element.setAttribute('autocomplete','off'); 87 | 88 | Element.hide(this.update); 89 | 90 | Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this)); 91 | Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this)); 92 | }, 93 | 94 | show: function() { 95 | if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update); 96 | if(!this.iefix && 97 | (Prototype.Browser.IE) && 98 | (Element.getStyle(this.update, 'position')=='absolute')) { 99 | new Insertion.After(this.update, 100 | ''); 103 | this.iefix = $(this.update.id+'_iefix'); 104 | } 105 | if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50); 106 | }, 107 | 108 | fixIEOverlapping: function() { 109 | Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)}); 110 | this.iefix.style.zIndex = 1; 111 | this.update.style.zIndex = 2; 112 | Element.show(this.iefix); 113 | }, 114 | 115 | hide: function() { 116 | this.stopIndicator(); 117 | if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update); 118 | if(this.iefix) Element.hide(this.iefix); 119 | }, 120 | 121 | startIndicator: function() { 122 | if(this.options.indicator) Element.show(this.options.indicator); 123 | }, 124 | 125 | stopIndicator: function() { 126 | if(this.options.indicator) Element.hide(this.options.indicator); 127 | }, 128 | 129 | onKeyPress: function(event) { 130 | if(this.active) 131 | switch(event.keyCode) { 132 | case Event.KEY_TAB: 133 | case Event.KEY_RETURN: 134 | this.selectEntry(); 135 | Event.stop(event); 136 | case Event.KEY_ESC: 137 | this.hide(); 138 | this.active = false; 139 | Event.stop(event); 140 | return; 141 | case Event.KEY_LEFT: 142 | case Event.KEY_RIGHT: 143 | return; 144 | case Event.KEY_UP: 145 | this.markPrevious(); 146 | this.render(); 147 | Event.stop(event); 148 | return; 149 | case Event.KEY_DOWN: 150 | this.markNext(); 151 | this.render(); 152 | Event.stop(event); 153 | return; 154 | } 155 | else 156 | if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN || 157 | (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return; 158 | 159 | this.changed = true; 160 | this.hasFocus = true; 161 | 162 | if(this.observer) clearTimeout(this.observer); 163 | this.observer = 164 | setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000); 165 | }, 166 | 167 | activate: function() { 168 | this.changed = false; 169 | this.hasFocus = true; 170 | this.getUpdatedChoices(); 171 | }, 172 | 173 | onHover: function(event) { 174 | var element = Event.findElement(event, 'LI'); 175 | if(this.index != element.autocompleteIndex) 176 | { 177 | this.index = element.autocompleteIndex; 178 | this.render(); 179 | } 180 | Event.stop(event); 181 | }, 182 | 183 | onClick: function(event) { 184 | var element = Event.findElement(event, 'LI'); 185 | this.index = element.autocompleteIndex; 186 | this.selectEntry(); 187 | this.hide(); 188 | }, 189 | 190 | onBlur: function(event) { 191 | // needed to make click events working 192 | setTimeout(this.hide.bind(this), 250); 193 | this.hasFocus = false; 194 | this.active = false; 195 | }, 196 | 197 | render: function() { 198 | if(this.entryCount > 0) { 199 | for (var i = 0; i < this.entryCount; i++) 200 | this.index==i ? 201 | Element.addClassName(this.getEntry(i),"selected") : 202 | Element.removeClassName(this.getEntry(i),"selected"); 203 | if(this.hasFocus) { 204 | this.show(); 205 | this.active = true; 206 | } 207 | } else { 208 | this.active = false; 209 | this.hide(); 210 | } 211 | }, 212 | 213 | markPrevious: function() { 214 | if(this.index > 0) this.index--; 215 | else this.index = this.entryCount-1; 216 | this.getEntry(this.index).scrollIntoView(true); 217 | }, 218 | 219 | markNext: function() { 220 | if(this.index < this.entryCount-1) this.index++; 221 | else this.index = 0; 222 | this.getEntry(this.index).scrollIntoView(false); 223 | }, 224 | 225 | getEntry: function(index) { 226 | return this.update.firstChild.childNodes[index]; 227 | }, 228 | 229 | getCurrentEntry: function() { 230 | return this.getEntry(this.index); 231 | }, 232 | 233 | selectEntry: function() { 234 | this.active = false; 235 | this.updateElement(this.getCurrentEntry()); 236 | }, 237 | 238 | updateElement: function(selectedElement) { 239 | if (this.options.updateElement) { 240 | this.options.updateElement(selectedElement); 241 | return; 242 | } 243 | var value = ''; 244 | if (this.options.select) { 245 | var nodes = $(selectedElement).select('.' + this.options.select) || []; 246 | if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select); 247 | } else 248 | value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal'); 249 | 250 | var bounds = this.getTokenBounds(); 251 | if (bounds[0] != -1) { 252 | var newValue = this.element.value.substr(0, bounds[0]); 253 | var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/); 254 | if (whitespace) 255 | newValue += whitespace[0]; 256 | this.element.value = newValue + value + this.element.value.substr(bounds[1]); 257 | } else { 258 | this.element.value = value; 259 | } 260 | this.oldElementValue = this.element.value; 261 | this.element.focus(); 262 | 263 | if (this.options.afterUpdateElement) 264 | this.options.afterUpdateElement(this.element, selectedElement); 265 | }, 266 | 267 | updateChoices: function(choices) { 268 | if(!this.changed && this.hasFocus) { 269 | this.update.innerHTML = choices; 270 | Element.cleanWhitespace(this.update); 271 | Element.cleanWhitespace(this.update.down()); 272 | 273 | if(this.update.firstChild && this.update.down().childNodes) { 274 | this.entryCount = 275 | this.update.down().childNodes.length; 276 | for (var i = 0; i < this.entryCount; i++) { 277 | var entry = this.getEntry(i); 278 | entry.autocompleteIndex = i; 279 | this.addObservers(entry); 280 | } 281 | } else { 282 | this.entryCount = 0; 283 | } 284 | 285 | this.stopIndicator(); 286 | this.index = 0; 287 | 288 | if(this.entryCount==1 && this.options.autoSelect) { 289 | this.selectEntry(); 290 | this.hide(); 291 | } else { 292 | this.render(); 293 | } 294 | } 295 | }, 296 | 297 | addObservers: function(element) { 298 | Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this)); 299 | Event.observe(element, "click", this.onClick.bindAsEventListener(this)); 300 | }, 301 | 302 | onObserverEvent: function() { 303 | this.changed = false; 304 | this.tokenBounds = null; 305 | if(this.getToken().length>=this.options.minChars) { 306 | this.getUpdatedChoices(); 307 | } else { 308 | this.active = false; 309 | this.hide(); 310 | } 311 | this.oldElementValue = this.element.value; 312 | }, 313 | 314 | getToken: function() { 315 | var bounds = this.getTokenBounds(); 316 | return this.element.value.substring(bounds[0], bounds[1]).strip(); 317 | }, 318 | 319 | getTokenBounds: function() { 320 | if (null != this.tokenBounds) return this.tokenBounds; 321 | var value = this.element.value; 322 | if (value.strip().empty()) return [-1, 0]; 323 | var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue); 324 | var offset = (diff == this.oldElementValue.length ? 1 : 0); 325 | var prevTokenPos = -1, nextTokenPos = value.length; 326 | var tp; 327 | for (var index = 0, l = this.options.tokens.length; index < l; ++index) { 328 | tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1); 329 | if (tp > prevTokenPos) prevTokenPos = tp; 330 | tp = value.indexOf(this.options.tokens[index], diff + offset); 331 | if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp; 332 | } 333 | return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]); 334 | } 335 | }); 336 | 337 | Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) { 338 | var boundary = Math.min(newS.length, oldS.length); 339 | for (var index = 0; index < boundary; ++index) 340 | if (newS[index] != oldS[index]) 341 | return index; 342 | return boundary; 343 | }; 344 | 345 | Ajax.Autocompleter = Class.create(Autocompleter.Base, { 346 | initialize: function(element, update, url, options) { 347 | this.baseInitialize(element, update, options); 348 | this.options.asynchronous = true; 349 | this.options.onComplete = this.onComplete.bind(this); 350 | this.options.defaultParams = this.options.parameters || null; 351 | this.url = url; 352 | }, 353 | 354 | getUpdatedChoices: function() { 355 | this.startIndicator(); 356 | 357 | var entry = encodeURIComponent(this.options.paramName) + '=' + 358 | encodeURIComponent(this.getToken()); 359 | 360 | this.options.parameters = this.options.callback ? 361 | this.options.callback(this.element, entry) : entry; 362 | 363 | if(this.options.defaultParams) 364 | this.options.parameters += '&' + this.options.defaultParams; 365 | 366 | new Ajax.Request(this.url, this.options); 367 | }, 368 | 369 | onComplete: function(request) { 370 | this.updateChoices(request.responseText); 371 | } 372 | }); 373 | 374 | // The local array autocompleter. Used when you'd prefer to 375 | // inject an array of autocompletion options into the page, rather 376 | // than sending out Ajax queries, which can be quite slow sometimes. 377 | // 378 | // The constructor takes four parameters. The first two are, as usual, 379 | // the id of the monitored textbox, and id of the autocompletion menu. 380 | // The third is the array you want to autocomplete from, and the fourth 381 | // is the options block. 382 | // 383 | // Extra local autocompletion options: 384 | // - choices - How many autocompletion choices to offer 385 | // 386 | // - partialSearch - If false, the autocompleter will match entered 387 | // text only at the beginning of strings in the 388 | // autocomplete array. Defaults to true, which will 389 | // match text at the beginning of any *word* in the 390 | // strings in the autocomplete array. If you want to 391 | // search anywhere in the string, additionally set 392 | // the option fullSearch to true (default: off). 393 | // 394 | // - fullSsearch - Search anywhere in autocomplete array strings. 395 | // 396 | // - partialChars - How many characters to enter before triggering 397 | // a partial match (unlike minChars, which defines 398 | // how many characters are required to do any match 399 | // at all). Defaults to 2. 400 | // 401 | // - ignoreCase - Whether to ignore case when autocompleting. 402 | // Defaults to true. 403 | // 404 | // It's possible to pass in a custom function as the 'selector' 405 | // option, if you prefer to write your own autocompletion logic. 406 | // In that case, the other options above will not apply unless 407 | // you support them. 408 | 409 | Autocompleter.Local = Class.create(Autocompleter.Base, { 410 | initialize: function(element, update, array, options) { 411 | this.baseInitialize(element, update, options); 412 | this.options.array = array; 413 | }, 414 | 415 | getUpdatedChoices: function() { 416 | this.updateChoices(this.options.selector(this)); 417 | }, 418 | 419 | setOptions: function(options) { 420 | this.options = Object.extend({ 421 | choices: 10, 422 | partialSearch: true, 423 | partialChars: 2, 424 | ignoreCase: true, 425 | fullSearch: false, 426 | selector: function(instance) { 427 | var ret = []; // Beginning matches 428 | var partial = []; // Inside matches 429 | var entry = instance.getToken(); 430 | var count = 0; 431 | 432 | for (var i = 0; i < instance.options.array.length && 433 | ret.length < instance.options.choices ; i++) { 434 | 435 | var elem = instance.options.array[i]; 436 | var foundPos = instance.options.ignoreCase ? 437 | elem.toLowerCase().indexOf(entry.toLowerCase()) : 438 | elem.indexOf(entry); 439 | 440 | while (foundPos != -1) { 441 | if (foundPos == 0 && elem.length != entry.length) { 442 | ret.push("
  • " + elem.substr(0, entry.length) + "" + 443 | elem.substr(entry.length) + "
  • "); 444 | break; 445 | } else if (entry.length >= instance.options.partialChars && 446 | instance.options.partialSearch && foundPos != -1) { 447 | if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) { 448 | partial.push("
  • " + elem.substr(0, foundPos) + "" + 449 | elem.substr(foundPos, entry.length) + "" + elem.substr( 450 | foundPos + entry.length) + "
  • "); 451 | break; 452 | } 453 | } 454 | 455 | foundPos = instance.options.ignoreCase ? 456 | elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) : 457 | elem.indexOf(entry, foundPos + 1); 458 | 459 | } 460 | } 461 | if (partial.length) 462 | ret = ret.concat(partial.slice(0, instance.options.choices - ret.length)); 463 | return ""; 464 | } 465 | }, options || { }); 466 | } 467 | }); 468 | 469 | // AJAX in-place editor and collection editor 470 | // Full rewrite by Christophe Porteneuve (April 2007). 471 | 472 | // Use this if you notice weird scrolling problems on some browsers, 473 | // the DOM might be a bit confused when this gets called so do this 474 | // waits 1 ms (with setTimeout) until it does the activation 475 | Field.scrollFreeActivate = function(field) { 476 | setTimeout(function() { 477 | Field.activate(field); 478 | }, 1); 479 | }; 480 | 481 | Ajax.InPlaceEditor = Class.create({ 482 | initialize: function(element, url, options) { 483 | this.url = url; 484 | this.element = element = $(element); 485 | this.prepareOptions(); 486 | this._controls = { }; 487 | arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!! 488 | Object.extend(this.options, options || { }); 489 | if (!this.options.formId && this.element.id) { 490 | this.options.formId = this.element.id + '-inplaceeditor'; 491 | if ($(this.options.formId)) 492 | this.options.formId = ''; 493 | } 494 | if (this.options.externalControl) 495 | this.options.externalControl = $(this.options.externalControl); 496 | if (!this.options.externalControl) 497 | this.options.externalControlOnly = false; 498 | this._originalBackground = this.element.getStyle('background-color') || 'transparent'; 499 | this.element.title = this.options.clickToEditText; 500 | this._boundCancelHandler = this.handleFormCancellation.bind(this); 501 | this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this); 502 | this._boundFailureHandler = this.handleAJAXFailure.bind(this); 503 | this._boundSubmitHandler = this.handleFormSubmission.bind(this); 504 | this._boundWrapperHandler = this.wrapUp.bind(this); 505 | this.registerListeners(); 506 | }, 507 | checkForEscapeOrReturn: function(e) { 508 | if (!this._editing || e.ctrlKey || e.altKey || e.shiftKey) return; 509 | if (Event.KEY_ESC == e.keyCode) 510 | this.handleFormCancellation(e); 511 | else if (Event.KEY_RETURN == e.keyCode) 512 | this.handleFormSubmission(e); 513 | }, 514 | createControl: function(mode, handler, extraClasses) { 515 | var control = this.options[mode + 'Control']; 516 | var text = this.options[mode + 'Text']; 517 | if ('button' == control) { 518 | var btn = document.createElement('input'); 519 | btn.type = 'submit'; 520 | btn.value = text; 521 | btn.className = 'editor_' + mode + '_button'; 522 | if ('cancel' == mode) 523 | btn.onclick = this._boundCancelHandler; 524 | this._form.appendChild(btn); 525 | this._controls[mode] = btn; 526 | } else if ('link' == control) { 527 | var link = document.createElement('a'); 528 | link.href = '#'; 529 | link.appendChild(document.createTextNode(text)); 530 | link.onclick = 'cancel' == mode ? this._boundCancelHandler : this._boundSubmitHandler; 531 | link.className = 'editor_' + mode + '_link'; 532 | if (extraClasses) 533 | link.className += ' ' + extraClasses; 534 | this._form.appendChild(link); 535 | this._controls[mode] = link; 536 | } 537 | }, 538 | createEditField: function() { 539 | var text = (this.options.loadTextURL ? this.options.loadingText : this.getText()); 540 | var fld; 541 | if (1 >= this.options.rows && !/\r|\n/.test(this.getText())) { 542 | fld = document.createElement('input'); 543 | fld.type = 'text'; 544 | var size = this.options.size || this.options.cols || 0; 545 | if (0 < size) fld.size = size; 546 | } else { 547 | fld = document.createElement('textarea'); 548 | fld.rows = (1 >= this.options.rows ? this.options.autoRows : this.options.rows); 549 | fld.cols = this.options.cols || 40; 550 | } 551 | fld.name = this.options.paramName; 552 | fld.value = text; // No HTML breaks conversion anymore 553 | fld.className = 'editor_field'; 554 | if (this.options.submitOnBlur) 555 | fld.onblur = this._boundSubmitHandler; 556 | this._controls.editor = fld; 557 | if (this.options.loadTextURL) 558 | this.loadExternalText(); 559 | this._form.appendChild(this._controls.editor); 560 | }, 561 | createForm: function() { 562 | var ipe = this; 563 | function addText(mode, condition) { 564 | var text = ipe.options['text' + mode + 'Controls']; 565 | if (!text || condition === false) return; 566 | ipe._form.appendChild(document.createTextNode(text)); 567 | }; 568 | this._form = $(document.createElement('form')); 569 | this._form.id = this.options.formId; 570 | this._form.addClassName(this.options.formClassName); 571 | this._form.onsubmit = this._boundSubmitHandler; 572 | this.createEditField(); 573 | if ('textarea' == this._controls.editor.tagName.toLowerCase()) 574 | this._form.appendChild(document.createElement('br')); 575 | if (this.options.onFormCustomization) 576 | this.options.onFormCustomization(this, this._form); 577 | addText('Before', this.options.okControl || this.options.cancelControl); 578 | this.createControl('ok', this._boundSubmitHandler); 579 | addText('Between', this.options.okControl && this.options.cancelControl); 580 | this.createControl('cancel', this._boundCancelHandler, 'editor_cancel'); 581 | addText('After', this.options.okControl || this.options.cancelControl); 582 | }, 583 | destroy: function() { 584 | if (this._oldInnerHTML) 585 | this.element.innerHTML = this._oldInnerHTML; 586 | this.leaveEditMode(); 587 | this.unregisterListeners(); 588 | }, 589 | enterEditMode: function(e) { 590 | if (this._saving || this._editing) return; 591 | this._editing = true; 592 | this.triggerCallback('onEnterEditMode'); 593 | if (this.options.externalControl) 594 | this.options.externalControl.hide(); 595 | this.element.hide(); 596 | this.createForm(); 597 | this.element.parentNode.insertBefore(this._form, this.element); 598 | if (!this.options.loadTextURL) 599 | this.postProcessEditField(); 600 | if (e) Event.stop(e); 601 | }, 602 | enterHover: function(e) { 603 | if (this.options.hoverClassName) 604 | this.element.addClassName(this.options.hoverClassName); 605 | if (this._saving) return; 606 | this.triggerCallback('onEnterHover'); 607 | }, 608 | getText: function() { 609 | return this.element.innerHTML.unescapeHTML(); 610 | }, 611 | handleAJAXFailure: function(transport) { 612 | this.triggerCallback('onFailure', transport); 613 | if (this._oldInnerHTML) { 614 | this.element.innerHTML = this._oldInnerHTML; 615 | this._oldInnerHTML = null; 616 | } 617 | }, 618 | handleFormCancellation: function(e) { 619 | this.wrapUp(); 620 | if (e) Event.stop(e); 621 | }, 622 | handleFormSubmission: function(e) { 623 | var form = this._form; 624 | var value = $F(this._controls.editor); 625 | this.prepareSubmission(); 626 | var params = this.options.callback(form, value) || ''; 627 | if (Object.isString(params)) 628 | params = params.toQueryParams(); 629 | params.editorId = this.element.id; 630 | if (this.options.htmlResponse) { 631 | var options = Object.extend({ evalScripts: true }, this.options.ajaxOptions); 632 | Object.extend(options, { 633 | parameters: params, 634 | onComplete: this._boundWrapperHandler, 635 | onFailure: this._boundFailureHandler 636 | }); 637 | new Ajax.Updater({ success: this.element }, this.url, options); 638 | } else { 639 | var options = Object.extend({ method: 'get' }, this.options.ajaxOptions); 640 | Object.extend(options, { 641 | parameters: params, 642 | onComplete: this._boundWrapperHandler, 643 | onFailure: this._boundFailureHandler 644 | }); 645 | new Ajax.Request(this.url, options); 646 | } 647 | if (e) Event.stop(e); 648 | }, 649 | leaveEditMode: function() { 650 | this.element.removeClassName(this.options.savingClassName); 651 | this.removeForm(); 652 | this.leaveHover(); 653 | this.element.style.backgroundColor = this._originalBackground; 654 | this.element.show(); 655 | if (this.options.externalControl) 656 | this.options.externalControl.show(); 657 | this._saving = false; 658 | this._editing = false; 659 | this._oldInnerHTML = null; 660 | this.triggerCallback('onLeaveEditMode'); 661 | }, 662 | leaveHover: function(e) { 663 | if (this.options.hoverClassName) 664 | this.element.removeClassName(this.options.hoverClassName); 665 | if (this._saving) return; 666 | this.triggerCallback('onLeaveHover'); 667 | }, 668 | loadExternalText: function() { 669 | this._form.addClassName(this.options.loadingClassName); 670 | this._controls.editor.disabled = true; 671 | var options = Object.extend({ method: 'get' }, this.options.ajaxOptions); 672 | Object.extend(options, { 673 | parameters: 'editorId=' + encodeURIComponent(this.element.id), 674 | onComplete: Prototype.emptyFunction, 675 | onSuccess: function(transport) { 676 | this._form.removeClassName(this.options.loadingClassName); 677 | var text = transport.responseText; 678 | if (this.options.stripLoadedTextTags) 679 | text = text.stripTags(); 680 | this._controls.editor.value = text; 681 | this._controls.editor.disabled = false; 682 | this.postProcessEditField(); 683 | }.bind(this), 684 | onFailure: this._boundFailureHandler 685 | }); 686 | new Ajax.Request(this.options.loadTextURL, options); 687 | }, 688 | postProcessEditField: function() { 689 | var fpc = this.options.fieldPostCreation; 690 | if (fpc) 691 | $(this._controls.editor)['focus' == fpc ? 'focus' : 'activate'](); 692 | }, 693 | prepareOptions: function() { 694 | this.options = Object.clone(Ajax.InPlaceEditor.DefaultOptions); 695 | Object.extend(this.options, Ajax.InPlaceEditor.DefaultCallbacks); 696 | [this._extraDefaultOptions].flatten().compact().each(function(defs) { 697 | Object.extend(this.options, defs); 698 | }.bind(this)); 699 | }, 700 | prepareSubmission: function() { 701 | this._saving = true; 702 | this.removeForm(); 703 | this.leaveHover(); 704 | this.showSaving(); 705 | }, 706 | registerListeners: function() { 707 | this._listeners = { }; 708 | var listener; 709 | $H(Ajax.InPlaceEditor.Listeners).each(function(pair) { 710 | listener = this[pair.value].bind(this); 711 | this._listeners[pair.key] = listener; 712 | if (!this.options.externalControlOnly) 713 | this.element.observe(pair.key, listener); 714 | if (this.options.externalControl) 715 | this.options.externalControl.observe(pair.key, listener); 716 | }.bind(this)); 717 | }, 718 | removeForm: function() { 719 | if (!this._form) return; 720 | this._form.remove(); 721 | this._form = null; 722 | this._controls = { }; 723 | }, 724 | showSaving: function() { 725 | this._oldInnerHTML = this.element.innerHTML; 726 | this.element.innerHTML = this.options.savingText; 727 | this.element.addClassName(this.options.savingClassName); 728 | this.element.style.backgroundColor = this._originalBackground; 729 | this.element.show(); 730 | }, 731 | triggerCallback: function(cbName, arg) { 732 | if ('function' == typeof this.options[cbName]) { 733 | this.options[cbName](this, arg); 734 | } 735 | }, 736 | unregisterListeners: function() { 737 | $H(this._listeners).each(function(pair) { 738 | if (!this.options.externalControlOnly) 739 | this.element.stopObserving(pair.key, pair.value); 740 | if (this.options.externalControl) 741 | this.options.externalControl.stopObserving(pair.key, pair.value); 742 | }.bind(this)); 743 | }, 744 | wrapUp: function(transport) { 745 | this.leaveEditMode(); 746 | // Can't use triggerCallback due to backward compatibility: requires 747 | // binding + direct element 748 | this._boundComplete(transport, this.element); 749 | } 750 | }); 751 | 752 | Object.extend(Ajax.InPlaceEditor.prototype, { 753 | dispose: Ajax.InPlaceEditor.prototype.destroy 754 | }); 755 | 756 | Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, { 757 | initialize: function($super, element, url, options) { 758 | this._extraDefaultOptions = Ajax.InPlaceCollectionEditor.DefaultOptions; 759 | $super(element, url, options); 760 | }, 761 | 762 | createEditField: function() { 763 | var list = document.createElement('select'); 764 | list.name = this.options.paramName; 765 | list.size = 1; 766 | this._controls.editor = list; 767 | this._collection = this.options.collection || []; 768 | if (this.options.loadCollectionURL) 769 | this.loadCollection(); 770 | else 771 | this.checkForExternalText(); 772 | this._form.appendChild(this._controls.editor); 773 | }, 774 | 775 | loadCollection: function() { 776 | this._form.addClassName(this.options.loadingClassName); 777 | this.showLoadingText(this.options.loadingCollectionText); 778 | var options = Object.extend({ method: 'get' }, this.options.ajaxOptions); 779 | Object.extend(options, { 780 | parameters: 'editorId=' + encodeURIComponent(this.element.id), 781 | onComplete: Prototype.emptyFunction, 782 | onSuccess: function(transport) { 783 | var js = transport.responseText.strip(); 784 | if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check 785 | throw('Server returned an invalid collection representation.'); 786 | this._collection = eval(js); 787 | this.checkForExternalText(); 788 | }.bind(this), 789 | onFailure: this.onFailure 790 | }); 791 | new Ajax.Request(this.options.loadCollectionURL, options); 792 | }, 793 | 794 | showLoadingText: function(text) { 795 | this._controls.editor.disabled = true; 796 | var tempOption = this._controls.editor.firstChild; 797 | if (!tempOption) { 798 | tempOption = document.createElement('option'); 799 | tempOption.value = ''; 800 | this._controls.editor.appendChild(tempOption); 801 | tempOption.selected = true; 802 | } 803 | tempOption.update((text || '').stripScripts().stripTags()); 804 | }, 805 | 806 | checkForExternalText: function() { 807 | this._text = this.getText(); 808 | if (this.options.loadTextURL) 809 | this.loadExternalText(); 810 | else 811 | this.buildOptionList(); 812 | }, 813 | 814 | loadExternalText: function() { 815 | this.showLoadingText(this.options.loadingText); 816 | var options = Object.extend({ method: 'get' }, this.options.ajaxOptions); 817 | Object.extend(options, { 818 | parameters: 'editorId=' + encodeURIComponent(this.element.id), 819 | onComplete: Prototype.emptyFunction, 820 | onSuccess: function(transport) { 821 | this._text = transport.responseText.strip(); 822 | this.buildOptionList(); 823 | }.bind(this), 824 | onFailure: this.onFailure 825 | }); 826 | new Ajax.Request(this.options.loadTextURL, options); 827 | }, 828 | 829 | buildOptionList: function() { 830 | this._form.removeClassName(this.options.loadingClassName); 831 | this._collection = this._collection.map(function(entry) { 832 | return 2 === entry.length ? entry : [entry, entry].flatten(); 833 | }); 834 | var marker = ('value' in this.options) ? this.options.value : this._text; 835 | var textFound = this._collection.any(function(entry) { 836 | return entry[0] == marker; 837 | }.bind(this)); 838 | this._controls.editor.update(''); 839 | var option; 840 | this._collection.each(function(entry, index) { 841 | option = document.createElement('option'); 842 | option.value = entry[0]; 843 | option.selected = textFound ? entry[0] == marker : 0 == index; 844 | option.appendChild(document.createTextNode(entry[1])); 845 | this._controls.editor.appendChild(option); 846 | }.bind(this)); 847 | this._controls.editor.disabled = false; 848 | Field.scrollFreeActivate(this._controls.editor); 849 | } 850 | }); 851 | 852 | //**** DEPRECATION LAYER FOR InPlace[Collection]Editor! **** 853 | //**** This only exists for a while, in order to let **** 854 | //**** users adapt to the new API. Read up on the new **** 855 | //**** API and convert your code to it ASAP! **** 856 | 857 | Ajax.InPlaceEditor.prototype.initialize.dealWithDeprecatedOptions = function(options) { 858 | if (!options) return; 859 | function fallback(name, expr) { 860 | if (name in options || expr === undefined) return; 861 | options[name] = expr; 862 | }; 863 | fallback('cancelControl', (options.cancelLink ? 'link' : (options.cancelButton ? 'button' : 864 | options.cancelLink == options.cancelButton == false ? false : undefined))); 865 | fallback('okControl', (options.okLink ? 'link' : (options.okButton ? 'button' : 866 | options.okLink == options.okButton == false ? false : undefined))); 867 | fallback('highlightColor', options.highlightcolor); 868 | fallback('highlightEndColor', options.highlightendcolor); 869 | }; 870 | 871 | Object.extend(Ajax.InPlaceEditor, { 872 | DefaultOptions: { 873 | ajaxOptions: { }, 874 | autoRows: 3, // Use when multi-line w/ rows == 1 875 | cancelControl: 'link', // 'link'|'button'|false 876 | cancelText: 'cancel', 877 | clickToEditText: 'Click to edit', 878 | externalControl: null, // id|elt 879 | externalControlOnly: false, 880 | fieldPostCreation: 'activate', // 'activate'|'focus'|false 881 | formClassName: 'inplaceeditor-form', 882 | formId: null, // id|elt 883 | highlightColor: '#ffff99', 884 | highlightEndColor: '#ffffff', 885 | hoverClassName: '', 886 | htmlResponse: true, 887 | loadingClassName: 'inplaceeditor-loading', 888 | loadingText: 'Loading...', 889 | okControl: 'button', // 'link'|'button'|false 890 | okText: 'ok', 891 | paramName: 'value', 892 | rows: 1, // If 1 and multi-line, uses autoRows 893 | savingClassName: 'inplaceeditor-saving', 894 | savingText: 'Saving...', 895 | size: 0, 896 | stripLoadedTextTags: false, 897 | submitOnBlur: false, 898 | textAfterControls: '', 899 | textBeforeControls: '', 900 | textBetweenControls: '' 901 | }, 902 | DefaultCallbacks: { 903 | callback: function(form) { 904 | return Form.serialize(form); 905 | }, 906 | onComplete: function(transport, element) { 907 | // For backward compatibility, this one is bound to the IPE, and passes 908 | // the element directly. It was too often customized, so we don't break it. 909 | new Effect.Highlight(element, { 910 | startcolor: this.options.highlightColor, keepBackgroundImage: true }); 911 | }, 912 | onEnterEditMode: null, 913 | onEnterHover: function(ipe) { 914 | ipe.element.style.backgroundColor = ipe.options.highlightColor; 915 | if (ipe._effect) 916 | ipe._effect.cancel(); 917 | }, 918 | onFailure: function(transport, ipe) { 919 | alert('Error communication with the server: ' + transport.responseText.stripTags()); 920 | }, 921 | onFormCustomization: null, // Takes the IPE and its generated form, after editor, before controls. 922 | onLeaveEditMode: null, 923 | onLeaveHover: function(ipe) { 924 | ipe._effect = new Effect.Highlight(ipe.element, { 925 | startcolor: ipe.options.highlightColor, endcolor: ipe.options.highlightEndColor, 926 | restorecolor: ipe._originalBackground, keepBackgroundImage: true 927 | }); 928 | } 929 | }, 930 | Listeners: { 931 | click: 'enterEditMode', 932 | keydown: 'checkForEscapeOrReturn', 933 | mouseover: 'enterHover', 934 | mouseout: 'leaveHover' 935 | } 936 | }); 937 | 938 | Ajax.InPlaceCollectionEditor.DefaultOptions = { 939 | loadingCollectionText: 'Loading options...' 940 | }; 941 | 942 | // Delayed observer, like Form.Element.Observer, 943 | // but waits for delay after last key input 944 | // Ideal for live-search fields 945 | 946 | Form.Element.DelayedObserver = Class.create({ 947 | initialize: function(element, delay, callback) { 948 | this.delay = delay || 0.5; 949 | this.element = $(element); 950 | this.callback = callback; 951 | this.timer = null; 952 | this.lastValue = $F(this.element); 953 | Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this)); 954 | }, 955 | delayedListener: function(event) { 956 | if(this.lastValue == $F(this.element)) return; 957 | if(this.timer) clearTimeout(this.timer); 958 | this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000); 959 | this.lastValue = $F(this.element); 960 | }, 961 | onTimerEvent: function() { 962 | this.timer = null; 963 | this.callback(this.element, $F(this.element)); 964 | } 965 | }); -------------------------------------------------------------------------------- /spec/rails_app/public/javascripts/dragdrop.js: -------------------------------------------------------------------------------- 1 | // script.aculo.us dragdrop.js v1.8.3, Thu Oct 08 11:23:33 +0200 2009 2 | 3 | // Copyright (c) 2005-2009 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) 4 | // 5 | // script.aculo.us is freely distributable under the terms of an MIT-style license. 6 | // For details, see the script.aculo.us web site: http://script.aculo.us/ 7 | 8 | if(Object.isUndefined(Effect)) 9 | throw("dragdrop.js requires including script.aculo.us' effects.js library"); 10 | 11 | var Droppables = { 12 | drops: [], 13 | 14 | remove: function(element) { 15 | this.drops = this.drops.reject(function(d) { return d.element==$(element) }); 16 | }, 17 | 18 | add: function(element) { 19 | element = $(element); 20 | var options = Object.extend({ 21 | greedy: true, 22 | hoverclass: null, 23 | tree: false 24 | }, arguments[1] || { }); 25 | 26 | // cache containers 27 | if(options.containment) { 28 | options._containers = []; 29 | var containment = options.containment; 30 | if(Object.isArray(containment)) { 31 | containment.each( function(c) { options._containers.push($(c)) }); 32 | } else { 33 | options._containers.push($(containment)); 34 | } 35 | } 36 | 37 | if(options.accept) options.accept = [options.accept].flatten(); 38 | 39 | Element.makePositioned(element); // fix IE 40 | options.element = element; 41 | 42 | this.drops.push(options); 43 | }, 44 | 45 | findDeepestChild: function(drops) { 46 | deepest = drops[0]; 47 | 48 | for (i = 1; i < drops.length; ++i) 49 | if (Element.isParent(drops[i].element, deepest.element)) 50 | deepest = drops[i]; 51 | 52 | return deepest; 53 | }, 54 | 55 | isContained: function(element, drop) { 56 | var containmentNode; 57 | if(drop.tree) { 58 | containmentNode = element.treeNode; 59 | } else { 60 | containmentNode = element.parentNode; 61 | } 62 | return drop._containers.detect(function(c) { return containmentNode == c }); 63 | }, 64 | 65 | isAffected: function(point, element, drop) { 66 | return ( 67 | (drop.element!=element) && 68 | ((!drop._containers) || 69 | this.isContained(element, drop)) && 70 | ((!drop.accept) || 71 | (Element.classNames(element).detect( 72 | function(v) { return drop.accept.include(v) } ) )) && 73 | Position.within(drop.element, point[0], point[1]) ); 74 | }, 75 | 76 | deactivate: function(drop) { 77 | if(drop.hoverclass) 78 | Element.removeClassName(drop.element, drop.hoverclass); 79 | this.last_active = null; 80 | }, 81 | 82 | activate: function(drop) { 83 | if(drop.hoverclass) 84 | Element.addClassName(drop.element, drop.hoverclass); 85 | this.last_active = drop; 86 | }, 87 | 88 | show: function(point, element) { 89 | if(!this.drops.length) return; 90 | var drop, affected = []; 91 | 92 | this.drops.each( function(drop) { 93 | if(Droppables.isAffected(point, element, drop)) 94 | affected.push(drop); 95 | }); 96 | 97 | if(affected.length>0) 98 | drop = Droppables.findDeepestChild(affected); 99 | 100 | if(this.last_active && this.last_active != drop) this.deactivate(this.last_active); 101 | if (drop) { 102 | Position.within(drop.element, point[0], point[1]); 103 | if(drop.onHover) 104 | drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element)); 105 | 106 | if (drop != this.last_active) Droppables.activate(drop); 107 | } 108 | }, 109 | 110 | fire: function(event, element) { 111 | if(!this.last_active) return; 112 | Position.prepare(); 113 | 114 | if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active)) 115 | if (this.last_active.onDrop) { 116 | this.last_active.onDrop(element, this.last_active.element, event); 117 | return true; 118 | } 119 | }, 120 | 121 | reset: function() { 122 | if(this.last_active) 123 | this.deactivate(this.last_active); 124 | } 125 | }; 126 | 127 | var Draggables = { 128 | drags: [], 129 | observers: [], 130 | 131 | register: function(draggable) { 132 | if(this.drags.length == 0) { 133 | this.eventMouseUp = this.endDrag.bindAsEventListener(this); 134 | this.eventMouseMove = this.updateDrag.bindAsEventListener(this); 135 | this.eventKeypress = this.keyPress.bindAsEventListener(this); 136 | 137 | Event.observe(document, "mouseup", this.eventMouseUp); 138 | Event.observe(document, "mousemove", this.eventMouseMove); 139 | Event.observe(document, "keypress", this.eventKeypress); 140 | } 141 | this.drags.push(draggable); 142 | }, 143 | 144 | unregister: function(draggable) { 145 | this.drags = this.drags.reject(function(d) { return d==draggable }); 146 | if(this.drags.length == 0) { 147 | Event.stopObserving(document, "mouseup", this.eventMouseUp); 148 | Event.stopObserving(document, "mousemove", this.eventMouseMove); 149 | Event.stopObserving(document, "keypress", this.eventKeypress); 150 | } 151 | }, 152 | 153 | activate: function(draggable) { 154 | if(draggable.options.delay) { 155 | this._timeout = setTimeout(function() { 156 | Draggables._timeout = null; 157 | window.focus(); 158 | Draggables.activeDraggable = draggable; 159 | }.bind(this), draggable.options.delay); 160 | } else { 161 | window.focus(); // allows keypress events if window isn't currently focused, fails for Safari 162 | this.activeDraggable = draggable; 163 | } 164 | }, 165 | 166 | deactivate: function() { 167 | this.activeDraggable = null; 168 | }, 169 | 170 | updateDrag: function(event) { 171 | if(!this.activeDraggable) return; 172 | var pointer = [Event.pointerX(event), Event.pointerY(event)]; 173 | // Mozilla-based browsers fire successive mousemove events with 174 | // the same coordinates, prevent needless redrawing (moz bug?) 175 | if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return; 176 | this._lastPointer = pointer; 177 | 178 | this.activeDraggable.updateDrag(event, pointer); 179 | }, 180 | 181 | endDrag: function(event) { 182 | if(this._timeout) { 183 | clearTimeout(this._timeout); 184 | this._timeout = null; 185 | } 186 | if(!this.activeDraggable) return; 187 | this._lastPointer = null; 188 | this.activeDraggable.endDrag(event); 189 | this.activeDraggable = null; 190 | }, 191 | 192 | keyPress: function(event) { 193 | if(this.activeDraggable) 194 | this.activeDraggable.keyPress(event); 195 | }, 196 | 197 | addObserver: function(observer) { 198 | this.observers.push(observer); 199 | this._cacheObserverCallbacks(); 200 | }, 201 | 202 | removeObserver: function(element) { // element instead of observer fixes mem leaks 203 | this.observers = this.observers.reject( function(o) { return o.element==element }); 204 | this._cacheObserverCallbacks(); 205 | }, 206 | 207 | notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag' 208 | if(this[eventName+'Count'] > 0) 209 | this.observers.each( function(o) { 210 | if(o[eventName]) o[eventName](eventName, draggable, event); 211 | }); 212 | if(draggable.options[eventName]) draggable.options[eventName](draggable, event); 213 | }, 214 | 215 | _cacheObserverCallbacks: function() { 216 | ['onStart','onEnd','onDrag'].each( function(eventName) { 217 | Draggables[eventName+'Count'] = Draggables.observers.select( 218 | function(o) { return o[eventName]; } 219 | ).length; 220 | }); 221 | } 222 | }; 223 | 224 | /*--------------------------------------------------------------------------*/ 225 | 226 | var Draggable = Class.create({ 227 | initialize: function(element) { 228 | var defaults = { 229 | handle: false, 230 | reverteffect: function(element, top_offset, left_offset) { 231 | var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02; 232 | new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur, 233 | queue: {scope:'_draggable', position:'end'} 234 | }); 235 | }, 236 | endeffect: function(element) { 237 | var toOpacity = Object.isNumber(element._opacity) ? element._opacity : 1.0; 238 | new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity, 239 | queue: {scope:'_draggable', position:'end'}, 240 | afterFinish: function(){ 241 | Draggable._dragging[element] = false 242 | } 243 | }); 244 | }, 245 | zindex: 1000, 246 | revert: false, 247 | quiet: false, 248 | scroll: false, 249 | scrollSensitivity: 20, 250 | scrollSpeed: 15, 251 | snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] } 252 | delay: 0 253 | }; 254 | 255 | if(!arguments[1] || Object.isUndefined(arguments[1].endeffect)) 256 | Object.extend(defaults, { 257 | starteffect: function(element) { 258 | element._opacity = Element.getOpacity(element); 259 | Draggable._dragging[element] = true; 260 | new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7}); 261 | } 262 | }); 263 | 264 | var options = Object.extend(defaults, arguments[1] || { }); 265 | 266 | this.element = $(element); 267 | 268 | if(options.handle && Object.isString(options.handle)) 269 | this.handle = this.element.down('.'+options.handle, 0); 270 | 271 | if(!this.handle) this.handle = $(options.handle); 272 | if(!this.handle) this.handle = this.element; 273 | 274 | if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) { 275 | options.scroll = $(options.scroll); 276 | this._isScrollChild = Element.childOf(this.element, options.scroll); 277 | } 278 | 279 | Element.makePositioned(this.element); // fix IE 280 | 281 | this.options = options; 282 | this.dragging = false; 283 | 284 | this.eventMouseDown = this.initDrag.bindAsEventListener(this); 285 | Event.observe(this.handle, "mousedown", this.eventMouseDown); 286 | 287 | Draggables.register(this); 288 | }, 289 | 290 | destroy: function() { 291 | Event.stopObserving(this.handle, "mousedown", this.eventMouseDown); 292 | Draggables.unregister(this); 293 | }, 294 | 295 | currentDelta: function() { 296 | return([ 297 | parseInt(Element.getStyle(this.element,'left') || '0'), 298 | parseInt(Element.getStyle(this.element,'top') || '0')]); 299 | }, 300 | 301 | initDrag: function(event) { 302 | if(!Object.isUndefined(Draggable._dragging[this.element]) && 303 | Draggable._dragging[this.element]) return; 304 | if(Event.isLeftClick(event)) { 305 | // abort on form elements, fixes a Firefox issue 306 | var src = Event.element(event); 307 | if((tag_name = src.tagName.toUpperCase()) && ( 308 | tag_name=='INPUT' || 309 | tag_name=='SELECT' || 310 | tag_name=='OPTION' || 311 | tag_name=='BUTTON' || 312 | tag_name=='TEXTAREA')) return; 313 | 314 | var pointer = [Event.pointerX(event), Event.pointerY(event)]; 315 | var pos = this.element.cumulativeOffset(); 316 | this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) }); 317 | 318 | Draggables.activate(this); 319 | Event.stop(event); 320 | } 321 | }, 322 | 323 | startDrag: function(event) { 324 | this.dragging = true; 325 | if(!this.delta) 326 | this.delta = this.currentDelta(); 327 | 328 | if(this.options.zindex) { 329 | this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0); 330 | this.element.style.zIndex = this.options.zindex; 331 | } 332 | 333 | if(this.options.ghosting) { 334 | this._clone = this.element.cloneNode(true); 335 | this._originallyAbsolute = (this.element.getStyle('position') == 'absolute'); 336 | if (!this._originallyAbsolute) 337 | Position.absolutize(this.element); 338 | this.element.parentNode.insertBefore(this._clone, this.element); 339 | } 340 | 341 | if(this.options.scroll) { 342 | if (this.options.scroll == window) { 343 | var where = this._getWindowScroll(this.options.scroll); 344 | this.originalScrollLeft = where.left; 345 | this.originalScrollTop = where.top; 346 | } else { 347 | this.originalScrollLeft = this.options.scroll.scrollLeft; 348 | this.originalScrollTop = this.options.scroll.scrollTop; 349 | } 350 | } 351 | 352 | Draggables.notify('onStart', this, event); 353 | 354 | if(this.options.starteffect) this.options.starteffect(this.element); 355 | }, 356 | 357 | updateDrag: function(event, pointer) { 358 | if(!this.dragging) this.startDrag(event); 359 | 360 | if(!this.options.quiet){ 361 | Position.prepare(); 362 | Droppables.show(pointer, this.element); 363 | } 364 | 365 | Draggables.notify('onDrag', this, event); 366 | 367 | this.draw(pointer); 368 | if(this.options.change) this.options.change(this); 369 | 370 | if(this.options.scroll) { 371 | this.stopScrolling(); 372 | 373 | var p; 374 | if (this.options.scroll == window) { 375 | with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; } 376 | } else { 377 | p = Position.page(this.options.scroll); 378 | p[0] += this.options.scroll.scrollLeft + Position.deltaX; 379 | p[1] += this.options.scroll.scrollTop + Position.deltaY; 380 | p.push(p[0]+this.options.scroll.offsetWidth); 381 | p.push(p[1]+this.options.scroll.offsetHeight); 382 | } 383 | var speed = [0,0]; 384 | if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity); 385 | if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity); 386 | if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity); 387 | if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity); 388 | this.startScrolling(speed); 389 | } 390 | 391 | // fix AppleWebKit rendering 392 | if(Prototype.Browser.WebKit) window.scrollBy(0,0); 393 | 394 | Event.stop(event); 395 | }, 396 | 397 | finishDrag: function(event, success) { 398 | this.dragging = false; 399 | 400 | if(this.options.quiet){ 401 | Position.prepare(); 402 | var pointer = [Event.pointerX(event), Event.pointerY(event)]; 403 | Droppables.show(pointer, this.element); 404 | } 405 | 406 | if(this.options.ghosting) { 407 | if (!this._originallyAbsolute) 408 | Position.relativize(this.element); 409 | delete this._originallyAbsolute; 410 | Element.remove(this._clone); 411 | this._clone = null; 412 | } 413 | 414 | var dropped = false; 415 | if(success) { 416 | dropped = Droppables.fire(event, this.element); 417 | if (!dropped) dropped = false; 418 | } 419 | if(dropped && this.options.onDropped) this.options.onDropped(this.element); 420 | Draggables.notify('onEnd', this, event); 421 | 422 | var revert = this.options.revert; 423 | if(revert && Object.isFunction(revert)) revert = revert(this.element); 424 | 425 | var d = this.currentDelta(); 426 | if(revert && this.options.reverteffect) { 427 | if (dropped == 0 || revert != 'failure') 428 | this.options.reverteffect(this.element, 429 | d[1]-this.delta[1], d[0]-this.delta[0]); 430 | } else { 431 | this.delta = d; 432 | } 433 | 434 | if(this.options.zindex) 435 | this.element.style.zIndex = this.originalZ; 436 | 437 | if(this.options.endeffect) 438 | this.options.endeffect(this.element); 439 | 440 | Draggables.deactivate(this); 441 | Droppables.reset(); 442 | }, 443 | 444 | keyPress: function(event) { 445 | if(event.keyCode!=Event.KEY_ESC) return; 446 | this.finishDrag(event, false); 447 | Event.stop(event); 448 | }, 449 | 450 | endDrag: function(event) { 451 | if(!this.dragging) return; 452 | this.stopScrolling(); 453 | this.finishDrag(event, true); 454 | Event.stop(event); 455 | }, 456 | 457 | draw: function(point) { 458 | var pos = this.element.cumulativeOffset(); 459 | if(this.options.ghosting) { 460 | var r = Position.realOffset(this.element); 461 | pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY; 462 | } 463 | 464 | var d = this.currentDelta(); 465 | pos[0] -= d[0]; pos[1] -= d[1]; 466 | 467 | if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) { 468 | pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft; 469 | pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop; 470 | } 471 | 472 | var p = [0,1].map(function(i){ 473 | return (point[i]-pos[i]-this.offset[i]) 474 | }.bind(this)); 475 | 476 | if(this.options.snap) { 477 | if(Object.isFunction(this.options.snap)) { 478 | p = this.options.snap(p[0],p[1],this); 479 | } else { 480 | if(Object.isArray(this.options.snap)) { 481 | p = p.map( function(v, i) { 482 | return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this)); 483 | } else { 484 | p = p.map( function(v) { 485 | return (v/this.options.snap).round()*this.options.snap }.bind(this)); 486 | } 487 | }} 488 | 489 | var style = this.element.style; 490 | if((!this.options.constraint) || (this.options.constraint=='horizontal')) 491 | style.left = p[0] + "px"; 492 | if((!this.options.constraint) || (this.options.constraint=='vertical')) 493 | style.top = p[1] + "px"; 494 | 495 | if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering 496 | }, 497 | 498 | stopScrolling: function() { 499 | if(this.scrollInterval) { 500 | clearInterval(this.scrollInterval); 501 | this.scrollInterval = null; 502 | Draggables._lastScrollPointer = null; 503 | } 504 | }, 505 | 506 | startScrolling: function(speed) { 507 | if(!(speed[0] || speed[1])) return; 508 | this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed]; 509 | this.lastScrolled = new Date(); 510 | this.scrollInterval = setInterval(this.scroll.bind(this), 10); 511 | }, 512 | 513 | scroll: function() { 514 | var current = new Date(); 515 | var delta = current - this.lastScrolled; 516 | this.lastScrolled = current; 517 | if(this.options.scroll == window) { 518 | with (this._getWindowScroll(this.options.scroll)) { 519 | if (this.scrollSpeed[0] || this.scrollSpeed[1]) { 520 | var d = delta / 1000; 521 | this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] ); 522 | } 523 | } 524 | } else { 525 | this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000; 526 | this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000; 527 | } 528 | 529 | Position.prepare(); 530 | Droppables.show(Draggables._lastPointer, this.element); 531 | Draggables.notify('onDrag', this); 532 | if (this._isScrollChild) { 533 | Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer); 534 | Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000; 535 | Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000; 536 | if (Draggables._lastScrollPointer[0] < 0) 537 | Draggables._lastScrollPointer[0] = 0; 538 | if (Draggables._lastScrollPointer[1] < 0) 539 | Draggables._lastScrollPointer[1] = 0; 540 | this.draw(Draggables._lastScrollPointer); 541 | } 542 | 543 | if(this.options.change) this.options.change(this); 544 | }, 545 | 546 | _getWindowScroll: function(w) { 547 | var T, L, W, H; 548 | with (w.document) { 549 | if (w.document.documentElement && documentElement.scrollTop) { 550 | T = documentElement.scrollTop; 551 | L = documentElement.scrollLeft; 552 | } else if (w.document.body) { 553 | T = body.scrollTop; 554 | L = body.scrollLeft; 555 | } 556 | if (w.innerWidth) { 557 | W = w.innerWidth; 558 | H = w.innerHeight; 559 | } else if (w.document.documentElement && documentElement.clientWidth) { 560 | W = documentElement.clientWidth; 561 | H = documentElement.clientHeight; 562 | } else { 563 | W = body.offsetWidth; 564 | H = body.offsetHeight; 565 | } 566 | } 567 | return { top: T, left: L, width: W, height: H }; 568 | } 569 | }); 570 | 571 | Draggable._dragging = { }; 572 | 573 | /*--------------------------------------------------------------------------*/ 574 | 575 | var SortableObserver = Class.create({ 576 | initialize: function(element, observer) { 577 | this.element = $(element); 578 | this.observer = observer; 579 | this.lastValue = Sortable.serialize(this.element); 580 | }, 581 | 582 | onStart: function() { 583 | this.lastValue = Sortable.serialize(this.element); 584 | }, 585 | 586 | onEnd: function() { 587 | Sortable.unmark(); 588 | if(this.lastValue != Sortable.serialize(this.element)) 589 | this.observer(this.element) 590 | } 591 | }); 592 | 593 | var Sortable = { 594 | SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/, 595 | 596 | sortables: { }, 597 | 598 | _findRootElement: function(element) { 599 | while (element.tagName.toUpperCase() != "BODY") { 600 | if(element.id && Sortable.sortables[element.id]) return element; 601 | element = element.parentNode; 602 | } 603 | }, 604 | 605 | options: function(element) { 606 | element = Sortable._findRootElement($(element)); 607 | if(!element) return; 608 | return Sortable.sortables[element.id]; 609 | }, 610 | 611 | destroy: function(element){ 612 | element = $(element); 613 | var s = Sortable.sortables[element.id]; 614 | 615 | if(s) { 616 | Draggables.removeObserver(s.element); 617 | s.droppables.each(function(d){ Droppables.remove(d) }); 618 | s.draggables.invoke('destroy'); 619 | 620 | delete Sortable.sortables[s.element.id]; 621 | } 622 | }, 623 | 624 | create: function(element) { 625 | element = $(element); 626 | var options = Object.extend({ 627 | element: element, 628 | tag: 'li', // assumes li children, override with tag: 'tagname' 629 | dropOnEmpty: false, 630 | tree: false, 631 | treeTag: 'ul', 632 | overlap: 'vertical', // one of 'vertical', 'horizontal' 633 | constraint: 'vertical', // one of 'vertical', 'horizontal', false 634 | containment: element, // also takes array of elements (or id's); or false 635 | handle: false, // or a CSS class 636 | only: false, 637 | delay: 0, 638 | hoverclass: null, 639 | ghosting: false, 640 | quiet: false, 641 | scroll: false, 642 | scrollSensitivity: 20, 643 | scrollSpeed: 15, 644 | format: this.SERIALIZE_RULE, 645 | 646 | // these take arrays of elements or ids and can be 647 | // used for better initialization performance 648 | elements: false, 649 | handles: false, 650 | 651 | onChange: Prototype.emptyFunction, 652 | onUpdate: Prototype.emptyFunction 653 | }, arguments[1] || { }); 654 | 655 | // clear any old sortable with same element 656 | this.destroy(element); 657 | 658 | // build options for the draggables 659 | var options_for_draggable = { 660 | revert: true, 661 | quiet: options.quiet, 662 | scroll: options.scroll, 663 | scrollSpeed: options.scrollSpeed, 664 | scrollSensitivity: options.scrollSensitivity, 665 | delay: options.delay, 666 | ghosting: options.ghosting, 667 | constraint: options.constraint, 668 | handle: options.handle }; 669 | 670 | if(options.starteffect) 671 | options_for_draggable.starteffect = options.starteffect; 672 | 673 | if(options.reverteffect) 674 | options_for_draggable.reverteffect = options.reverteffect; 675 | else 676 | if(options.ghosting) options_for_draggable.reverteffect = function(element) { 677 | element.style.top = 0; 678 | element.style.left = 0; 679 | }; 680 | 681 | if(options.endeffect) 682 | options_for_draggable.endeffect = options.endeffect; 683 | 684 | if(options.zindex) 685 | options_for_draggable.zindex = options.zindex; 686 | 687 | // build options for the droppables 688 | var options_for_droppable = { 689 | overlap: options.overlap, 690 | containment: options.containment, 691 | tree: options.tree, 692 | hoverclass: options.hoverclass, 693 | onHover: Sortable.onHover 694 | }; 695 | 696 | var options_for_tree = { 697 | onHover: Sortable.onEmptyHover, 698 | overlap: options.overlap, 699 | containment: options.containment, 700 | hoverclass: options.hoverclass 701 | }; 702 | 703 | // fix for gecko engine 704 | Element.cleanWhitespace(element); 705 | 706 | options.draggables = []; 707 | options.droppables = []; 708 | 709 | // drop on empty handling 710 | if(options.dropOnEmpty || options.tree) { 711 | Droppables.add(element, options_for_tree); 712 | options.droppables.push(element); 713 | } 714 | 715 | (options.elements || this.findElements(element, options) || []).each( function(e,i) { 716 | var handle = options.handles ? $(options.handles[i]) : 717 | (options.handle ? $(e).select('.' + options.handle)[0] : e); 718 | options.draggables.push( 719 | new Draggable(e, Object.extend(options_for_draggable, { handle: handle }))); 720 | Droppables.add(e, options_for_droppable); 721 | if(options.tree) e.treeNode = element; 722 | options.droppables.push(e); 723 | }); 724 | 725 | if(options.tree) { 726 | (Sortable.findTreeElements(element, options) || []).each( function(e) { 727 | Droppables.add(e, options_for_tree); 728 | e.treeNode = element; 729 | options.droppables.push(e); 730 | }); 731 | } 732 | 733 | // keep reference 734 | this.sortables[element.identify()] = options; 735 | 736 | // for onupdate 737 | Draggables.addObserver(new SortableObserver(element, options.onUpdate)); 738 | 739 | }, 740 | 741 | // return all suitable-for-sortable elements in a guaranteed order 742 | findElements: function(element, options) { 743 | return Element.findChildren( 744 | element, options.only, options.tree ? true : false, options.tag); 745 | }, 746 | 747 | findTreeElements: function(element, options) { 748 | return Element.findChildren( 749 | element, options.only, options.tree ? true : false, options.treeTag); 750 | }, 751 | 752 | onHover: function(element, dropon, overlap) { 753 | if(Element.isParent(dropon, element)) return; 754 | 755 | if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) { 756 | return; 757 | } else if(overlap>0.5) { 758 | Sortable.mark(dropon, 'before'); 759 | if(dropon.previousSibling != element) { 760 | var oldParentNode = element.parentNode; 761 | element.style.visibility = "hidden"; // fix gecko rendering 762 | dropon.parentNode.insertBefore(element, dropon); 763 | if(dropon.parentNode!=oldParentNode) 764 | Sortable.options(oldParentNode).onChange(element); 765 | Sortable.options(dropon.parentNode).onChange(element); 766 | } 767 | } else { 768 | Sortable.mark(dropon, 'after'); 769 | var nextElement = dropon.nextSibling || null; 770 | if(nextElement != element) { 771 | var oldParentNode = element.parentNode; 772 | element.style.visibility = "hidden"; // fix gecko rendering 773 | dropon.parentNode.insertBefore(element, nextElement); 774 | if(dropon.parentNode!=oldParentNode) 775 | Sortable.options(oldParentNode).onChange(element); 776 | Sortable.options(dropon.parentNode).onChange(element); 777 | } 778 | } 779 | }, 780 | 781 | onEmptyHover: function(element, dropon, overlap) { 782 | var oldParentNode = element.parentNode; 783 | var droponOptions = Sortable.options(dropon); 784 | 785 | if(!Element.isParent(dropon, element)) { 786 | var index; 787 | 788 | var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only}); 789 | var child = null; 790 | 791 | if(children) { 792 | var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap); 793 | 794 | for (index = 0; index < children.length; index += 1) { 795 | if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) { 796 | offset -= Element.offsetSize (children[index], droponOptions.overlap); 797 | } else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) { 798 | child = index + 1 < children.length ? children[index + 1] : null; 799 | break; 800 | } else { 801 | child = children[index]; 802 | break; 803 | } 804 | } 805 | } 806 | 807 | dropon.insertBefore(element, child); 808 | 809 | Sortable.options(oldParentNode).onChange(element); 810 | droponOptions.onChange(element); 811 | } 812 | }, 813 | 814 | unmark: function() { 815 | if(Sortable._marker) Sortable._marker.hide(); 816 | }, 817 | 818 | mark: function(dropon, position) { 819 | // mark on ghosting only 820 | var sortable = Sortable.options(dropon.parentNode); 821 | if(sortable && !sortable.ghosting) return; 822 | 823 | if(!Sortable._marker) { 824 | Sortable._marker = 825 | ($('dropmarker') || Element.extend(document.createElement('DIV'))). 826 | hide().addClassName('dropmarker').setStyle({position:'absolute'}); 827 | document.getElementsByTagName("body").item(0).appendChild(Sortable._marker); 828 | } 829 | var offsets = dropon.cumulativeOffset(); 830 | Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'}); 831 | 832 | if(position=='after') 833 | if(sortable.overlap == 'horizontal') 834 | Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'}); 835 | else 836 | Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'}); 837 | 838 | Sortable._marker.show(); 839 | }, 840 | 841 | _tree: function(element, options, parent) { 842 | var children = Sortable.findElements(element, options) || []; 843 | 844 | for (var i = 0; i < children.length; ++i) { 845 | var match = children[i].id.match(options.format); 846 | 847 | if (!match) continue; 848 | 849 | var child = { 850 | id: encodeURIComponent(match ? match[1] : null), 851 | element: element, 852 | parent: parent, 853 | children: [], 854 | position: parent.children.length, 855 | container: $(children[i]).down(options.treeTag) 856 | }; 857 | 858 | /* Get the element containing the children and recurse over it */ 859 | if (child.container) 860 | this._tree(child.container, options, child); 861 | 862 | parent.children.push (child); 863 | } 864 | 865 | return parent; 866 | }, 867 | 868 | tree: function(element) { 869 | element = $(element); 870 | var sortableOptions = this.options(element); 871 | var options = Object.extend({ 872 | tag: sortableOptions.tag, 873 | treeTag: sortableOptions.treeTag, 874 | only: sortableOptions.only, 875 | name: element.id, 876 | format: sortableOptions.format 877 | }, arguments[1] || { }); 878 | 879 | var root = { 880 | id: null, 881 | parent: null, 882 | children: [], 883 | container: element, 884 | position: 0 885 | }; 886 | 887 | return Sortable._tree(element, options, root); 888 | }, 889 | 890 | /* Construct a [i] index for a particular node */ 891 | _constructIndex: function(node) { 892 | var index = ''; 893 | do { 894 | if (node.id) index = '[' + node.position + ']' + index; 895 | } while ((node = node.parent) != null); 896 | return index; 897 | }, 898 | 899 | sequence: function(element) { 900 | element = $(element); 901 | var options = Object.extend(this.options(element), arguments[1] || { }); 902 | 903 | return $(this.findElements(element, options) || []).map( function(item) { 904 | return item.id.match(options.format) ? item.id.match(options.format)[1] : ''; 905 | }); 906 | }, 907 | 908 | setSequence: function(element, new_sequence) { 909 | element = $(element); 910 | var options = Object.extend(this.options(element), arguments[2] || { }); 911 | 912 | var nodeMap = { }; 913 | this.findElements(element, options).each( function(n) { 914 | if (n.id.match(options.format)) 915 | nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode]; 916 | n.parentNode.removeChild(n); 917 | }); 918 | 919 | new_sequence.each(function(ident) { 920 | var n = nodeMap[ident]; 921 | if (n) { 922 | n[1].appendChild(n[0]); 923 | delete nodeMap[ident]; 924 | } 925 | }); 926 | }, 927 | 928 | serialize: function(element) { 929 | element = $(element); 930 | var options = Object.extend(Sortable.options(element), arguments[1] || { }); 931 | var name = encodeURIComponent( 932 | (arguments[1] && arguments[1].name) ? arguments[1].name : element.id); 933 | 934 | if (options.tree) { 935 | return Sortable.tree(element, arguments[1]).children.map( function (item) { 936 | return [name + Sortable._constructIndex(item) + "[id]=" + 937 | encodeURIComponent(item.id)].concat(item.children.map(arguments.callee)); 938 | }).flatten().join('&'); 939 | } else { 940 | return Sortable.sequence(element, arguments[1]).map( function(item) { 941 | return name + "[]=" + encodeURIComponent(item); 942 | }).join('&'); 943 | } 944 | } 945 | }; 946 | 947 | // Returns true if child is contained within element 948 | Element.isParent = function(child, element) { 949 | if (!child.parentNode || child == element) return false; 950 | if (child.parentNode == element) return true; 951 | return Element.isParent(child.parentNode, element); 952 | }; 953 | 954 | Element.findChildren = function(element, only, recursive, tagName) { 955 | if(!element.hasChildNodes()) return null; 956 | tagName = tagName.toUpperCase(); 957 | if(only) only = [only].flatten(); 958 | var elements = []; 959 | $A(element.childNodes).each( function(e) { 960 | if(e.tagName && e.tagName.toUpperCase()==tagName && 961 | (!only || (Element.classNames(e).detect(function(v) { return only.include(v) })))) 962 | elements.push(e); 963 | if(recursive) { 964 | var grandchildren = Element.findChildren(e, only, recursive, tagName); 965 | if(grandchildren) elements.push(grandchildren); 966 | } 967 | }); 968 | 969 | return (elements.length>0 ? elements.flatten() : []); 970 | }; 971 | 972 | Element.offsetSize = function (element, type) { 973 | return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')]; 974 | }; -------------------------------------------------------------------------------- /spec/rails_app/public/javascripts/rails.js: -------------------------------------------------------------------------------- 1 | document.observe("dom:loaded", function() { 2 | function handleRemote(element) { 3 | var method, url, params; 4 | 5 | if (element.tagName.toLowerCase() === 'form') { 6 | method = element.readAttribute('method') || 'post'; 7 | url = element.readAttribute('action'); 8 | params = element.serialize(true); 9 | } else { 10 | method = element.readAttribute('data-method') || 'get'; 11 | url = element.readAttribute('href'); 12 | params = {}; 13 | } 14 | 15 | var event = element.fire("ajax:before"); 16 | if (event.stopped) return false; 17 | 18 | new Ajax.Request(url, { 19 | method: method, 20 | parameters: params, 21 | asynchronous: true, 22 | evalScripts: true, 23 | 24 | onLoading: function(request) { element.fire("ajax:loading", {request: request}); }, 25 | onLoaded: function(request) { element.fire("ajax:loaded", {request: request}); }, 26 | onInteractive: function(request) { element.fire("ajax:interactive", {request: request}); }, 27 | onComplete: function(request) { element.fire("ajax:complete", {request: request}); }, 28 | onSuccess: function(request) { element.fire("ajax:success", {request: request}); }, 29 | onFailure: function(request) { element.fire("ajax:failure", {request: request}); } 30 | }); 31 | 32 | element.fire("ajax:after"); 33 | } 34 | 35 | function handleMethod(element) { 36 | var method, url, token_name, token; 37 | 38 | method = element.readAttribute('data-method'); 39 | url = element.readAttribute('href'); 40 | csrf_param = $$('meta[name=csrf-param]').first(); 41 | csrf_token = $$('meta[name=csrf-token]').first(); 42 | 43 | var form = new Element('form', { method: "POST", action: url, style: "display: none;" }); 44 | element.parentNode.appendChild(form); 45 | 46 | if (method != 'post') { 47 | var field = new Element('input', { type: 'hidden', name: '_method', value: method }); 48 | form.appendChild(field); 49 | } 50 | 51 | if (csrf_param) { 52 | var param = csrf_param.readAttribute('content'); 53 | var token = csrf_token.readAttribute('content'); 54 | var field = new Element('input', { type: 'hidden', name: param, value: token }); 55 | form.appendChild(field); 56 | } 57 | 58 | form.submit(); 59 | } 60 | 61 | $(document.body).observe("click", function(event) { 62 | var message = event.findElement().readAttribute('data-confirm'); 63 | if (message && !confirm(message)) { 64 | event.stop(); 65 | return false; 66 | } 67 | 68 | var element = event.findElement("a[data-remote]"); 69 | if (element) { 70 | handleRemote(element); 71 | event.stop(); 72 | return true; 73 | } 74 | 75 | var element = event.findElement("a[data-method]"); 76 | if (element) { 77 | handleMethod(element); 78 | event.stop(); 79 | return true; 80 | } 81 | }); 82 | 83 | // TODO: I don't think submit bubbles in IE 84 | $(document.body).observe("submit", function(event) { 85 | var element = event.findElement(), 86 | message = element.readAttribute('data-confirm'); 87 | if (message && !confirm(message)) { 88 | event.stop(); 89 | return false; 90 | } 91 | 92 | var inputs = element.select("input[type=submit][data-disable-with]"); 93 | inputs.each(function(input) { 94 | input.disabled = true; 95 | input.writeAttribute('data-original-value', input.value); 96 | input.value = input.readAttribute('data-disable-with'); 97 | }); 98 | 99 | var element = event.findElement("form[data-remote]"); 100 | if (element) { 101 | handleRemote(element); 102 | event.stop(); 103 | } 104 | }); 105 | 106 | $(document.body).observe("ajax:after", function(event) { 107 | var element = event.findElement(); 108 | 109 | if (element.tagName.toLowerCase() === 'form') { 110 | var inputs = element.select("input[type=submit][disabled=true][data-disable-with]"); 111 | inputs.each(function(input) { 112 | input.value = input.readAttribute('data-original-value'); 113 | input.writeAttribute('data-original-value', null); 114 | input.disabled = false; 115 | }); 116 | } 117 | }); 118 | }); -------------------------------------------------------------------------------- /spec/rails_app/public/stylesheets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cschiewek/devise_ldap_authenticatable/6ef2131e79ff3421429f8d1b0645c6e113db4dc7/spec/rails_app/public/stylesheets/.gitkeep -------------------------------------------------------------------------------- /spec/rails_app/script/cucumber: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | vendored_cucumber_bin = Dir["#{File.dirname(__FILE__)}/../vendor/{gems,plugins}/cucumber*/bin/cucumber"].first 4 | if vendored_cucumber_bin 5 | load File.expand_path(vendored_cucumber_bin) 6 | else 7 | require 'rubygems' unless ENV['NO_RUBYGEMS'] 8 | require 'cucumber' 9 | load Cucumber::BINARY 10 | end 11 | -------------------------------------------------------------------------------- /spec/rails_app/script/rails: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | # This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application. 3 | 4 | APP_PATH = File.expand_path('../../config/application', __FILE__) 5 | require File.expand_path('../../config/boot', __FILE__) 6 | require 'rails/commands' 7 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | ENV["RAILS_ENV"] = "test" 2 | 3 | require File.expand_path("rails_app/config/environment.rb", File.dirname(__FILE__)) 4 | require 'rspec/rails' 5 | require 'factory_girl' # not sure why this is not already required 6 | 7 | # Rails 4.1 and RSpec are a bit on different pages on who should run migrations 8 | # on the test db and when. 9 | # 10 | # https://github.com/rspec/rspec-rails/issues/936 11 | if defined?(ActiveRecord::Migration) && ActiveRecord::Migration.respond_to?(:maintain_test_schema!) 12 | ActiveRecord::Migration.maintain_test_schema! 13 | end 14 | 15 | Dir[File.expand_path("support/**/*.rb", File.dirname(__FILE__))].each {|f| require f} 16 | 17 | RSpec.configure do |config| 18 | config.mock_with :rspec 19 | config.use_transactional_fixtures = true 20 | config.infer_base_class_for_anonymous_controllers = false 21 | end 22 | 23 | def ldap_root 24 | File.expand_path('ldap', File.dirname(__FILE__)) 25 | end 26 | 27 | def ldap_connect_string 28 | if ENV["LDAP_SSL"] 29 | "-x -H ldaps://localhost:3389 -D 'cn=admin,dc=test,dc=com' -w secret" 30 | else 31 | "-x -h localhost -p 3389 -D 'cn=admin,dc=test,dc=com' -w secret" 32 | end 33 | end 34 | 35 | def reset_ldap_server! 36 | if ENV["LDAP_SSL"] 37 | `ldapmodify #{ldap_connect_string} -f #{File.join(ldap_root, 'clear.ldif')}` 38 | `ldapadd #{ldap_connect_string} -f #{File.join(ldap_root, 'base.ldif')}` 39 | else 40 | `ldapmodify #{ldap_connect_string} -f #{File.join(ldap_root, 'clear.ldif')}` 41 | `ldapadd #{ldap_connect_string} -f #{File.join(ldap_root, 'base.ldif')}` 42 | end 43 | end 44 | 45 | def default_devise_settings! 46 | ::Devise.ldap_logger = true 47 | ::Devise.ldap_create_user = false 48 | ::Devise.ldap_update_password = true 49 | ::Devise.ldap_config = "#{Rails.root}/config/#{"ssl_" if ENV["LDAP_SSL"]}ldap.yml" 50 | ::Devise.ldap_check_group_membership = false 51 | ::Devise.ldap_check_attributes = false 52 | ::Devise.ldap_check_attributes_presence = false 53 | ::Devise.ldap_auth_username_builder = Proc.new() {|attribute, login, ldap| "#{attribute}=#{login},#{ldap.base}" } 54 | ::Devise.authentication_keys = [:email] 55 | end 56 | -------------------------------------------------------------------------------- /spec/support/factories.rb: -------------------------------------------------------------------------------- 1 | FactoryGirl.define do 2 | factory :user do 3 | email "example.user@test.com" 4 | password "secret" 5 | end 6 | 7 | factory :admin, :class => User do 8 | email "example.admin@test.com" 9 | password "admin_secret" 10 | end 11 | 12 | factory :other, :class => User do 13 | email "other.user@test.com" 14 | password "other_secret" 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /spec/unit/adapter_spec.rb: -------------------------------------------------------------------------------- 1 | require 'spec_helper' 2 | 3 | describe Devise::LDAP::Adapter do 4 | describe '#expired_valid_credentials?' do 5 | before do 6 | ::Devise.ldap_use_admin_to_bind = true 7 | expect_any_instance_of(Devise::LDAP::Connection).to receive(:expired_valid_credentials?) 8 | end 9 | 10 | it 'can bind as the admin user' do 11 | expect(Devise::LDAP::Connection).to receive(:new) 12 | .with(hash_including( 13 | :login => 'test.user@test.com', 14 | :password => 'pass', 15 | :ldap_auth_username_builder => kind_of(Proc), 16 | :admin => true)).and_call_original 17 | 18 | Devise::LDAP::Adapter.expired_valid_credentials?('test.user@test.com', 'pass') 19 | end 20 | end 21 | end 22 | -------------------------------------------------------------------------------- /spec/unit/connection_spec.rb: -------------------------------------------------------------------------------- 1 | require File.expand_path('../spec_helper', File.dirname(__FILE__)) 2 | 3 | describe 'Connection' do 4 | it 'accepts a proc for ldap_config' do 5 | ::Devise.ldap_config = Proc.new() {{ 6 | 'host' => 'localhost', 7 | 'port' => 3389, 8 | 'base' => 'ou=testbase,dc=test,dc=com', 9 | 'attribute' => 'cn', 10 | }} 11 | connection = Devise::LDAP::Connection.new() 12 | expect(connection.ldap.base).to eq('ou=testbase,dc=test,dc=com') 13 | end 14 | 15 | it 'allows encryption options to be set in ldap_config' do 16 | ::Devise.ldap_config = Proc.new() {{ 17 | 'host' => 'localhost', 18 | 'port' => 3389, 19 | 'base' => 'ou=testbase,dc=test,dc=com', 20 | 'attribute' => 'cn', 21 | 'encryption' => { 22 | :method => :simple_tls, 23 | :tls_options => OpenSSL::SSL::SSLContext::DEFAULT_PARAMS 24 | } 25 | }} 26 | connection = Devise::LDAP::Connection.new() 27 | expect(connection.ldap.instance_variable_get(:@encryption)).to eq({ 28 | :method => :simple_tls, 29 | :tls_options => OpenSSL::SSL::SSLContext::DEFAULT_PARAMS 30 | }) 31 | end 32 | 33 | class TestOpResult 34 | attr_accessor :error_message 35 | end 36 | 37 | describe '#expired_valid_credentials?' do 38 | let(:conn) { double(Net::LDAP).as_null_object } 39 | let(:error) { } 40 | let(:is_authed) { false } 41 | before do 42 | expect(Net::LDAP).to receive(:new).and_return(conn) 43 | allow(conn).to receive(:get_operation_result).and_return(TestOpResult.new.tap{|r| r.error_message = error}) 44 | allow_any_instance_of(Devise::LDAP::Connection).to receive(:authenticated?).and_return(is_authed) 45 | allow_any_instance_of(Devise::LDAP::Connection).to receive(:dn).and_return('any dn') 46 | expect(DeviseLdapAuthenticatable::Logger).to receive(:send).with('Authorizing user any dn') 47 | end 48 | subject do 49 | Devise::LDAP::Connection.new.expired_valid_credentials? 50 | end 51 | 52 | context do 53 | let(:error) { 'THIS PART CAN BE ANYTHING AcceptSecurityContext error, data 773 SO CAN THIS' } 54 | it 'is true when expired credential error is returned and not already authenticated' do 55 | expect(subject).to be true 56 | end 57 | end 58 | 59 | context do 60 | it 'is false when expired credential error is not returned and not already authenticated' do 61 | expect(subject).to be false 62 | end 63 | end 64 | 65 | context do 66 | let(:is_authed) { true } 67 | it 'is false when expired credential error is not returned and already authenticated' do 68 | expect(subject).to be false 69 | end 70 | end 71 | end 72 | 73 | describe '#authorized?' do 74 | let(:conn) { double(Net::LDAP).as_null_object } 75 | let(:error) { } 76 | let(:log_message) { } 77 | let(:is_authed) { false } 78 | before do 79 | expect(Net::LDAP).to receive(:new).and_return(conn) 80 | allow(conn).to receive(:get_operation_result).and_return(TestOpResult.new.tap{|r| r.error_message = error}) 81 | allow_any_instance_of(Devise::LDAP::Connection).to receive(:authenticated?).and_return(is_authed) 82 | allow_any_instance_of(Devise::LDAP::Connection).to receive(:dn).and_return('any dn') 83 | expect(DeviseLdapAuthenticatable::Logger).to receive(:send).with('Authorizing user any dn') 84 | end 85 | subject do 86 | Devise::LDAP::Connection.new.authorized? 87 | end 88 | context do 89 | before { expect(DeviseLdapAuthenticatable::Logger).to receive(:send).with(log_message) } 90 | 91 | context do 92 | let(:error) { 'THIS PART CAN BE ANYTHING AcceptSecurityContext error, data 52e SO CAN THIS' } 93 | let(:log_message) { 'Not authorized because of invalid credentials.' } 94 | it 'is false when credential error is returned' do 95 | expect(subject).to be false 96 | end 97 | end 98 | context do 99 | let(:error) { 'THIS PART CAN BE ANYTHING AcceptSecurityContext error, data 773 SO CAN THIS' } 100 | let(:log_message) { 'Not authorized because of expired credentials.' } 101 | it 'is false when expired error is returned' do 102 | expect(subject).to be false 103 | end 104 | end 105 | context do 106 | let(:error) { 'any error' } 107 | let(:log_message) { 'Not authorized because not authenticated.' } 108 | it 'is false when any other error is returned' do 109 | expect(subject).to be false 110 | end 111 | end 112 | end 113 | 114 | context do 115 | let(:is_authed) { true } 116 | it 'is true when already authenticated' do 117 | expect(subject).to be true 118 | end 119 | end 120 | end 121 | end 122 | -------------------------------------------------------------------------------- /spec/unit/user_spec.rb: -------------------------------------------------------------------------------- 1 | require File.expand_path('../spec_helper', File.dirname(__FILE__)) 2 | 3 | describe 'Users' do 4 | 5 | def should_be_validated(user, password, message = "Password is invalid") 6 | assert(user.valid_ldap_authentication?(password), message) 7 | end 8 | 9 | def should_not_be_validated(user, password, message = "Password is not properly set") 10 | assert(!user.valid_ldap_authentication?(password), message) 11 | end 12 | 13 | describe "With default settings" do 14 | before do 15 | default_devise_settings! 16 | reset_ldap_server! 17 | end 18 | 19 | describe "look up an ldap user" do 20 | it "should return true for a user that does exist in LDAP" do 21 | assert_equal true, ::Devise::LDAP::Adapter.valid_login?('example.user@test.com') 22 | end 23 | 24 | it "should return false for a user that doesn't exist in LDAP" do 25 | assert_equal false, ::Devise::LDAP::Adapter.valid_login?('barneystinson') 26 | end 27 | end 28 | 29 | describe "create a basic user" do 30 | before do 31 | @user = Factory.create(:user) 32 | end 33 | 34 | it "should check for password validation" do 35 | assert_equal(@user.email, "example.user@test.com") 36 | should_be_validated @user, "secret" 37 | should_not_be_validated @user, "wrong_secret" 38 | should_not_be_validated @user, "Secret" 39 | end 40 | end 41 | 42 | describe "change a LDAP password" do 43 | before do 44 | @user = Factory.create(:user) 45 | end 46 | 47 | it "should change password" do 48 | should_be_validated @user, "secret" 49 | @user.password = "changed" 50 | @user.change_password!("secret") 51 | should_be_validated @user, "changed", "password was not changed properly on the LDAP server" 52 | end 53 | 54 | it "should not allow to change password if setting is false" do 55 | should_be_validated @user, "secret" 56 | ::Devise.ldap_update_password = false 57 | @user.reset_password!("wrong_secret", "wrong_secret") 58 | should_not_be_validated @user, "wrong_secret" 59 | should_be_validated @user, "secret" 60 | end 61 | end 62 | 63 | describe "create new local user if user is in LDAP" do 64 | 65 | before do 66 | assert(User.all.blank?, "There shouldn't be any users in the database") 67 | end 68 | 69 | it "should not create user in the database" do 70 | @user = User.find_for_ldap_authentication(:email => "example.user@test.com", :password => "secret") 71 | assert(User.all.blank?) 72 | assert(@user.new_record?) 73 | end 74 | 75 | describe "creating users is enabled" do 76 | before do 77 | ::Devise.ldap_create_user = true 78 | end 79 | 80 | it "should create a user in the database" do 81 | @user = User.find_for_ldap_authentication(:email => "example.user@test.com", :password => "secret") 82 | assert_equal(User.all.size, 1) 83 | expect(User.all.collect(&:email)).to include("example.user@test.com") 84 | assert(@user.persisted?) 85 | end 86 | 87 | it "should not create a user in the database if the password is wrong_secret" do 88 | @user = User.find_for_ldap_authentication(:email => "example.user", :password => "wrong_secret") 89 | assert(User.all.blank?, "There's users in the database") 90 | end 91 | 92 | it "should not create a user if the user is not in LDAP" do 93 | @user = User.find_for_ldap_authentication(:email => "wrong_secret.user@test.com", :password => "wrong_secret") 94 | assert(User.all.blank?, "There's users in the database") 95 | end 96 | 97 | it "should create a user in the database if case insensitivity does not matter" do 98 | ::Devise.case_insensitive_keys = [] 99 | @user = Factory.create(:user) 100 | 101 | expect do 102 | User.find_for_ldap_authentication(:email => "EXAMPLE.user@test.com", :password => "secret") 103 | end.to change { User.count }.by(1) 104 | end 105 | 106 | it "should not create a user in the database if case insensitivity matters" do 107 | ::Devise.case_insensitive_keys = [:email] 108 | @user = Factory.create(:user) 109 | 110 | expect do 111 | User.find_for_ldap_authentication(:email => "EXAMPLE.user@test.com", :password => "secret") 112 | end.to_not change { User.count } 113 | end 114 | 115 | it "should create a user with downcased email in the database if case insensitivity matters" do 116 | ::Devise.case_insensitive_keys = [:email] 117 | 118 | @user = User.find_for_ldap_authentication(:email => "EXAMPLE.user@test.com", :password => "secret") 119 | expect(User.all.collect(&:email)).to include("example.user@test.com") 120 | end 121 | end 122 | 123 | end 124 | 125 | describe "use groups for authorization" do 126 | before do 127 | @admin = Factory.create(:admin) 128 | @user = Factory.create(:user) 129 | ::Devise.authentication_keys = [:email] 130 | ::Devise.ldap_check_group_membership = true 131 | end 132 | 133 | it "should admin should be allowed in" do 134 | should_be_validated @admin, "admin_secret" 135 | end 136 | 137 | it "should admin should have the proper groups set" do 138 | expect(@admin.ldap_groups).to include('cn=admins,ou=groups,dc=test,dc=com') 139 | end 140 | 141 | it "should user should not be allowed in" do 142 | should_not_be_validated @user, "secret" 143 | end 144 | end 145 | 146 | describe "check group membership" do 147 | before do 148 | @admin = Factory.create(:admin) 149 | @user = Factory.create(:user) 150 | end 151 | 152 | it "should return true for admin being in the admins group" do 153 | assert_equal true, @admin.in_ldap_group?('cn=admins,ou=groups,dc=test,dc=com') 154 | end 155 | 156 | it "should return false for admin being in the admins group using the 'foobar' group attribute" do 157 | assert_equal false, @admin.in_ldap_group?('cn=admins,ou=groups,dc=test,dc=com', 'foobar') 158 | end 159 | 160 | it "should return true for user being in the users group" do 161 | assert_equal true, @user.in_ldap_group?('cn=users,ou=groups,dc=test,dc=com') 162 | end 163 | 164 | it "should return false for user being in the admins group" do 165 | assert_equal false, @user.in_ldap_group?('cn=admins,ou=groups,dc=test,dc=com') 166 | end 167 | 168 | it "should return false for a user being in a nonexistent group" do 169 | assert_equal false, @user.in_ldap_group?('cn=thisgroupdoesnotexist,ou=groups,dc=test,dc=com') 170 | end 171 | end 172 | 173 | describe "check group membership w/out admin bind" do 174 | before do 175 | @user = Factory.create(:user) 176 | ::Devise.ldap_check_group_membership_without_admin = true 177 | end 178 | 179 | after do 180 | ::Devise.ldap_check_group_membership_without_admin = false 181 | end 182 | 183 | it "should return true for user being in the users group" do 184 | assert_equal true, @user.in_ldap_group?('cn=users,ou=groups,dc=test,dc=com') 185 | end 186 | 187 | it "should return false for user being in the admins group" do 188 | assert_equal false, @user.in_ldap_group?('cn=admins,ou=groups,dc=test,dc=com') 189 | end 190 | 191 | it "should return false for a user being in a nonexistent group" do 192 | assert_equal false, @user.in_ldap_group?('cn=thisgroupdoesnotexist,ou=groups,dc=test,dc=com') 193 | end 194 | 195 | # TODO: add a test that confirms the user's own binding is used rather 196 | # than the admin binding by creating an LDAP user who can't do group 197 | # lookups perhaps? 198 | 199 | # TODO: add a test to demonstrate this function won't work on a user 200 | # after the initial login request if the password isn't available. This 201 | # might have to be more of a full stack test. 202 | end 203 | 204 | describe "use role attribute for authorization" do 205 | before do 206 | @admin = Factory.create(:admin) 207 | @user = Factory.create(:user) 208 | ::Devise.ldap_check_attributes = true 209 | end 210 | 211 | it "should admin should be allowed in" do 212 | should_be_validated @admin, "admin_secret" 213 | end 214 | 215 | it "should user should not be allowed in" do 216 | should_not_be_validated @user, "secret" 217 | end 218 | end 219 | 220 | describe "use attribute presence for authorization" do 221 | before do 222 | @admin = Factory.create(:admin) 223 | @user = Factory.create(:user) 224 | ::Devise.ldap_check_attributes_presence = true 225 | end 226 | 227 | after do 228 | ::Devise.ldap_check_attributes_presence = false 229 | end 230 | 231 | it "should admin should not be allowed in" do 232 | should_not_be_validated @admin, "admin_secret" 233 | end 234 | 235 | it "should user should be allowed in" do 236 | should_be_validated @user, "secret" 237 | end 238 | end 239 | 240 | describe "use admin setting to bind" do 241 | before do 242 | @admin = Factory.create(:admin) 243 | @user = Factory.create(:user) 244 | ::Devise.ldap_use_admin_to_bind = true 245 | end 246 | 247 | it "should description" do 248 | should_be_validated @admin, "admin_secret" 249 | end 250 | end 251 | 252 | describe 'check password expiration' do 253 | before { allow_any_instance_of(Devise::LDAP::Connection).to receive(:authenticated?).and_return(false) } 254 | 255 | it 'should return false for a user that has a fresh password' do 256 | allow_any_instance_of(Devise::LDAP::Connection).to receive(:last_message_expired_credentials?).and_return(false) 257 | assert_equal false, ::Devise::LDAP::Adapter.expired_valid_credentials?('example.user@test.com','secret') 258 | end 259 | 260 | it 'should return true for a user that has an expired password' do 261 | allow_any_instance_of(Devise::LDAP::Connection).to receive(:last_message_expired_credentials?).and_return(true) 262 | assert_equal true, ::Devise::LDAP::Adapter.expired_valid_credentials?('example.user@test.com','secret') 263 | end 264 | end 265 | end 266 | 267 | describe "use uid for login" do 268 | before do 269 | default_devise_settings! 270 | reset_ldap_server! 271 | ::Devise.ldap_config = "#{Rails.root}/config/#{"ssl_" if ENV["LDAP_SSL"]}ldap_with_uid.yml" 272 | ::Devise.authentication_keys = [:uid] 273 | end 274 | 275 | describe "description" do 276 | before do 277 | @admin = Factory.create(:admin) 278 | @user = Factory.create(:user, :uid => "example_user") 279 | end 280 | 281 | it "should be able to authenticate using uid" do 282 | should_be_validated @user, "secret" 283 | should_not_be_validated @admin, "admin_secret" 284 | end 285 | end 286 | 287 | describe "create user" do 288 | before do 289 | ::Devise.ldap_create_user = true 290 | end 291 | 292 | it "should create a user in the database" do 293 | @user = User.find_for_ldap_authentication(:uid => "example_user", :password => "secret") 294 | assert_equal(User.all.size, 1) 295 | expect(User.all.collect(&:uid)).to include("example_user") 296 | end 297 | 298 | it "should call ldap_before_save hooks" do 299 | User.class_eval do 300 | def ldap_before_save 301 | @foobar = 'foobar' 302 | end 303 | end 304 | user = User.find_for_ldap_authentication(:uid => "example_user", :password => "secret") 305 | assert_equal 'foobar', user.instance_variable_get(:"@foobar") 306 | User.class_eval do 307 | undef ldap_before_save 308 | end 309 | end 310 | 311 | it "should not call ldap_before_save hook if not defined" do 312 | should_be_validated Factory.create(:user, :uid => "example_user"), "secret" 313 | end 314 | end 315 | end 316 | 317 | describe "using ERB in the config file" do 318 | before do 319 | default_devise_settings! 320 | reset_ldap_server! 321 | ::Devise.ldap_config = "#{Rails.root}/config/#{"ssl_" if ENV["LDAP_SSL"]}ldap_with_erb.yml" 322 | end 323 | 324 | describe "authenticate" do 325 | before do 326 | @admin = Factory.create(:admin) 327 | @user = Factory.create(:user) 328 | end 329 | 330 | it "should be able to authenticate" do 331 | should_be_validated @user, "secret" 332 | should_be_validated @admin, "admin_secret" 333 | end 334 | end 335 | end 336 | 337 | describe "using variants in the config file" do 338 | before do 339 | default_devise_settings! 340 | reset_ldap_server! 341 | ::Devise.ldap_config = Rails.root.join 'config', 'ldap_with_boolean_ssl.yml' 342 | end 343 | 344 | it "should not fail if config file has ssl: true" do 345 | Devise::LDAP::Connection.new 346 | end 347 | end 348 | 349 | describe "use username builder" do 350 | before do 351 | default_devise_settings! 352 | reset_ldap_server! 353 | ::Devise.ldap_auth_username_builder = Proc.new() do |attribute, login, ldap| 354 | "#{attribute}=#{login},ou=others,dc=test,dc=com" 355 | end 356 | @other = Factory.create(:other) 357 | end 358 | 359 | it "should be able to authenticate" do 360 | should_be_validated @other, "other_secret" 361 | end 362 | end 363 | 364 | end 365 | --------------------------------------------------------------------------------