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
15 redirect_to :controller => 'user', :action => 'login', :referer => request.request_uri unless @user
18 def authorize(realm='Web Password', errormessage="Couldn't authenticate you")
19 username, passwd = get_auth_data # parse from headers
20 # authenticate per-scheme
22 @user = nil # no authentication provided - perhaps first connect (client should retry after 401)
23 elsif username == 'token'
24 @user = User.authenticate(:token => passwd) # preferred - random token for user from db, passed in basic auth
26 @user = User.authenticate(:username => username, :password => passwd) # basic auth
29 # handle authenticate pass/fail
31 # no auth, the user does not exist or the password was wrong
32 response.headers["Status"] = "Unauthorized"
33 response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\""
34 render :text => errormessage, :status => :unauthorized
39 def check_availability
41 response.headers['Error'] = "Database offline for maintenance"
42 render :nothing => true, :status => :service_unavailable
47 # Report and error to the user
48 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
49 # rather than only a status code and having the web engine make up a
50 # phrase from that, we can also put the error message into the status
51 # message. For now, rails won't let us)
52 def report_error(message)
53 render :nothing => true, :status => :bad_request
54 # Todo: some sort of escaping of problem characters in the message
55 response.headers['Error'] = message
60 # extract authorisation credentials from headers, returns user = nil if none
62 if request.env.has_key? 'X-HTTP_AUTHORIZATION' # where mod_rewrite might have put it
63 authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split
64 elsif request.env.has_key? 'HTTP_AUTHORIZATION' # regular location
65 authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
67 # only basic authentication supported
68 if authdata and authdata[0] == 'Basic'
69 user, pass = Base64.decode64(authdata[1]).split(':',2)