diary/ldap_cache.rb

68 lines
1.5 KiB
Ruby

# SPDX-License-Identifier: Apache-2.0
# Copyright (C) 2021 OKTET Labs Ltd. All rights reserved.
#
# Class LDAP::Cache for Diary Management Application.
#
require 'ldap'
class LDAP::Cache < Hash
def initialize(ldap, base_dn, scope, field)
@ldap = ldap
@base_dn = base_dn
@scope = scope
@field = field
@lists = Hash.new
super(0)
end
attr_reader :ldap, :lists
attr_accessor :base_dn, :scope, :field
def search(filter)
list = Array.new
begin
@ldap.search(@base_dn, @scope, filter) do |entry|
hash = Hash.new
entry.to_hash.each do |key, value|
hash[key] = value[0]
end
self[hash[@field]] = hash
list.push(hash)
end
rescue
$stderr.printf "Failed to search in LDAP\n"
exit (-1)
end
list
end
private :search
def list(filter, main_value)
if not @lists[filter]
@lists[filter] = search(filter).sort_by do |entry|
entry[main_value]
end.collect do |entry|
[entry[@field], entry[main_value]]
end
end
@lists[filter]
end
def [](key)
if super(key) == 0
list = search("(#{@field}=#{key})")
if list.length != 1
self[key] = nil
else
self[key] = list[0]
end
end
super(key)
end
end