├── .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 | [](http://badge.fury.io/rb/devise_ldap_authenticatable) 5 | [](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 |<%= message %>
21 | <% end %> 22 | 23 | <%= yield %> 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /spec/rails_app/app/views/posts/index.html.erb: -------------------------------------------------------------------------------- 1 |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 |You may have mistyped the address or the page may have moved.
24 |Maybe you tried to change something you didn't have access to.
24 |We've been notified about this issue and we'll take a look at it shortly.
24 |