require 'ldap'
class NotAuthenticatedError < Exception
end
class EdAuth
    HOST, PORT = '192.168.10.10', 62222
    DN, FILTER = 't=R', '(certificateRevocationList=*)'

    def initialize(pid, pass)
        @ldap = LDAP::SSLConn.new(HOST, PORT, true)
        @authenticated = false
        @pid, @pass = pid, pass
        @dn, @filter = DN, format(FILTER, pid)

         @authenticity = false
         @pri_affil, @affil = nil, nil
    end

    def authenticate
        return @authenticity if @authenticated
        begin
            @ldap.search(@dn, LDAP::LDAP_SCOPE_ONELEVEL, @filter) {|c| @dn = c.get_dn}
            @ldap.bind(@dn, @pass)
            @authenticity = true
        rescue LDAP::ResultError
            @authenticity = false
        ensure
            @authenticated = true
        end
        @authenticity
    end

    def get_primary_affiliation
        query if @pri_affil.nil?
    puts @pri_affil
        @pri_affil
    end

    def get_affiliations
        query if @affil.nil?
    puts @affil
        @affil
    end

    def close
       begin
            @ldap.unbind
       rescue LDAP::InvalidDataError
       end
    end

    private
    def query
        raise NotAuthenticatedError unless @authenticated and
        @authenticity
        @ldap.search(@dn, LDAP::LDAP_SCOPE_SUBTREE, @filter,
                    ['eduPersonPrimaryAffiliation',
                    'eduPersonAffiliation']) do |entry|
                    @pri_affil =
                    entry.get_values('edupersonprimaryaffiliation').shift
                    @affil = entry.get_values('edupersonaffiliation')
        end
    end
end

x = EdAuth.new('your_pid', 'your_password')
x.authenticate
x.get_primary_affiliation
x.get_affiliations
x.close