2014-01-22 50 views
1

我试图修改现有的使用设计检查LDAP连接的rails应用程序。我需要检查多个不同的LDAP连接。基本上我的用户群分为两个或三个不同的活动目录,我希望能够提供一组连接信息对象,并通过连接运行,直到获得响应或失败。这可能与设计?设计多个LDAP连接

回答

3

这是!有点。我最近一起攻击了一个解决方案,不确定它现在对你有多大帮助。

首先,您需要使用devise_ldap_authenticatable。安装完成后,您可以对此gem中的connection.rb文件中的initialize方法进行一些更新,以接受一个配置或多个配置。

def initialize(params = {}) 
    ldap_configs = YAML.load(ERB.new(File.read(::Devise.ldap_config || "#{Rails.root}/config/ldap.yml")).result)[Rails.env] 
    ldap_configs = ldap_configs.is_a?(Hash) ? [ldap_configs] : ldap_configs 

下一部分由您决定。由于我的约束(两个目录中存在用户名),我强制用户在循环连接之前输入一个有效的域。你可能没有这个约束。无论哪种情况,只需循环配置即可。一旦你成功绑定,打破循环。该配置值将存储在这里初始化的变量@ldap -

ldap_configs.each do |ldap_config| 
    #Maybe not needed if you don't have usernames in each directory. @domain is a user-entered value  
    if @domain == ldap_config["domain"] 
     #This should all stay the same, until you check the bindings 

      if @ldap.bind 
      #If it binds, break the loop. the values in @ldap will be stored 
      break 
      else 
      #keep looping 
      end 
    end 
end 

接下来,确保devise_ldap_authenticatable生成配置了所有的连接,包括域名的,如果需要的话ldap.yml文件 -

## Environment 

development: 
- 
    host: "localhost1.com" 
    port: "389" 
    attribute: uid 
    base: dc=my-domain,dc=com 
    admin_user: cn=admin,dc=my-domain,dc=com 
    admin_password: admin_password 
    ssl: false 
    domain: "FIRST" 
- 
    host: "localhost2.com" 
    port: "389" 
    attribute: uid 
    base: dc=my-domain,dc=com 
    admin_user: cn=admin,dc=my-domain,dc=com 
    admin_password: admin_password 
    ssl: false 
    domain: "SECOND" 
+0

是可能的,如果我有一个主机(运行全局编录),多基地CONFIGS为多个域,以简化这个解决方案? –

0

我建立在史蒂夫的回答下面,似乎工作得很好。这样做的好处是它包装了原始代码并为其添加了功能。您可以保持ldap.yml文件相同,并添加一个hosts密钥以及YAML的一组主机来执行此操作。

请注意,我挽救了循环中的连接错误。当它试图再次建立图书馆已经试图建立的联系时,它仍然会抛出。

module Devise 
    module LDAP 
    module ConnectionExtensions 
     def initialize(params = {}) 
     super 
     ldap_config = YAML.load(File.read("#{Rails.root}/config/ldap.yml"))[Rails.env] 
     ldap_config["hosts"]&.each do |host| 
      begin 
      @ldap.host = host 
      break if @ldap.bind 
      rescue Net::LDAP::Error => e 
      DeviseLdapAuthenticatable::Logger.send(e) 
      next 
      end 
     end 
     end 
    end 

    class Connection 
     prepend ConnectionExtensions 
    end 
    end 
end 

这里是样本YAML文件:

development: 
    host: localhost1.com 
    hosts: 
    - localhost1.com 
    - localhost2.com 
    port: 389 
    attribute: uid 
    base: dc=my-domain,dc=com 
    admin_user: cn=admin,dc=my-domain,dc=com 
    admin_password: admin_password 
    ssl: false