1 # Filters added to this controller will be run for all controllers in the application.
2 # Likewise, all the methods added will be available for all controllers.
3 class ApplicationController < ActionController::Base
7 @user = User.find(session[:user])
9 @user = User.authenticate(:token => session[:token])
10 session[:user] = @user.id
12 rescue Exception => ex
13 logger.info("Exception authorizing user: #{ex.to_s}")
18 redirect_to :controller => 'user', :action => 'login', :referer => request.request_uri unless @user
21 def authorize(realm='Web Password', errormessage="Couldn't authenticate you")
22 username, passwd = get_auth_data # parse from headers
23 # authenticate per-scheme
25 @user = nil # no authentication provided - perhaps first connect (client should retry after 401)
26 elsif username == 'token'
27 @user = User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
29 @user = User.authenticate(:username => username, :password => passwd) # basic auth
32 # handle authenticate pass/fail
34 # no auth, the user does not exist or the password was wrong
35 response.headers["Status"] = "Unauthorized"
36 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
37 render :text => errormessage, :status => :unauthorized
42 def check_read_availability
43 if API_STATUS == :offline
44 response.headers['Error'] = "Database offline for maintenance"
45 render :nothing => true, :status => :service_unavailable
50 def check_write_availability
51 if API_STATUS == :offline or API_STATUS == :readonly
52 response.headers['Error'] = "Database offline for maintenance"
53 render :nothing => true, :status => :service_unavailable
58 # Report and error to the user
59 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
60 # rather than only a status code and having the web engine make up a
61 # phrase from that, we can also put the error message into the status
62 # message. For now, rails won't let us)
63 def report_error(message)
64 render :text => message, :status => :bad_request
65 # Todo: some sort of escaping of problem characters in the message
66 response.headers['Error'] = message
71 # extract authorisation credentials from headers, returns user = nil if none
73 if request.env.has_key? 'X-HTTP_AUTHORIZATION' # where mod_rewrite might have put it
74 authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split
75 elsif request.env.has_key? 'REDIRECT_X_HTTP_AUTHORIZATION' # mod_fcgi
76 authdata = request.env['REDIRECT_X_HTTP_AUTHORIZATION'].to_s.split
77 elsif request.env.has_key? 'HTTP_AUTHORIZATION' # regular location
78 authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
80 # only basic authentication supported
81 if authdata and authdata[0] == 'Basic'
82 user, pass = Base64.decode64(authdata[1]).split(':',2)