]> git.openstreetmap.org Git - rails.git/blob - app/controllers/application.rb
0c8b4f17a8d369d9dbfa802c64ec449d63276042
[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 authorize(realm='Web Password', errormessage="Could't authenticate you") 
10     username, passwd = get_auth_data 
11     # check if authorized 
12     # try to get user 
13     if @user = User.authenticate(username, passwd) 
14       # user exists and password is correct ... horray! 
15       if @user.methods.include? 'lastlogin' 
16         # note last login 
17         @session['lastlogin'] = user.lastlogin 
18         @user.last.login = Time.now 
19         @user.save() 
20         @session["User.id"] = @user.id 
21       end             
22     else 
23       # the user does not exist or the password was wrong 
24       @response.headers["Status"] = "Unauthorized" 
25       @response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\"" 
26       render_text(errormessage, 401)
27     end 
28   end 
29
30   def get_xml_doc
31     doc = XML::Document.new
32     doc.encoding = 'UTF-8' 
33     root = XML::Node.new 'osm'
34     root['version'] = API_VERSION
35     root['generator'] = 'OpenStreetMap server'
36     doc.root = root
37     return doc
38   end
39
40   private 
41   def get_auth_data 
42     user, pass = '', '' 
43     # extract authorisation credentials 
44     if request.env.has_key? 'X-HTTP_AUTHORIZATION' 
45       # try to get it where mod_rewrite might have put it 
46       authdata = @request.env['X-HTTP_AUTHORIZATION'].to_s.split 
47     elsif request.env.has_key? 'HTTP_AUTHORIZATION' 
48       # this is the regular location 
49       authdata = @request.env['HTTP_AUTHORIZATION'].to_s.split  
50     end 
51
52     # at the moment we only support basic authentication 
53     if authdata and authdata[0] == 'Basic' 
54       user, pass = Base64.decode64(authdata[1]).split(':')[0..1] 
55     end 
56     return [user, pass] 
57   end 
58
59 end