]> git.openstreetmap.org Git - rails.git/blob - app/controllers/application.rb
API 0.4: User rename, view trace links, tag filter summary / see all link, traces...
[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") \r
10     username, passwd = get_auth_data # parse from headers\r
11     # authenticate per-scheme
12     if username.nil?\r
13       @user = nil # no authentication provided - perhaps first connect (client should retry after 401)\r
14     elsif username == 'token' \r
15       @user = User.authenticate_token(passwd) # preferred - random token for user from db, passed in basic auth\r
16     else\r
17       @user = User.authenticate(username, passwd) # basic auth\r
18     end\r
19     \r
20     # handle authenticate pass/fail\r
21     if @user
22       # user exists and password is correct ... horray! 
23       if @user.methods.include? 'lastlogin'         # note last login 
24         @session['lastlogin'] = user.lastlogin 
25         @user.last.login = Time.now 
26         @user.save() 
27         @session["User.id"] = @user.id 
28       end             
29     else 
30       # no auth, the user does not exist or the password was wrong
31       response.headers["Status"] = "Unauthorized" 
32       response.headers["WWW-Authenticate"] = "Basic realm=\"#{realm}\"" 
33       render_text(errormessage, 401) # :unauthorized
34     end 
35   end 
36
37   def get_xml_doc
38     doc = XML::Document.new
39     doc.encoding = 'UTF-8' 
40     root = XML::Node.new 'osm'
41     root['version'] = API_VERSION
42     root['generator'] = 'OpenStreetMap server'
43     doc.root = root
44     return doc
45   end
46
47   # extract authorisation credentials from headers, returns user = nil if none\r
48   private 
49   def get_auth_data 
50     if request.env.has_key? 'X-HTTP_AUTHORIZATION'          # where mod_rewrite might have put it 
51       authdata = request.env['X-HTTP_AUTHORIZATION'].to_s.split 
52     elsif request.env.has_key? 'HTTP_AUTHORIZATION'         # regular location
53       authdata = request.env['HTTP_AUTHORIZATION'].to_s.split
54     end 
55     # only basic authentication supported
56     if authdata and authdata[0] == 'Basic' 
57       user, pass = Base64.decode64(authdata[1]).split(':')[0..1] 
58     end \r
59     return [user, pass] 
60   end 
61
62 end