module LdapManager class FetchAvatar < LdapManagerService def initialize(cn:) @cn = cn end def call treebase = ldap_config["base"] attributes = %w{ jpegPhoto } filter = Net::LDAP::Filter.eq("cn", @cn) entry = client.search(base: treebase, filter: filter, attributes: attributes).first if entry&.jpegPhoto binary_data = entry.jpegPhoto.first # Use first value (binary) Rails.logger.debug { "Fetched jpegPhoto size: #{binary_data.bytesize}" } create_tempfile(binary_data) else Rails.logger.debug { "No jpegPhoto found for cn=#{@cn}, ou=#{@ou}" } nil end end def create_tempfile(binary_data) tempfile = Tempfile.new(['image', '.jpg']) tempfile.binmode tempfile.write(binary_data) tempfile.rewind Rails.logger.debug { "Storing debug file for cn=#{@cn}, size=#{tempfile.size}" } data = tempfile.read debug_file_path = "#{Rails.root}/tmp/avatar-fetched.jpg" debug_file = File.open(debug_file_path, 'wb') debug_file.write(data) debug_file.close data end end end