class IDRAC::Client
def authenticated_request(method, path, options = {}, retry_count = 0)
def authenticated_request(method, path, options = {}, retry_count = 0) # Limit retries to prevent infinite loops if retry_count >= 3 # If we've tried too many times, switch to direct mode @direct_mode = true puts "Switching to direct mode after multiple authentication failures" end # Ensure we have a valid session (unless in direct mode) unless @direct_mode begin login unless @x_auth_token rescue Error => e # If login fails and we've tried too many times, switch to direct mode if retry_count >= 2 @direct_mode = true puts "Switching to direct mode after multiple authentication failures" else # Re-raise other errors raise end end end options[:headers] ||= {} # Use X-Auth-Token if available (preferred Redfish method) if @x_auth_token options[:headers]['X-Auth-Token'] = @x_auth_token elsif @direct_mode # In direct mode, use Basic Auth options[:headers]['Authorization'] = "Basic #{Base64.strict_encode64("#{username}:#{password}")}" end response = connection.send(method, path, options[:params]) do |req| req.headers.merge!(options[:headers]) req.body = options[:body] if options[:body] end # Handle authentication errors if response.status == 401 && !@direct_mode puts "Session expired, re-authenticating..." logout sleep(2) login # Update headers with new authentication options[:headers] ||= {} if @x_auth_token options[:headers]['X-Auth-Token'] = @x_auth_token elsif @direct_mode options[:headers]['Authorization'] = "Basic #{Base64.strict_encode64("#{username}:#{password}")}" end response = connection.send(method, path, options[:params]) do |req| req.headers.merge!(options[:headers]) req.body = options[:body] if options[:body] end # If we still get a 401, switch to direct mode if response.status == 401 && retry_count < 2 @direct_mode = true puts "Switching to direct mode after authentication failure" return authenticated_request(method, path, options, retry_count + 1) end end response end