### Ruby Styleguide Examples Source: https://github.com/ruby-ldap/ruby-net-ldap/blob/master/CONTRIBUTING.md Examples demonstrating the preferred coding style for the ruby-net-ldap project, including hash syntax and multi-line argument formatting. ```ruby # 1.9+ style hashes {key: "value"} # Multi-line arguments with `\` MyClass.new \ foo: 'bar', baz: 'garply' ``` -------------------------------- ### Run Rake Tasks for ruby-net-ldap Source: https://github.com/ruby-ldap/ruby-net-ldap/blob/master/CONTRIBUTING.md Commands to execute Rake tasks for the ruby-net-ldap project. This is used to run the full test suite. ```shell bundle exec rake ``` -------------------------------- ### Add LDAP Directory Entries (Ruby) Source: https://context7.com/ruby-ldap/ruby-net-ldap/llms.txt This snippet shows the initial setup for adding new entries to an LDAP directory using the Net::LDAP library. It includes requiring the 'net/ldap' gem and establishing a connection with authentication details. The actual 'add' operation would follow this setup. It assumes a valid host, port, and administrative credentials. ```ruby require 'net/ldap' ldap = Net::LDAP.new( host: 'ldap.example.com', port: 389, auth: { method: :simple, username: 'cn=admin,dc=example,dc=com', password: 'secret' } ) ``` -------------------------------- ### Ruby Net::LDAP: Basic and Complex Searches Source: https://context7.com/ruby-ldap/ruby-net-ldap/llms.txt Demonstrates how to perform basic and complex searches using the Net::LDAP library. Includes examples for attribute-only retrieval and multi-criteria filtering with pagination and timing options. Requires the 'net/ldap' gem. ```ruby require 'net/ldap' # Assuming ldap is an initialized Net::LDAP object # Return only attribute names, not values attributes_only = ldap.search( base: 'dc=example,dc=com', attributes_only: true ) # Complex search with multiple options results = ldap.search( base: 'ou=people,dc=example,dc=com', filter: Net::LDAP::Filter.eq('objectClass', 'inetOrgPerson') & Net::LDAP::Filter.present('mail'), attributes: ['uid', 'cn', 'mail', 'telephoneNumber'], scope: Net::LDAP::SearchScope_WholeSubtree, size: 500, time: 30, return_result: true ) if results puts "Found #{results.size} entries" results.each do |entry| puts "#{entry.uid.first}: #{entry.cn.first}" end else result = ldap.get_operation_result puts "Search failed: #{result.message}" end ``` -------------------------------- ### Establish Secure LDAP Connections with TLS/SSL Source: https://context7.com/ruby-ldap/ruby-net-ldap/llms.txt Provides examples for establishing secure connections to an LDAP server using TLS/SSL. It covers two main methods: Simple TLS (LDAPS on port 636) where the entire connection is encrypted from the start, and Start TLS (on standard port 389) which upgrades an existing connection to use TLS. Options for custom TLS settings, including CA file paths and verification modes, are also demonstrated. ```ruby require 'net/ldap' require 'openssl' # Method 1: Simple TLS (LDAPS on port 636) # Entire connection is encrypted from start begin ldap_ldaps = Net::LDAP.new( host: 'ldaps.example.com', # Replace with your LDAPS host port: 636, auth: { method: :simple, username: 'cn=admin,dc=example,dc=com', password: 'secret' }, encryption: { method: :simple_tls, tls_options: OpenSSL::SSL::SSLContext::DEFAULT_PARAMS } ) # You can perform operations here, e.g., ldap_ldaps.bind puts "Connected via LDAPS (Simple TLS)" rescue Net::LDAP::Error => e puts "LDAPS connection failed: #{e.message}" end # Method 2: Start TLS (on standard port 389) # Upgrades existing connection to TLS begin ldap_starttls = Net::LDAP.new( host: 'ldap.example.com', # Replace with your LDAP host port: 389, auth: { method: :simple, username: 'cn=admin,dc=example,dc=com', password: 'secret' }, encryption: { method: :start_tls, tls_options: { ca_file: '/etc/ssl/certs/ca-bundle.crt', # Adjust path as needed verify_mode: OpenSSL::SSL::VERIFY_PEER } } ) # You can perform operations here, e.g., ldap_starttls.bind puts "Connected via Start TLS" rescue Net::LDAP::Error => e puts "Start TLS connection failed: #{e.message}" end # Custom TLS options for self-signed certificates or specific versions begin ldap_custom_tls = Net::LDAP.new( host: 'ldap.example.com', # Replace with your LDAP host port: 636, encryption: { method: :simple_tls, tls_options: { ca_file: '/path/to/custom-ca.pem', # Path to your custom CA certificate verify_mode: OpenSSL::SSL::VERIFY_PEER, ssl_version: 'TLSv1_2' # Specify TLS version if needed } } ) # You can perform operations here puts "Connected with custom TLS options" rescue Net::LDAP::Error => e puts "Custom TLS connection failed: #{e.message}" end ``` -------------------------------- ### Search LDAP Directory Entries (Ruby) Source: https://context7.com/ruby-ldap/ruby-net-ldap/llms.txt Provides examples of searching an LDAP directory using Net::LDAP. It covers basic searches with filters, specifying base DN and attributes, and handling results. It also demonstrates a memory-efficient search using a block, suitable for large result sets. The code requires the 'net/ldap' gem and assumes a prior connection and authentication. ```ruby require 'net/ldap' ldap = Net::LDAP.new( host: 'ldap.example.com', port: 389, auth: { method: :simple, username: 'cn=admin,dc=example,dc=com', password: 'secret' } ) # Basic search with filter filter = Net::LDAP::Filter.eq('objectClass', 'inetOrgPerson') treebase = 'ou=people,dc=example,dc=com' entries = ldap.search( base: treebase, filter: filter, attributes: ['cn', 'mail', 'telephoneNumber'] ) if entries entries.each do |entry| puts "DN: #{entry.dn}" puts "Name: #{entry.cn.first}" puts "Email: #{entry.mail.first}" if entry.mail.any? end else puts "Search failed: #{ldap.get_operation_result.message}" end # Search with block (memory efficient for large results) ldap.search(base: treebase, filter: filter, return_result: false) do |entry| puts "DN: #{entry.dn}" entry.each do |attribute, values| puts " #{attribute}:" values.each { |value| puts " -> #{value}" } end end ``` -------------------------------- ### Add New LDAP Entry with Ruby Net::LDAP Source: https://context7.com/ruby-ldap/ruby-net-ldap/llms.txt Demonstrates how to define and add a new entry to an LDAP directory using Net::LDAP. It shows defining the DN and attributes, performing the add operation, and handling success or failure responses. Includes an example of using Net::LDAP.open for multiple operations. ```ruby require 'net/ldap' # Assuming 'ldap' is an initialized Net::LDAP object # Example initialization: # ldap = Net::LDAP.new(...) # Define new entry dn = 'uid=jsmith,ou=people,dc=example,dc=com' attributes = { cn: 'John Smith', sn: 'Smith', givenName: 'John', mail: 'jsmith@example.com', uid: 'jsmith', uidNumber: '1001', gidNumber: '100', homeDirectory: '/home/jsmith', userPassword: Net::LDAP::Password.generate(:ssha, 'secretpassword'), objectClass: ['top', 'person', 'organizationalPerson', 'inetOrgPerson', 'posixAccount'] } # Add entry if ldap.add(dn: dn, attributes: attributes) puts "Entry added successfully" else result = ldap.get_operation_result puts "Add failed: #{result.code} - #{result.message}" puts "Details: #{result.error_message}" if result.error_message end # Using Net::LDAP.open for multiple operations # Replace 'auth_hash' with your actual authentication details # Net::LDAP.open(host: 'ldap.example.com', port: 389, auth: auth_hash) do |ldap| # ldap.add(dn: 'uid=user1,ou=people,dc=example,dc=com', attributes: attrs1) # ldap.add(dn: 'uid=user2,ou=people,dc=example,dc=com', attributes: attrs2) # end ``` -------------------------------- ### Run Specific Test File in ruby-net-ldap Source: https://github.com/ruby-ldap/ruby-net-ldap/blob/master/CONTRIBUTING.md Command to execute a specific test file within the ruby-net-ldap project's test suite. ```shell bundle exec ruby test/test_ldap.rb ``` -------------------------------- ### Run Specific Test in ruby-net-ldap Source: https://github.com/ruby-ldap/ruby-net-ldap/blob/master/CONTRIBUTING.md Command to run a particular test case within a specified test file in the ruby-net-ldap project. ```shell bundle exec ruby test/test_ldap.rb -n test_instrument_bind ``` -------------------------------- ### Perform Advanced LDAP Searches with Net::LDAP Source: https://context7.com/ruby-ldap/ruby-net-ldap/llms.txt Provides examples of advanced search operations using Net::LDAP, including specifying search scopes (BaseObject, SingleLevel, WholeSubtree), setting result size limits, and configuring search timeouts. Requires the Net::LDAP gem and a connection to an LDAP server. ```ruby require 'net/ldap' ldap = Net::LDAP.new(host: 'ldap.example.com', auth: auth_hash) # Search with different scopes # Base: Only search the base DN itself base_entry = ldap.search( base: 'uid=jsmith,ou=people,dc=example,dc=com', scope: Net::LDAP::SearchScope_BaseObject ) # One level: Direct children only direct_children = ldap.search( base: 'ou=people,dc=example,dc=com', scope: Net::LDAP::SearchScope_SingleLevel ) # Subtree: Entire subtree (default) all_entries = ldap.search( base: 'dc=example,dc=com', scope: Net::LDAP::SearchScope_WholeSubtree ) # Limit number of results limited_results = ldap.search( base: 'ou=people,dc=example,dc=com', size: 100 # Maximum 100 entries ) # Set search timeout (in seconds) timed_search = ldap.search( base: 'dc=example,dc=com', time: 10 # 10 second timeout ) ``` -------------------------------- ### Delete LDAP Entry and Tree with Ruby Net::LDAP Source: https://context7.com/ruby-ldap/ruby-net-ldap/llms.txt Provides code examples for removing entries from an LDAP directory using Net::LDAP. It demonstrates how to delete a single entry and how to delete an entire subtree recursively. Error handling for delete operations is also included. ```ruby require 'net/ldap' ldap = Net::LDAP.new( host: 'ldap.example.com', port: 389, auth: { method: :simple, username: 'cn=admin,dc=example,dc=com', password: 'secret' } ) # Delete single entry dn = 'uid=jsmith,ou=people,dc=example,dc=com' if ldap.delete(dn: dn) puts "Entry deleted successfully" else result = ldap.get_operation_result puts "Delete failed: #{result.code} - #{result.message}" end # Delete entry with all subordinate entries (tree delete) # Automatically uses DELETE_TREE control if supported, otherwise recursive delete organizational_unit = 'ou=oldteam,dc=example,dc=com' if ldap.delete_tree(dn: organizational_unit) puts "Tree deleted successfully" else puts "Tree delete failed: #{ldap.get_operation_result.message}" end ``` -------------------------------- ### Rename LDAP Entry with Ruby Net::LDAP Source: https://context7.com/ruby-ldap/ruby-net-ldap/llms.txt Illustrates how to change the distinguished name (DN) of an LDAP entry using Net::LDAP. The example shows renaming an entry by modifying its Relative Distinguished Name (RDN) and also mentions the 'modify_rdn' alias. ```ruby require 'net/ldap' ldap = Net::LDAP.new( host: 'ldap.example.com', port: 389, auth: { method: :simple, username: 'cn=admin,dc=example,dc=com', password: 'secret' } ) # Rename entry by changing its RDN (leftmost DN component) old_dn = 'uid=jsmith,ou=people,dc=example,dc=com' new_rdn = 'uid=john.smith' if ldap.rename(dn: old_dn, new_rdn: new_rdn) puts "Entry renamed successfully" puts "New DN: uid=john.smith,ou=people,dc=example,dc=com" else puts "Rename failed: #{ldap.get_operation_result.message}" end # Can also use modify_rdn (alias) # ldap.modify_rdn(dn: old_dn, new_rdn: 'cn=John Smith') ``` -------------------------------- ### Connect and Authenticate to LDAP (Ruby) Source: https://context7.com/ruby-ldap/ruby-net-ldap/llms.txt Demonstrates how to establish a connection to an LDAP server and authenticate using simple username/password credentials. It shows two methods: direct instantiation with authentication details and setting authentication after initialization. The code requires the 'net/ldap' gem. It returns a success message or an error code and message upon failed binding. ```ruby require 'net/ldap' # Method 1: Direct instantiation with authentication ldap = Net::LDAP.new( host: 'ldap.example.com', port: 389, auth: { method: :simple, username: 'cn=admin,dc=example,dc=com', password: 'secret' } ) if ldap.bind puts "Authentication successful" else result = ldap.get_operation_result puts "Failed: #{result.code} - #{result.message}" end # Method 2: Set authentication after initialization ldap = Net::LDAP.new(host: 'ldap.example.com', port: 389) ldap.auth('cn=admin,dc=example,dc=com', 'secret') if ldap.bind puts "Authenticated successfully" end ``` -------------------------------- ### Ruby Net::LDAP: Connection Timeout and Failover Configuration Source: https://context7.com/ruby-ldap/ruby-net-ldap/llms.txt Illustrates how to configure connection timeouts and set up failover for multiple LDAP servers using the Net::LDAP library. Handles connection timeout exceptions and demonstrates connecting to a list of hosts. Requires the 'net/ldap' gem. ```ruby require 'net/ldap' # Assuming auth_hash is defined # Set connection timeout (default is 5 seconds) ldap = Net::LDAP.new( host: 'ldap.example.com', port: 389, connect_timeout: 10, # 10 seconds auth: auth_hash ) begin ldap.bind rescue Errno::ETIMEDOUT => e puts "Connection timed out after 10 seconds" end # Configure failover with multiple hosts ldap = Net::LDAP.new( hosts: [ ['ldap1.example.com', 389], ['ldap2.example.com', 389], ['ldap3.example.com', 389] ], auth: auth_hash, connect_timeout: 3 ) # Will attempt each host in order until connection succeeds if ldap.bind puts "Connected successfully" else puts "All hosts failed" end # Base DN for searches ldap = Net::LDAP.new( host: 'ldap.example.com', port: 389, base: 'dc=example,dc=com', # Default base for searches auth: auth_hash ) # Search without specifying base (uses default) entries = ldap.search(filter: Net::LDAP::Filter.present('uid')) # Override default base other_entries = ldap.search( base: 'ou=groups,dc=example,dc=com', filter: Net::LDAP::Filter.eq('objectClass', 'groupOfNames') ) ``` -------------------------------- ### Discover Server Capabilities with Net::LDAP Source: https://context7.com/ruby-ldap/ruby-net-ldap/llms.txt Demonstrates how to query LDAP server capabilities and schema information using Net::LDAP. It includes fetching the root DSE, checking for paged search support, and retrieving schema details like object classes and attribute types. Requires the Net::LDAP gem and a connection to an LDAP server. ```ruby require 'net/ldap' ldap = Net::LDAP.new(host: 'ldap.example.com', port: 389) # Query root DSE (Directory Server Entry) root_dse = ldap.search_root_dse if root_dse puts "Naming Contexts:" root_dse[:namingContexts].each { |ctx| puts " #{ctx}" } puts "\nSupported LDAP Versions:" root_dse[:supportedLDAPVersion].each { |ver| puts " #{ver}" } puts "\nSupported Controls:" root_dse[:supportedControl].each { |ctrl| puts " #{ctrl}" } puts "\nSupported Extensions:" root_dse[:supportedExtension].each { |ext| puts " #{ext}" } puts "\nSupported SASL Mechanisms:" root_dse[:supportedSASLMechanisms].each { |mech| puts " #{mech}" } end # Check if server supports paged results if ldap.paged_searches_supported? puts "Server supports paged search results" end # Query schema information schema = ldap.search_subschema_entry if schema puts "\nObject Classes:" schema.objectclasses.first(5).each { |oc| puts " #{oc}" } puts "\nAttribute Types:" schema.attributetypes.first(5).each { |at| puts " #{at}" } end # Use capabilities to adapt behavior if ldap.paged_searches_supported? # Large search with paging ldap.search(base: 'dc=example,dc=com', size: 1000) else # Fall back to non-paged search ldap.search(base: 'dc=example,dc=com') end ``` -------------------------------- ### Authenticate Users with Ruby Net::LDAP Source: https://context7.com/ruby-ldap/ruby-net-ldap/llms.txt Demonstrates user authentication against an LDAP directory using Net::LDAP. It shows two methods: direct bind with user credentials and searching for a user followed by binding. Error handling for different authentication failure codes is included. ```ruby require 'net/ldap' ldap = Net::LDAP.new( host: 'ldap.example.com', port: 389, auth: { method: :simple, username: 'cn=admin,dc=example,dc=com', password: 'adminpassword' } ) # Method 1: Direct bind with user DN user_dn = 'uid=jsmith,ou=people,dc=example,dc=com' user_password = 'userpassword' ldap_user = Net::LDAP.new(host: 'ldap.example.com') if ldap_user.bind(method: :simple, username: user_dn, password: user_password) puts "User authenticated successfully" else result = ldap_user.get_operation_result case result.code when Net::LDAP::ResultCodeInvalidCredentials puts "Invalid username or password" when Net::LDAP::ResultCodeNoSuchObject puts "User not found" else puts "Authentication failed: #{result.message}" end end # Method 2: Search for user then bind (bind_as) # This part is not fully implemented in the provided snippet, but outlines the concept. ``` -------------------------------- ### Establish Secure TLS Connection with Net::LDAP Source: https://context7.com/ruby-ldap/ruby-net-ldap/llms.txt Demonstrates how to establish a secure connection using TLS with Net::LDAP. It includes error handling for connection failures. Requires the Net::LDAP gem and a configured LDAP server with TLS enabled. ```ruby require 'net/ldap' ldap = Net::LDAP.new(:host => 'ldap.example.com') ldap.use_ssl = true # Attempt bind (will raise error if cert validation fails) begin if ldap.bind puts "Secure connection established" end rescue Net::LDAP::ConnectionError => e puts "TLS connection failed: #{e.message}" end ``` -------------------------------- ### Ruby Net::LDAP: Error Handling and Result Codes Source: https://context7.com/ruby-ldap/ruby-net-ldap/llms.txt Shows how to properly handle LDAP operation errors and check result codes using the Net::LDAP library. Covers checking general operation results, handling specific LDAP result codes, and catching connection exceptions. Requires the 'net/ldap' gem. ```ruby require 'net/ldap' # Assuming ldap is an initialized Net::LDAP object with auth_hash defined ldap = Net::LDAP.new(host: 'ldap.example.com', auth: auth_hash) # Check result after any operation if ldap.bind puts "Bind successful" else result = ldap.get_operation_result puts "Error Code: #{result.code}" puts "Message: #{result.message}" puts "Error Details: #{result.error_message}" if result.error_message puts "Matched DN: #{result.matched_dn}" if result.matched_dn end # Handle specific result codes # Assuming result is obtained from ldap.get_operation_result case result.code when Net::LDAP::ResultCodeSuccess puts "Operation completed successfully" when Net::LDAP::ResultCodeInvalidCredentials puts "Authentication failed - invalid username or password" when Net::LDAP::ResultCodeNoSuchObject puts "Entry not found" when Net::LDAP::ResultCodeInsufficientAccessRights puts "Permission denied - insufficient access rights" when Net::LDAP::ResultCodeEntryAlreadyExists puts "Entry already exists" when Net::LDAP::ResultCodeObjectClassViolation puts "Schema violation - check required attributes and object classes" when Net::LDAP::ResultCodeConstraintViolation puts "Constraint violation" when Net::LDAP::ResultCodeUnavailable puts "Server unavailable" when Net::LDAP::ResultCodeBusy puts "Server busy - retry later" else puts "Error: #{Net::LDAP.result2string(result.code)}" end # Catch connection exceptions begin ldap.bind rescue Net::LDAP::ConnectionError => e puts "Connection failed: #{e.message}" rescue Net::LDAP::Error => e puts "LDAP error: #{e.class} - #{e.message}" end # Check search success with multiple acceptable codes # Assuming entries and result are obtained from ldap.search and ldap.get_operation_result if [ Net::LDAP::ResultCodeSuccess, Net::LDAP::ResultCodeSizeLimitExceeded, Net::LDAP::ResultCodeTimeLimitExceeded ].include?(result.code) puts "Search returned #{entries&.size || 0} entries" puts "Note: #{result.message}" unless result.code == Net::LDAP::ResultCodeSuccess end ``` -------------------------------- ### Build Complex LDAP Search Filters (Ruby) Source: https://context7.com/ruby-ldap/ruby-net-ldap/llms.txt Illustrates how to construct sophisticated LDAP search filters using Net::LDAP's filter DSL. It covers basic filters (equality, presence, wildcard), comparison operators, combining filters with AND/OR, negation, and nesting. The code also shows how to parse RFC 2254 filter strings and escape special characters for literal matching. Requires the 'net/ldap' gem. ```ruby require 'net/ldap' # Simple equality filter f1 = Net::LDAP::Filter.eq('cn', 'John Smith') # Output: (cn=John Smith) # Presence check f2 = Net::LDAP::Filter.present('mail') # Output: (mail=*) # Wildcard matching with automatic escaping f3 = Net::LDAP::Filter.begins('mail', 'john') # Output: (mail=john*) f4 = Net::LDAP::Filter.contains('cn', 'smith') # Output: (cn=*smith*) # Comparison operators f5 = Net::LDAP::Filter.ge('uidNumber', '1000') # greater or equal f6 = Net::LDAP::Filter.le('uidNumber', '5000') # less or equal # Combining filters with AND combined_and = f1 & f2 # Output: (&(cn=John Smith)(mail=*)) # Combining filters with OR combined_or = f1 | f2 # Output: (|(cn=John Smith)(mail=*)) # Negation not_filter = ~Net::LDAP::Filter.eq('accountStatus', 'disabled') # Output: (!(accountStatus=disabled)) # Complex nested filter complex_filter = Net::LDAP::Filter.eq('objectClass', 'inetOrgPerson') & (Net::LDAP::Filter.begins('mail', 'john') | Net::LDAP::Filter.begins('mail', 'jane')) & ~Net::LDAP::Filter.eq('accountStatus', 'disabled') # Output: (&(objectClass=inetOrgPerson)(|(mail=john*)(mail=jane*))(!(accountStatus=disabled))) # Parse RFC 2254 filter string filter_from_string = Net::LDAP::Filter.construct('(&(cn=*Smith)(mail=*@example.com))') # Escape special characters for literal matching escaped = Net::LDAP::Filter.escape('*special*') # => "\2Aspecial\2A" safe_filter = Net::LDAP::Filter.equals('cn', '*special*') # Output: (cn=\2Aspecial\2A) ``` -------------------------------- ### Authenticate User with Username and Password Source: https://context7.com/ruby-ldap/ruby-net-ldap/llms.txt Authenticates a user using their username and password against an LDAP directory. It searches for a user by their UID and then binds using the provided password. This is useful when the full Distinguished Name (DN) is not known beforehand. It outputs the user's DN and details if authentication is successful, otherwise indicates failure. ```ruby require 'net/ldap' # Assuming ldap object is already initialized ldap = Net::LDAP.new(host: 'ldap.example.com') # Replace with your LDAP host username = 'jsmith' password = 'userpassword' # Example using bind_as for username authentication begin result = ldap.bind_as( base: 'ou=people,dc=example,dc=com', # Replace with your base DN filter: "(uid=#{username})", password: password ) if result puts "User authenticated: #{result.first.dn}" puts "User details:" puts " Name: #{result.first.cn.first}" if result.first.cn puts " Email: #{result.first.mail.first}" if result.first.mail else puts "Authentication failed" end rescue Net::LDAP::Error => e puts "LDAP Error: #{e.message}" end # Example using auth with a password Proc for delayed evaluation # get_password = proc { STDIN.gets.chomp } # Use STDIN.gets for interactive input # ldap.auth('cn=admin,dc=example,dc=com', get_password) # Replace with your admin DN ``` -------------------------------- ### Ruby Net::LDAP: Who Am I Extended Operation Source: https://context7.com/ruby-ldap/ruby-net-ldap/llms.txt Demonstrates how to perform the 'who am I' extended operation using the Net::LDAP library to retrieve the authorization identity of the current connection. Requires the 'net/ldap' gem. ```ruby require 'net/ldap' ldap = Net::LDAP.new( host: 'ldap.example.com', port: 389, auth: { method: :simple, username: 'cn=admin,dc=example,dc=com', password: 'secret' } ) # Query current authorization identity identity = ldap.whoami if identity puts "Authenticated as: #{identity}" # => "dn:cn=admin,dc=example,dc=com" else puts "Who Am I operation failed: #{ldap.get_operation_result.message}" end # Can also use ldapwhoami auth_id = ldap.ldapwhoami puts "Authorization identity: #{auth_id}" ``` -------------------------------- ### Construct and Parse LDAP Distinguished Names with Net::LDAP Source: https://context7.com/ruby-ldap/ruby-net-ldap/llms.txt Shows how to build and parse LDAP distinguished names (DNs) using Net::LDAP::DN. It covers automatic escaping of special characters during construction and parsing DNs into key-value pairs or arrays. Requires the Net::LDAP gem. ```ruby require 'net/ldap' # Construct DN with automatic escaping dn = Net::LDAP::DN.new('cn', 'Smith, John', 'dc=example,dc=com') puts dn.to_s # => "cn=Smith\, John,dc=example,dc=com" # Escape special characters in DN components escaped = Net::LDAP::DN.escape('Smith, John Jr. (Manager)') # => "Smith\, John Jr. \(Manager\)" # Build DN with multiple components dn = Net::LDAP::DN.new( 'uid', 'jsmith', 'ou', 'people', 'dc=example,dc=com' ) puts dn.to_s # => "uid=jsmith,ou=people,dc=example,dc=com" # Parse DN into key-value pairs dn = Net::LDAP::DN.new('uid=jsmith,ou=people,dc=example,dc=com') dn.each_pair do |key, value| puts "#{key}: #{value}" end # Output: # uid: jsmith # ou: people # dc: example # dc: com # Convert to array dn_array = dn.to_a # => ["uid", "jsmith", "ou", "people", "dc", "example", "dc", "com"] ``` -------------------------------- ### Maintain Persistent LDAP Connections with Net::LDAP Source: https://context7.com/ruby-ldap/ruby-net-ldap/llms.txt Illustrates how to maintain persistent connections to an LDAP server for multiple operations using Net::LDAP. It shows two methods: instance-level `open` block and class-level `open` block, both ensuring the connection is automatically closed. Performing operations without `open` results in a new connection for each operation. Requires the Net::LDAP gem and an LDAP server connection. ```ruby require 'net/ldap' # Method 1: Instance open (recommended for object reuse) ldap = Net::LDAP.new( host: 'ldap.example.com', port: 389, auth: { method: :simple, username: 'cn=admin,dc=example,dc=com', password: 'secret' } ) ldap.open do |connection| # All operations share the same connection users = connection.search(base: 'ou=people,dc=example,dc=com') users.each do |user| # Modify each user connection.modify( dn: user.dn, operations: [[:add, :description, 'Updated batch']] ) end # Add new entries connection.add(dn: 'uid=new1,ou=people,dc=example,dc=com', attributes: attrs1) connection.add(dn: 'uid=new2,ou=people,dc=example,dc=com', attributes: attrs2) end # Connection automatically closed after block # Method 2: Class-level open Net::LDAP.open( host: 'ldap.example.com', port: 389, auth: auth_hash ) do |ldap| result1 = ldap.search(base: 'ou=people,dc=example,dc=com') result2 = ldap.search(base: 'ou=groups,dc=example,dc=com') ldap.add(dn: 'uid=temp,ou=people,dc=example,dc=com', attributes: temp_attrs) ldap.delete(dn: 'uid=temp,ou=people,dc=example,dc=com') end # Without open (each operation creates new connection) ldap = Net::LDAP.new(host: 'ldap.example.com', auth: auth_hash)ldap.search(base: 'dc=example,dc=com') # Opens and closes connectionldap.add(dn: 'uid=user,ou=people,dc=example,dc=com', attributes: attrs) # New connection ``` -------------------------------- ### Manipulate LDAP Entry Objects Source: https://context7.com/ruby-ldap/ruby-net-ldap/llms.txt Shows how to search for LDAP entries and access their attributes using various methods (direct access, array-like, and method calls). It covers handling multi-valued attributes, iterating through all attributes, converting an entry to a hash, and converting an entry to LDIF format. It also includes parsing an LDIF string back into an entry object. ```ruby require 'net/ldap' # Assuming ldap object is already initialized ldap = Net::LDAP.new(host: 'ldap.example.com') # Replace with your LDAP host # Assuming auth_hash is configured # Search and access entry attributes entry = ldap.search( base: 'uid=jsmith,ou=people,dc=example,dc=com', scope: Net::LDAP::SearchScope_BaseObject ).first if entry # Access attributes multiple ways puts "DN: #{entry.dn}" puts "CN: #{entry['cn'].first}" puts "CN (symbol): #{entry[:cn].first}" puts "CN (method): #{entry.cn.first}" # Multi-valued attributes if entry.mail entry.mail.each do |email| puts "Email: #{email}" end end # List all attributes puts "\nAll Attributes:" entry.attribute_names.each do |attr| puts "#{attr}: #{entry[attr].join(', ')}" end # Iterate over all attributes puts "\nIterating Attributes:" entry.each do |attribute, values| puts "#{attribute}:" values.each { |value| puts " -> #{value}" } end # Convert to hash entry_hash = entry.to_h puts "\nEntry Hash: #{entry_hash}" # Convert to LDIF ldif = entry.to_ldif puts "\nEntry LDIF:\n#{ldif}" # Parse LDIF string to entry ldif_string = """ dn: uid=jsmith,ou=people,dc=example,dc=com cn: John Smith mail: jsmith@example.com objectClass: inetOrgPerson """ parsed_entry = Net::LDAP::Entry.from_single_ldif_string(ldif_string) puts "\nParsed Entry CN: #{parsed_entry.cn.first}" else puts "Entry not found." end ``` -------------------------------- ### Generate and Modify LDAP Passwords Source: https://context7.com/ruby-ldap/ruby-net-ldap/llms.txt Demonstrates how to generate various types of password hashes (MD5, SHA, SSHA, SSHA256) using `Net::LDAP::Password.generate`. It also shows how to use these hashes when creating new entries and how to modify existing passwords using the `password_modify` method, including the capability for the server to generate a new password. ```ruby require 'net/ldap' # Assuming ldap object is already initialized ldap = Net::LDAP.new(host: 'ldap.example.com') # Replace with your LDAP host # Generate password hashes md5_hash = Net::LDAP::Password.generate(:md5, 'secret') # => "{MD5}Xr4ilOzQ4PCOq3aQ0qbuaQ==" sha_hash = Net::LDAP::Password.generate(:sha, 'secret') # => "{SHA}5en6G6MezRroT3XKqkdPOmY/BfQ=" ssha_hash = Net::LDAP::Password.generate(:ssha, 'secret') # => "{SSHA}WjgMKrJMX9+h9Xy/p7R8qYzVv3QNPT8W" (random salt) ssha256_hash = Net::LDAP::Password.generate(:ssha256, 'secret') # => "{SSHA256}..." (salted SHA-256) # Use in entry creation attributes = { cn: 'John Smith', uid: 'jsmith', userPassword: Net::LDAP::Password.generate(:ssha, 'userpassword'), objectClass: ['top', 'person', 'inetOrgPerson'] } # Assuming admin_auth is configured # ldap.add(dn: 'uid=jsmith,ou=people,dc=example,dc=com', attributes: attributes) # Modify existing password using password_modify (RFC 3062) dn = 'uid=jsmith,ou=people,dc=example,dc=com' auth_as_user = { method: :simple, username: dn, password: 'oldpassword' } begin if ldap.password_modify( dn: dn, auth: auth_as_user, old_password: 'oldpassword', new_password: 'newpassword' ) puts "Password changed successfully" else puts "Password change failed: #{ldap.get_operation_result.message}" end rescue Net::LDAP::Error => e puts "LDAP Error during password modify: #{e.message}" end # Let server generate password (requires server support) # begin # ldap.password_modify(dn: dn, auth: auth_as_user, old_password: 'current') # generated_password = ldap.get_operation_result.extended_response[0][0] # puts "Server generated password: #{generated_password}" # rescue Net::LDAP::Error => e # puts "Failed to let server generate password: #{e.message}" # end ``` -------------------------------- ### Modify LDAP Entry Attributes with Ruby Net::LDAP Source: https://context7.com/ruby-ldap/ruby-net-ldap/llms.txt Shows how to update attribute values of existing LDAP entries using Net::LDAP. It covers using the 'modify' method with an operations array for adding, replacing, or deleting attributes, as well as using convenience methods like 'add_attribute', 'replace_attribute', and 'delete_attribute'. ```ruby require 'net/ldap' ldap = Net::LDAP.new( host: 'ldap.example.com', port: 389, auth: { method: :simple, username: 'cn=admin,dc=example,dc=com', password: 'secret' } ) dn = 'uid=jsmith,ou=people,dc=example,dc=com' # Method 1: Using modify with operations array operations = [ [:add, :mail, 'john.smith@example.com'], [:replace, :telephoneNumber, '+1-555-1234'], [:delete, :description, nil] # nil deletes entire attribute ] if ldap.modify(dn: dn, operations: operations) puts "Modifications successful" else puts "Modify failed: #{ldap.get_operation_result.message}" end # Method 2: Using convenience methods ldap.add_attribute(dn, :mail, 'jsmith@company.com') ldap.replace_attribute(dn, :telephoneNumber, ['+1-555-9999', '+1-555-8888']) ldap.delete_attribute(dn, :description) # Modify multiple values in one operation multi_ops = [ [:replace, :cn, 'John Q. Smith'], [:add, :title, 'Senior Developer'], [:replace, :mail, ['john.smith@example.com', 'jsmith@example.com']], [:delete, :mobile, '+1-555-0000'] ] ldap.modify(dn: dn, operations: multi_ops) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.