]> git.openstreetmap.org Git - rails.git/blob - app/controllers/application.rb
simplify grabbing of a xml base doc
[rails.git] / app / controllers / application.rb
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
4
5   def authorize_web
6     @user = User.find_by_token(session[:token])
7   end
8
9   def require_user
10     redirect_to :controller => 'user', :action => 'login' unless @user
11   end
12
13   def authorize(realm='Web Password', errormessage="Could't authenticate you") \r
14     username, passwd = get_auth_data # parse from headers\r
15     # authenticate per-scheme
16     if username.nil?\r
17       @user = nil # no authentication provided - perhaps first connect (client should retry after 401)\r
18     elsif username == 'token' \r
19       @user = User.authenticate_token(passwd) # preferred - random token for user from db, passed in basic auth\r
20     else\r
21       @user = User.authenticate(username, passwd) # basic auth\r
22     end\r
23     \r
24     # handle authenticate pass/fail\r
25     if @user
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 
30         @user.save() 
31         @session["User.id"] = @user.id 
32       end             
33     else 
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
38     end 
39   end 
40
41   # extract authorisation credentials from headers, returns user = nil if none\r
42   private 
43   def get_auth_data 
44     if request.env.has_key? 'X-HTTP_AUTHORIZATION'          # where mod_rewrite might have put it 
45       authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split 
46     elsif request.env.has_key? 'HTTP_AUTHORIZATION'         # regular location
47       authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
48     end 
49     # only basic authentication supported
50     if authdata and authdata[0] == 'Basic' 
51       user, pass = Base64.decode64(authdata[1]).split(':')[0..1] 
52     end \r
53     return [user, pass] 
54   end 
55
56 end