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
6 @user = User.find_by_token(session[:token])
10 redirect_to :controller => 'user', :action => 'login', :referer => request.request_uri unless @user
13 def authorize(realm='Web Password', errormessage="Couldn't authenticate you")
14 username, passwd = get_auth_data # parse from headers
15 # authenticate per-scheme
17 @user = nil # no authentication provided - perhaps first connect (client should retry after 401)
18 elsif username == 'token'
19 @user = User.authenticate_token(passwd) # preferred - random token for user from db, passed in basic auth
21 @user = User.authenticate(username, passwd) # basic auth
24 # handle authenticate pass/fail
26 # user exists and password is correct ... horray!
27 if @user.methods.include? 'lastlogin' # note last login
28 @session['lastlogin'] = user.lastlogin
29 @user.last.login = Time.now
31 @session["User.id"] = @user.id
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, 401) # :unauthorized
41 # Report and error to the user
42 # (If anyone ever fixes Rails so it can set a http status "reason phrase",
43 # rather than only a status code and having the web engine make up a
44 # phrase from that, we can also put the error message into the status
45 # message. For now, rails won't let us)
46 def report_error(message)
47 render :nothing => true, :status => :bad_request
48 # Todo: some sort of escaping of problem characters in the message
49 response.headers['Error'] = message
52 # extract authorisation credentials from headers, returns user = nil if none
55 if request.env.has_key? 'X-HTTP_AUTHORIZATION' # where mod_rewrite might have put it
56 authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split
57 elsif request.env.has_key? 'HTTP_AUTHORIZATION' # regular location
58 authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
60 # only basic authentication supported
61 if authdata and authdata[0] == 'Basic'
62 user, pass = Base64.decode64(authdata[1]).split(':',2)