Class: CASServer::Server

Inherits:
Sinatra::Base
  • Object
show all
Includes:
CAS, Localization
Defined in:
lib/casserver/server.rb

Constant Summary collapse

CONFIG_FILE =
"/etc/synapses-cas/config.yml"

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Localization

included

Methods included from CAS

clean_service_url, #generate_login_ticket, #generate_proxy_granting_ticket, #generate_proxy_ticket, #generate_service_ticket, #generate_ticket_granting_ticket, #send_logout_notification_for_service_ticket, #service_uri_with_ticket, #validate_login_ticket, #validate_proxy_granting_ticket, #validate_proxy_ticket, #validate_service_ticket, #validate_ticket_granting_ticket

Class Method Details

.handler_optionsObject



153
154
155
156
157
158
159
160
# File 'lib/casserver/server.rb', line 153

def self.handler_options
  handler_options = {
    :Host => bind || config[:bind_address],
    :Port => config[:port] || 443
  }

  handler_options.merge(handler_ssl_options).to_hash.symbolize_keys!
end

.handler_ssl_optionsObject



162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/casserver/server.rb', line 162

def self.handler_ssl_options
  return {} unless config[:ssl_cert]

  cert_path = config[:ssl_cert]
  key_path = config[:ssl_key] || config[:ssl_cert]
  
  unless cert_path.nil? && key_path.nil?
    raise "The ssl_cert and ssl_key options cannot be used with mongrel. You will have to run your " +
      " server behind a reverse proxy if you want SSL under mongrel." if
        config[:server] == 'mongrel'

    raise "The specified certificate file #{cert_path.inspect} does not exist or is not readable. " +
      " Your 'ssl_cert' configuration setting must be a path to a valid " +
      " ssl certificate." unless
        File.exists? cert_path

    raise "The specified key file #{key_path.inspect} does not exist or is not readable. " +
      " Your 'ssl_key' configuration setting must be a path to a valid " +
      " ssl private key." unless
        File.exists? key_path

    require 'openssl'
    require 'webrick/https'

    cert = OpenSSL::X509::Certificate.new(File.read(cert_path))
    key = OpenSSL::PKey::RSA.new(File.read(key_path))

    {
      :SSLEnable        => true,
      :SSLVerifyClient  => ::OpenSSL::SSL::VERIFY_NONE,
      :SSLCertificate   => cert,
      :SSLPrivateKey    => key
    }
  end
end

.init_authenticators!Object



198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/casserver/server.rb', line 198

def self.init_authenticators!
  auth = []
  
  if config[:authenticator].nil?
    print_cli_message "No authenticators have been configured. Please double-check your config file (#{CONFIG_FILE.inspect}).", :error
    exit 1
  end
  
  begin
    # attempt to instantiate the authenticator
    config[:authenticator] = [config[:authenticator]] unless config[:authenticator].instance_of? Array
    config[:authenticator].each { |authenticator| auth << authenticator[:class].constantize}
  rescue NameError
    if config[:authenticator].instance_of? Array
      config[:authenticator].each do |authenticator|
        if !authenticator[:source].nil?
          # config.yml explicitly names source file
          require authenticator[:source]
        else
          # the authenticator class hasn't yet been loaded, so lets try to load it from the casserver/authenticators directory
          auth_rb = authenticator[:class].underscore.gsub('cas_server/', '')
          require 'casserver/'+auth_rb
        end
        auth << authenticator[:class].constantize
      end
    else
      if config[:authenticator][:source]
        # config.yml explicitly names source file
        require config[:authenticator][:source]
      else
        # the authenticator class hasn't yet been loaded, so lets try to load it from the casserver/authenticators directory
        auth_rb = config[:authenticator][:class].underscore.gsub('cas_server/', '')
        require 'casserver/'+auth_rb
      end

      auth << config[:authenticator][:class].constantize
      config[:authenticator] = [config[:authenticator]]
    end
  end

  auth.zip(config[:authenticator]).each_with_index{ |auth_conf, index|
    authenticator, conf = auth_conf
    $LOG.debug "About to setup #{authenticator} with #{conf.inspect}..."
    authenticator.setup(conf.merge('auth_index' => index)) if authenticator.respond_to?(:setup)
    $LOG.debug "Done setting up #{authenticator}."
  }

  set :auth, auth
end

.init_database!Object



268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
# File 'lib/casserver/server.rb', line 268

def self.init_database!

  unless config[:disable_auto_migrations]
    ActiveRecord::Base.establish_connection(config[:database])
    print_cli_message "Running migrations to make sure your database schema is up to date..."
    prev_db_log = ActiveRecord::Base.logger
    ActiveRecord::Base.logger = Logger.new(STDOUT)
    ActiveRecord::Migration.verbose = true
    ActiveRecord::Migrator.migrate(File.dirname(__FILE__) + "/../../db/migrate")
    ActiveRecord::Base.logger = prev_db_log
    print_cli_message "Your database is now up to date."
  end
  
  ActiveRecord::Base.establish_connection(config[:database])
end

.init_logger!Object



248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/casserver/server.rb', line 248

def self.init_logger!
  if config[:log]
    if $LOG && config[:log][:file]
      print_cli_message "Redirecting RubyCAS-Server log to #{config[:log][:file]}"
      #$LOG.close
      $LOG = Logger.new(config[:log][:file])
    end
    $LOG.level = Logger.const_get(config[:log][:level]) if config[:log][:level]
  end
  
  if config[:db_log]
    if $LOG && config[:db_log][:file]
      $LOG.debug "Redirecting ActiveRecord log to #{config[:log][:file]}"
      #$LOG.close
      ActiveRecord::Base.logger = Logger.new(config[:db_log][:file])
    end
    ActiveRecord::Base.logger.level = Logger.const_get(config[:db_log][:level]) if config[:db_log][:level]
  end
