创建自定义设计策略

Mik*_*iel 8 ruby ruby-on-rails devise ruby-on-rails-4

现在已经和它斗争了一段时间,不知道为什么它不起作用.

要点是将Devise与LDAP结合使用.除了自定义策略之外,我不需要做任何事情,所以除了自定义策略之外我不需要使用任何东西.

我创建了一个基于https://github.com/plataformatec/devise/wiki/How-To:-Authenticate-via-LDAP,据我所知,一切都应该工作,除非我尝试运行服务器(或rake)路线)我得到了NameError

lib/devise/models.rb:88:in `const_get': uninitialized constant Devise::Models::LdapAuthenticatable (NameError)
Run Code Online (Sandbox Code Playgroud)

我已经将错误追溯到了我的错误 app/models/user.rb

class User < ActiveRecord::Base
  devise :ldap_authenticatable, :rememberable, :trackable, :timeoutable
end
Run Code Online (Sandbox Code Playgroud)

如果我删除:ldap_authenticatable然后崩溃消失但我没有路由,user#session并且无法访问登录提示.

我的支持文件:

lib/ldap_authenticatable.rb

require 'net/ldap'
require 'devise/strategies/authenticatable'

module Devise
  module Strategies
    class LdapAuthenticatable < Authenticatable

      def authenticate!
        if params[:user]
          ldap = Net::LDAP.new
          ldap.host = 'redacted'
          ldap.port = 389
          ldap.auth login, password

          if ldap.bind
            user = User.where(login: login).first_or_create do |user|
            success!(user)
          else
            fail(:invalid_login)
          end
        end
      end

      def login
        params[:user][:login]
      end

      def password
        params[:user][:password]
      end

    end
  end
end

Warden::Strategies.add(:ldap_authenticatable, Devise::Strategies::LdapAuthenticatable)
Run Code Online (Sandbox Code Playgroud)

最后,在里面 config/initializers/devise.rb

Devise.setup do |config|
  # ==> LDAP Configuration
  require 'ldap_authenticatable'
  config.warden do |manager|
    manager.default_strategies(:scope => :user).unshift :ldap_authenticatable
  end
end
Run Code Online (Sandbox Code Playgroud)

我已经用尽了我的搜索,也许有人可以看到我失踪的东西.

干杯

小智 2

您的lib/ldap_authenticatable.rbis 在自动加载路径中还是明确需要的?由于 lib 文件夹中的 Rails 3 代码默认不再自动加载。这是解决该问题的一种方法

恕我直言,设计是一个伟大的宝石。然而,为了编写自己的策略,您不仅必须熟悉 Devise,还必须熟悉Warden源代码,并且需要在各个地方编写大量样板代码,因此我开始研究如何使自定义更容易设计并提出这个宝石devise_custom_authenticatable。您可以检查一下,它可能会以不同的方式解决您的问题。这个 gem 用于相当繁忙的应用程序的生产代码库,因此它经过了战斗证明:)