Skip to content

Commit

Permalink
implements parsing connection string like Postgres
Browse files Browse the repository at this point in the history
  • Loading branch information
rvalyi committed Jul 20, 2017
1 parent 33ce648 commit 0aeda89
Show file tree
Hide file tree
Showing 7 changed files with 289 additions and 74 deletions.
63 changes: 24 additions & 39 deletions bin/ooor
Expand Up @@ -7,52 +7,37 @@ require 'rubygems'
require 'logger'
require 'ooor'
require 'irb/completion'

unless ARGV.empty?
username = ARGV[0].split(".")[0]
database = ARGV[0].split(".")[1..100].join(".").split("@")[0]
if ARGV[0].index("@")
base_url = ARGV[0].split("@")[1]
else
base_url = "localhost"
end
port_given = false
if base_url.index(":") #port in URL
t = base_url.split(":")
base_url = t[0]
port = t[1]
port_given = true
else
port = "8069"
end

if ARGV[1] == "-s" || ARGV[2] == "-s" #secure mode
port = 443 unless port_given
protocol = "https"
else
protocol = "http"
end

url = "#{protocol}://#{base_url}:#{port}/xmlrpc"
if ARGV[1] && ARGV[1] != "-s"
password = ARGV[1]
else
puts "password?"
system "stty -echo"
password = $stdin.gets.chomp!
system "stty echo"
password = 'admin' if password.blank?
end

else


if ARGV.empty? || ARGV[0].sub('--', '') == 'help'
puts "USAGE: ooor admin.database@host\nor ooor admin.database@host:port\nor ooor admin.database for localhost\nyou can specify the password with ooor admin.database@host password\nyou can use the -s option for secure HTTPS mode"
exit 0
end

cs = ARGV.join
ARGV[0] = "--readline"
ARGV[1] = "--prompt"
ARGV[2] = "inf-ruby"

@ooor = Ooor.new(:url => url, :database => database || 'demo', :username => username || 'admin', :password => password || 'admin', :log_level => Logger::INFO)
Ooor.set_default_config(cs)

unless Ooor.default_config[:password]
puts "password?"
system "stty -echo"
password = $stdin.gets.chomp!
system "stty echo"
password = 'admin' if password.blank?
Ooor.default_config[:password] = password
end

unless Ooor.default_config[:database]
puts "database?"
system "stty -echo"
password = $stdin.gets.chomp!
system "stty echo"
database = 'db' if database.blank?
Ooor.default_config[:database] = database
end

@ooor = Ooor.new(Ooor.default_config)
IRB.start(__FILE__)
16 changes: 11 additions & 5 deletions lib/ooor.rb
Expand Up @@ -42,7 +42,7 @@ module Ooor
module OoorBehavior
extend ActiveSupport::Concern
module ClassMethods

attr_accessor :default_config, :default_session, :cache_store

IRREGULAR_CONTEXT_POSITIONS = {
Expand All @@ -57,11 +57,17 @@ module ClassMethods
check_recursion: 1
}

def set_default_config(config)
config = session_handler.format_config(config)
config.merge!(generate_constants: true)
self.default_config = config
end

def new(config={})
Ooor.default_config = config.merge(generate_constants: true)
session = session_handler.retrieve_session(config, :noweb)
if config[:database] && config[:password]
session.global_login(config)
set_default_config(config)
session = session_handler.retrieve_session(default_config, :noweb)
if default_config[:database] && default_config[:password] && default_config[:bootstrap] != false
session.global_login()
end
Ooor.default_session = session
end
Expand Down
20 changes: 2 additions & 18 deletions lib/ooor/railtie.rb
Expand Up @@ -6,14 +6,10 @@ module Ooor
class Railtie < Rails::Railtie
initializer "ooor.middleware" do |app|
Ooor.logger = Rails.logger unless $0 != 'irb'
Ooor.default_config = load_config(false, Rails.env)
Ooor.logger.level = @config[:log_level] if @config[:log_level]
Ooor.cache_store = Rails.cache
Ooor.default_session = Ooor.session_handler.retrieve_session(Ooor.default_config, :noweb)
Ooor.new("#{Rails.root}/config/ooor.yml")
Ooor.logger.level = Ooor.default_config[:log_level] if Ooor.default_config[:log_level]

if Ooor.default_config[:bootstrap]
Ooor.default_session.global_login(config.merge(generate_constants: true))
end
unless Ooor.default_config[:disable_locale_switcher]
if defined?(Rack::I18nLocaleSwitcher)
app.middleware.use '::Rack::I18nLocaleSwitcher'
Expand All @@ -27,17 +23,5 @@ class Railtie < Rails::Railtie
app.middleware.insert_after ::Rack::Head, ::Ooor::Rack
end
end

def load_config(config_file=nil, env=nil)
config_file ||= defined?(Rails.root) && "#{Rails.root}/config/ooor.yml" || 'ooor.yml'
config_parsed = ::YAML.load(ERB.new(File.new(config_file).read).result)
@config = HashWithIndifferentAccess.new(config_parsed)[env || 'development']
rescue SystemCallError
Ooor.logger.error """failed to load OOOR yaml configuration file.
make sure your app has a #{config_file} file correctly set up
if not, just copy/paste the default ooor.yml file from the OOOR Gem
to #{Rails.root}/config/ooor.yml and customize it properly\n\n"""
{}
end
end
end
16 changes: 6 additions & 10 deletions lib/ooor/session.rb
Expand Up @@ -34,7 +34,7 @@ def public_controller_method(path, query_values={})
end