end

.load_config_file(config_file) ⇒ Object



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/casserver/server.rb', line 108

def self.load_config_file(config_file)
  begin
    config_file = File.open(config_file)
  rescue Errno::ENOENT => e
    
    print_cli_message "Config file #{config_file} does not exist!", :error
    print_cli_message "Would you like the default config file copied to #{config_file.inspect}? [y/N]"
    if gets.strip.downcase == 'y'
      require 'fileutils'
      default_config = File.dirname(__FILE__) + '/../../config/config.example.yml'
      
      if !File.exists?(File.dirname(config_file))
        print_cli_message "Creating config directory..."
        FileUtils.mkdir_p(File.dirname(config_file), :verbose => true)
      end
      
      print_cli_message "Copying #{default_config.inspect} to #{config_file.inspect}..."
      FileUtils.cp(default_config, config_file, :verbose => true)
      print_cli_message "The default config has been copied. You should now edit it and try starting again."
      exit
    else
      print_cli_message "Cannot start RubyCAS-Server without a valid config file.", :error
      raise e
    end
  rescue Errno::EACCES => e
    print_cli_message "Config file #{config_file.inspect} is not readable (permission denied)!", :error
    raise e
  rescue => e
    print_cli_message "Config file #{config_file.inspect} could not be read!", :error
    raise e
  end
  
  config.merge! HashWithIndifferentAccess.new(YAML.load(config_file))
  set :server, config[:server] || 'webrick'
end


90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/casserver/server.rb', line 90

def self.print_cli_message(msg, type = :info)
  if respond_to?(:config) && config && config[:quiet]
    return
  end
  
  if type == :error
    io = $stderr
    prefix = "!!! "
  else
    io = $stdout
    prefix = ">>> "
  end
  
  io.puts
  io.puts "#{prefix}#{msg}"
  io.puts
end

.quit!(server, handler_name) ⇒ Object



84
85
86
87
88
# File 'lib/casserver/server.rb', line 84

def self.quit!(server, handler_name)
  ## Use thins' hard #stop! if available, otherwise just #stop
  server.respond_to?(:stop!) ? server.stop! : server.stop
  puts "\n== Synapses-CAS Server is shutting down" unless handler_name =~/cgi/i
end

.reconfigure!(config) ⇒ Object



144
145
146
147
148
149
150
151
# File 'lib/casserver/server.rb', line 144

def self.reconfigure!(config)
  config.each do |key, val|
    self.config[key] = val
  end
  init_database!
  init_logger!
  init_authenticators!
end

.run!(options = {}) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/casserver/server.rb', line 60

def self.run!(options={})
  set options

  handler      = detect_rack_handler
  handler_name = handler.name.gsub(/.*::/, '')
  
  puts "== Synapses-CAS Server is starting up " +
    "on port #{config[:port] || port} for #{environment} with backup from #{handler_name}" unless handler_name =~/cgi/i
    
  begin
    opts = handler_options
  rescue Exception => e
    print_cli_message e, :error
    raise e
  end
    
  handler.run self, opts do |server|
    [:INT, :TERM].each { |sig| trap(sig) { quit!(server, handler_name) } }
    set :running, true
  end
rescue Errno::EADDRINUSE => e
  puts "== Something is already running on port #{port}!"
end

.uri_pathObject



40
41
42
# File 'lib/casserver/server.rb', line 40

def self.uri_path
  config[:uri_path]
end

.use_public_folder?Boolean

Use :public_folder for Sinatra >= 1.3, and :public for older versions.

Returns:

  • (Boolean)


23
24
25
# File 'lib/casserver/server.rb', line 23

def self.use_public_folder?
  Sinatra.const_defined?("VERSION") && Gem::Version.new(Sinatra::VERSION) >= Gem::Version.new("1.3.0")
end

Instance Method Details

#compile_template(engine, data, options, views) ⇒ Object



780
781
782
783
784
785
# File 'lib/casserver/server.rb', line 780

def compile_template(engine, data, options, views)
  super engine, data, options, @custom_views || views
rescue Errno::ENOENT
  raise unless @custom_views
  super engine, data, options, views
end

#response_status_from_error(error) ⇒ Object

Helpers



757
758
759
760
761
762
763
764
765
766
# File 'lib/casserver/server.rb', line 757

def response_status_from_error(error)
  case error.code.to_s
  when /^INVALID_/, 'BAD_PGT'
    422
  when 'INTERNAL_ERROR'
    500
  else
    500
  end
end

#serialize_extra_attribute(builder, key, value) ⇒ Object



768
769
770
771
772
773
774
775
776
777
778
# File 'lib/casserver/server.rb', line 768

def serialize_extra_attribute(builder, key, value)
  if value.kind_of?(String)
    builder.tag! key, value
  elsif value.kind_of?(Numeric)
    builder.tag! key, value.to_s
  else
    builder.tag! key do
      builder.cdata! value.to_yaml
    end
  end
end

#static!Object

Strip the config.uri_path from the request.path_info… FIXME: do we really need to override all of Sinatra’s #static! to make this happen?



46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/casserver/server.rb', line 46

def static!
  # Workaround for differences in Sinatra versions.
  public_dir = Server.use_public_folder? ? settings.public_folder : settings.public
  return if public_dir.nil?
  public_dir = File.expand_path(public_dir)
  
  path = File.expand_path(public_dir + unescape(request.path_info.gsub(/^#{settings.config[:uri_path]}/,'')))
  return if path[0, public_dir.length] != public_dir
  return unless File.file?(path)

  env['sinatra.static_file'] = path
  send_file path, :disposition => nil
end