SystemDataBackendLdap.rb 1.94 KB
require 'active_support/secure_random'
require 'net/ldap'

class SystemDataBackendLdap

  LDAP_USER_MAP = {
    :uid           => :name,
    :userpassword  => :pass,
    :uidnumber     => :uid,
    :gidnumber     => :gid,
    :loginshell    => :shell,
    :homedirectory => :home
  }

  LDAP_GROUP_MAP = {
    :cn        => :name,
    :gidnumber => :gid,
    :memberuid => :members
  }

  LDAP_SITE_MAP = {:o => :name}

  LDAP_MAP = {
    :user      => LDAP_USER_MAP,
    :group     => LDAP_GROUP_MAP,
    :site      => LDAP_SITE_MAP
  }

  LDAP_FILTER = {
    :user        => Net::LDAP::Filter::eq('objectClass', 'posixAccount'),
    :group       => Net::LDAP::Filter::eq('objectClass', 'posixGroup'),
    :site        => Net::LDAP::Filter::eq('objectClass', 'organization') &
                    (~Net::LDAP::Filter::eq('o', 'hosting')),
    :mailAlias   => Net::LDAP::Filter::eq('objectClass', 'mailAlias'),
    :mailAccount => Net::LDAP::Filter::eq('objectClass', 'mailAccount')
  }


  def initialize(host, port, baseDn, args={})
    @baseDn    = baseDn
    @systemDn  = 'o=system,' + @baseDn
    @hostingDn = 'o=hosting,' + @baseDn

    @systemDn  = args[:systemDn] if args[:systemDn]
    @hostingDn = args[:hostingDn] if args[:hostingDn]

    @ldap      = Net::LDAP.new(:host => host, :port => port)
    @ldapData  = Hash.new
  end

  def load!(kind)
    @ldapData[kind] = @ldap.search(
      :base   => ldapBase(kind),
      :filter => LDAP_FILTER[kind]
    )
  end

  def load(kind)
    load!(kind) if ! @ldapData[kind]

    @ldapData[kind].each do |data|
      map = { :dn => :id }
      map.merge!(LDAP_MAP[kind]) if LDAP_MAP[kind]

      ydata = { :backend => self }

      data.each do |key,value|
        ydata.merge!({ map[key] || key => value.size==1?value[0]:value.to_a })
      end

      yield ydata
    end
  end

  private

  def ldapBase(kind)
    case(kind)
    when :user, :group: @systemDn
    when :site, :mailAlias, :mailAccount: @hostingDn
    end
  end

end