def initialize(config, web_session, id)
set_config(_config(config))
set_config(HashWithIndifferentAccess.new(config))
Object.const_set(config[:scope_prefix], Module.new) if config[:scope_prefix]
@models = {}
@local_context = {}
Expand All @@ -51,6 +51,9 @@ def login_if_required

def login(db, username, password, kw={})
logger.debug "OOOR login - db: #{db}, username: #{username}"
raise "Cannot login without specifying a database" unless db
raise "Cannot login without specifying a username" unless username
raise "Cannot login without specifying a password" unless password
if config[:force_xml_rpc]
send("ooor_alias_login", db, username, password)
else
Expand Down Expand Up @@ -104,9 +107,9 @@ def []=(key, value)
self[key] = value
end

def global_login(options)
def global_login(options={})
set_config(options)
load_models(config[:models], options[:reload])
load_models(config[:models], config[:reload])
end

def with_context(context)
Expand Down Expand Up @@ -243,12 +246,5 @@ def odoo_serie
end
end

private

def _config(config)
c = config.is_a?(String) ? Ooor.load_config(config, env) : config #TODO env, see old Connection
HashWithIndifferentAccess.new(c)
end

end
end
114 changes: 114 additions & 0 deletions lib/ooor/session_handler.rb
Expand Up @@ -10,6 +10,32 @@ def noweb_session_spec(config)
"#{config[:url]}-#{config[:database]}-#{config[:username]}"
end

# gives a hash config from a connection string or a yaml file, injects default values
def format_config(config)
if config.is_a?(String) && config.end_with?('.yml')
env = defined?(Rails.env) ? Rails.env : nil
config = load_config_file(config, env)
end
if config.is_a?(String)
cs = config
config = {}
elsif config[:ooor_url]
cs = config[:ooor_url]
elsif ENV['OOOR_URL']
cs = ENV['OOOR_URL'].dup()
end
config.merge!(parse_connection_string(cs)) if cs

defaults = {
url: 'http://localhost:8069',
username: 'admin',
}
defaults[:password] = ENV['OOOR_PASSWORD'] if ENV['OOOR_PASSWORD']
defaults[:username] = ENV['OOOR_USERNAME'] if ENV['OOOR_USERNAME']
defaults[:database] = ENV['OOOR_DATABASE'] if ENV['OOOR_DATABASE']
defaults.merge(config)
end

def retrieve_session(config, id=nil, web_session={})
id ||= SecureRandom.hex(16)
if id == :noweb
Expand Down Expand Up @@ -62,5 +88,93 @@ def set_web_session(key, web_session)

def sessions; @sessions ||= {}; end
def connections; @connections ||= {}; end


private

def load_config_file(config_file=nil, env=nil)
config_file ||= defined?(Rails.root) && "#{Rails.root}/config/ooor.yml" || 'ooor.yml'
config_parsed = ::YAML.load(ERB.new(File.new(config_file).read).result)
HashWithIndifferentAccess.new(config_parsed)[env || 'development']
rescue SystemCallError
Ooor.logger.error """failed to load OOOR yaml configuration file.
make sure your app has a #{config_file} file correctly set up
if not, just copy/paste the default ooor.yml file from the OOOR Gem
to #{Rails.root}/config/ooor.yml and customize it properly\n\n"""
{}
end

def parse_connection_string(cs)
if cs.start_with?('ooor://') && ! cs.index('@')
cs.sub!(/^ooor:\/\//, '@')
end

cs.sub!(/^http:\/\//, '')
cs.sub!(/^ooor:/, '')
cs.sub!(/^ooor:/, '')
cs.sub!('//', '')
if cs.index('ssl=true')
ssl = true
cs.gsub!('?ssl=true', '').gsub!('ssl=true', '')
end
if cs.index(' -s')
ssl = true
cs.gsub!(' -s', '')
end

if cs.index('@')
parts = cs.split('@')
right = parts[1]
left = parts[0]
if right.index('/')
parts = right.split('/')
database = parts[1]
host, port = parse_host_port(parts[0])
else
host, port = parse_host_port(right)
end

if left.index(':')
user_pwd = left.split(':')
username = user_pwd[0]
password = user_pwd[1]
else
if left.index('.') && !database
username = left.split('.')[0]
database = left.split('.')[1]
else
username = left
end
end
else
host, port = parse_host_port(cs)
end

host ||= 'localhost'
port ||= 8069
if port == 443
ssl = true
end
username = 'admin' if username.blank?
{
url: "#{ssl ? 'https' : 'http'}://#{host}:#{port}",
username: username,
database: database,
password: password,
}.select { |_, value| !value.nil? } # .compact() on Rails > 4
end

def parse_host_port(host_port)
if host_port.index(':')
host_port = host_port.split(':')
host = host_port[0]
port = host_port[1].to_i
else
host = host_port
port = 80
end
return host, port
end

end
end

0 comments on commit 0aeda89

Please sign in to comment.