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_availability
44 response.headers['Error'] = "Database offline for maintenance"
45 render :nothing => true, :status => :service_unavailable
50 # Report and error to the user
51 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
52 # rather than only a status code and having the web engine make up a
53 # phrase from that, we can also put the error message into the status
54 # message. For now, rails won't let us)
55 def report_error(message)
56 render :nothing => true, :status => :bad_request
57 # Todo: some sort of escaping of problem characters in the message
58 response.headers['Error'] = message
63 # extract authorisation credentials from headers, returns user = nil if none
65 if request.env.has_key? 'X-HTTP_AUTHORIZATION' # where mod_rewrite might have put it
66 authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split
67 elsif request.env.has_key? 'HTTP_AUTHORIZATION' # regular location
68 authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
70 # only basic authentication supported
71 if authdata and authdata[0] == 'Basic'
72 user, pass = Base64.decode64(authdata[1]).split(':',2)