无法使用自定义设计策略

时间:2018-09-11 15:50:56

标签: ruby-on-rails devise

我使用devise在我的Rails应用程序上添加一个身份验证层。我必须设置LDAP身份验证。因此,我制定了自己的策略,从字面上遵循了wiki article。但是,我收到此错误:

11: from /home/mcdostone/X/app/models/user.rb:3:in `<main>'
10: from /home/mcdostone/X/app/models/user.rb:4:in `<class:User>'
...
/home/mcdostone/.rvm/gems/ruby-2.5.1/gems/bootsnap-1.3.2/lib/bootsnap/load_path_cache/core_ext/active_support.rb:74:in `block in load_missing_constant': uninitialized constant Devise::Models::LdapAuthenticatable (NameError)
class User < ApplicationRecord
  devise :ldap_authenticatable
end

2 个答案:

答案 0 :(得分:1)

看起来该Wiki页面已经过时了。 现在,您需要在LdapAuthenticatableDevise::Models中使用一个Devise::Strategies模块。

config/initializers/ldap_authenticatable.rb

module Devise
  module Models
    module LdapAuthenticatable
      extend ActiveSupport::Concern
    end
  end

  module Strategies
    class LdapAuthenticatable < Authenticatable
      ... same as before ...
    end
  end
end

我真的建议您改用此gem,因为将需要进行许多调整以使其正常工作。

答案 1 :(得分:0)

谢谢Sree的帮助。现在工作正常!这是我的解决方案:

# config/initializers/ldpa_authenticatable.rb

module Devise
  module Models
    module LdapAuthenticatable
      extend ActiveSupport::Concern
    end
  end

  module Strategies
    class LdapAuthenticatable < Authenticatable
      # This method first checks if the user is present in the database.
      # After that, we authenticate the user thanks to the LDAP server
      def authenticate!
        if params[:user]
          user = User.find_by(username: username)
          if user.nil?
            return fail(:invalid_login)
          else
            ldap = Ldap.client
            ldap_username = Ldap.get_login(username)
            puts ldap_username.inspect
            ldap.authenticate ldap_username, password
            if ldap.bind
              success!(user)
            else
              return fail(:invalid_login)
            end
          end
        end
      end

      def username
        params[:user][:username]
      end

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

Warden::Strategies.add(:ldap_authenticatable, Devise::Strategies::LdapAuthenticatable)
Devise.add_module(:ldap_authenticatable,
                  route: :session, ## This will add the routes, rather than in the routes.rb
                  strategy: true,
                  controller: :sessions,
                  model: "ldap_authenticatable")