]> git.openstreetmap.org Git - rails.git/blob - app/controllers/application_controller.rb
Merge pull request #2624 from francois2metz/diary-entry
[rails.git] / app / controllers / application_controller.rb
1 class ApplicationController < ActionController::Base
2   include SessionPersistence
3
4   protect_from_forgery :with => :exception
5
6   rescue_from CanCan::AccessDenied, :with => :deny_access
7   check_authorization
8
9   before_action :fetch_body
10   around_action :better_errors_allow_inline, :if => proc { Rails.env.development? }
11
12   attr_accessor :current_user
13
14   helper_method :current_user
15
16   private
17
18   def authorize_web
19     if session[:user]
20       self.current_user = User.where(:id => session[:user]).where("status IN ('active', 'confirmed', 'suspended')").first
21
22       if current_user.status == "suspended"
23         session.delete(:user)
24         session_expires_automatically
25
26         redirect_to :controller => "users", :action => "suspended"
27
28       # don't allow access to any auth-requiring part of the site unless
29       # the new CTs have been seen (and accept/decline chosen).
30       elsif !current_user.terms_seen && flash[:skip_terms].nil?
31         flash[:notice] = t "users.terms.you need to accept or decline"
32         if params[:referer]
33           redirect_to :controller => "users", :action => "terms", :referer => params[:referer]
34         else
35           redirect_to :controller => "users", :action => "terms", :referer => request.fullpath
36         end
37       end
38     elsif session[:token]
39       session[:user] = current_user.id if self.current_user = User.authenticate(:token => session[:token])
40     end
41   rescue StandardError => e
42     logger.info("Exception authorizing user: #{e}")
43     reset_session
44     self.current_user = nil
45   end
46
47   def require_user
48     unless current_user
49       if request.get?
50         redirect_to :controller => "users", :action => "login", :referer => request.fullpath
51       else
52         head :forbidden
53       end
54     end
55   end
56
57   def require_oauth
58     @oauth = current_user.access_token(Settings.oauth_key) if current_user && Settings.key?(:oauth_key)
59   end
60
61   ##
62   # require the user to have cookies enabled in their browser
63   def require_cookies
64     if request.cookies["_osm_session"].to_s == ""
65       if params[:cookie_test].nil?
66         session[:cookie_test] = true
67         redirect_to params.to_unsafe_h.merge(:cookie_test => "true")
68         false
69       else
70         flash.now[:warning] = t "application.require_cookies.cookies_needed"
71       end
72     else
73       session.delete(:cookie_test)
74     end
75   end
76
77   def check_database_readable(need_api = false)
78     if Settings.status == "database_offline" || (need_api && Settings.status == "api_offline")
79       if request.xhr?
80         report_error "Database offline for maintenance", :service_unavailable
81       else
82         redirect_to :controller => "site", :action => "offline"
83       end
84     end
85   end
86
87   def check_database_writable(need_api = false)
88     if Settings.status == "database_offline" || Settings.status == "database_readonly" ||
89        (need_api && (Settings.status == "api_offline" || Settings.status == "api_readonly"))
90       if request.xhr?
91         report_error "Database offline for maintenance", :service_unavailable
92       else
93         redirect_to :controller => "site", :action => "offline"
94       end
95     end
96   end
97
98   def check_api_readable
99     if api_status == "offline"
100       report_error "Database offline for maintenance", :service_unavailable
101       false
102     end
103   end
104
105   def check_api_writable
106     unless api_status == "online"
107       report_error "Database offline for maintenance", :service_unavailable
108       false
109     end
110   end
111
112   def database_status
113     if Settings.status == "database_offline"
114       "offline"
115     elsif Settings.status == "database_readonly"
116       "readonly"
117     else
118       "online"
119     end
120   end
121
122   def api_status
123     status = database_status
124     if status == "online"
125       if Settings.status == "api_offline"
126         status = "offline"
127       elsif Settings.status == "api_readonly"
128         status = "readonly"
129       end
130     end
131     status
132   end
133
134   def require_public_data
135     unless current_user.data_public?
136       report_error "You must make your edits public to upload new data", :forbidden
137       false
138     end
139   end
140
141   # Report and error to the user
142   # (If anyone ever fixes Rails so it can set a http status "reason phrase",
143   #  rather than only a status code and having the web engine make up a
144   #  phrase from that, we can also put the error message into the status
145   #  message. For now, rails won't let us)
146   def report_error(message, status = :bad_request)
147     # TODO: some sort of escaping of problem characters in the message
148     response.headers["Error"] = message
149
150     if request.headers["X-Error-Format"]&.casecmp("xml")&.zero?
151       result = OSM::API.new.get_xml_doc
152       result.root.name = "osmError"
153       result.root << (XML::Node.new("status") << "#{Rack::Utils.status_code(status)} #{Rack::Utils::HTTP_STATUS_CODES[status]}")
154       result.root << (XML::Node.new("message") << message)
155
156       render :xml => result.to_s
157     else
158       render :plain => message, :status => status
159     end
160   end
161
162   def preferred_languages(reset = false)
163     @preferred_languages = nil if reset
164     @preferred_languages ||= if params[:locale]
165                                Locale.list(params[:locale])
166                              elsif current_user
167                                current_user.preferred_languages
168                              else
169                                Locale.list(http_accept_language.user_preferred_languages)
170                              end
171   end
172
173   helper_method :preferred_languages
174
175   def set_locale(reset = false)
176     if current_user&.languages&.empty? && !http_accept_language.user_preferred_languages.empty?
177       current_user.languages = http_accept_language.user_preferred_languages
178       current_user.save
179     end
180
181     I18n.locale = Locale.available.preferred(preferred_languages(reset))
182
183     response.headers["Vary"] = "Accept-Language"
184     response.headers["Content-Language"] = I18n.locale.to_s
185   end
186
187   def api_call_handle_error
188     yield
189   rescue ActionController::UnknownFormat
190     head :not_acceptable
191   rescue ActiveRecord::RecordNotFound => e
192     head :not_found
193   rescue LibXML::XML::Error, ArgumentError => e
194     report_error e.message, :bad_request
195   rescue ActiveRecord::RecordInvalid => e
196     message = "#{e.record.class} #{e.record.id}: "
197     e.record.errors.each { |attr, msg| message << "#{attr}: #{msg} (#{e.record[attr].inspect})" }
198     report_error message, :bad_request
199   rescue OSM::APIError => e
200     report_error e.message, e.status
201   rescue AbstractController::ActionNotFound => e
202     raise
203   rescue StandardError => e
204     logger.info("API threw unexpected #{e.class} exception: #{e.message}")
205     e.backtrace.each { |l| logger.info(l) }
206     report_error "#{e.class}: #{e.message}", :internal_server_error
207   end
208
209   ##
210   # asserts that the request method is the +method+ given as a parameter
211   # or raises a suitable error. +method+ should be a symbol, e.g: :put or :get.
212   def assert_method(method)
213     ok = request.send((method.to_s.downcase + "?").to_sym)
214     raise OSM::APIBadMethodError, method unless ok
215   end
216
217   ##
218   # wrap an api call in a timeout
219   def api_call_timeout
220     OSM::Timer.timeout(Settings.api_timeout, Timeout::Error) do
221       yield
222     end
223   rescue Timeout::Error
224     raise OSM::APITimeoutError
225   end
226
227   ##
228   # wrap a web page in a timeout
229   def web_timeout
230     OSM::Timer.timeout(Settings.web_timeout, Timeout::Error) do
231       yield
232     end
233   rescue ActionView::Template::Error => e
234     e = e.cause
235
236     if e.is_a?(Timeout::Error) ||
237        (e.is_a?(ActiveRecord::StatementInvalid) && e.message =~ /execution expired/)
238       render :action => "timeout"
239     else
240       raise
241     end
242   rescue Timeout::Error
243     render :action => "timeout"
244   end
245
246   ##
247   # ensure that there is a "user" instance variable
248   def lookup_user
249     render_unknown_user params[:display_name] unless @user = User.active.find_by(:display_name => params[:display_name])
250   end
251
252   ##
253   # render a "no such user" page
254   def render_unknown_user(name)
255     @title = t "users.no_such_user.title"
256     @not_found_user = name
257
258     respond_to do |format|
259       format.html { render :template => "users/no_such_user", :status => :not_found }
260       format.all { head :not_found }
261     end
262   end
263
264   ##
265   # Unfortunately if a PUT or POST request that has a body fails to
266   # read it then Apache will sometimes fail to return the response it
267   # is given to the client properly, instead erroring:
268   #
269   #   https://issues.apache.org/bugzilla/show_bug.cgi?id=44782
270   #
271   # To work round this we call rewind on the body here, which is added
272   # as a filter, to force it to be fetched from Apache into a file.
273   def fetch_body
274     request.body.rewind
275   end
276
277   def map_layout
278     append_content_security_policy_directives(
279       :child_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
280       :frame_src => %w[http://127.0.0.1:8111 https://127.0.0.1:8112],
281       :connect_src => [Settings.nominatim_url, Settings.overpass_url, Settings.fossgis_osrm_url, Settings.graphhopper_url],
282       :form_action => %w[render.openstreetmap.org],
283       :style_src => %w['unsafe-inline']
284     )
285
286     if Settings.status == "database_offline" || Settings.status == "api_offline"
287       flash.now[:warning] = t("layouts.osm_offline")
288     elsif Settings.status == "database_readonly" || Settings.status == "api_readonly"
289       flash.now[:warning] = t("layouts.osm_read_only")
290     end
291
292     request.xhr? ? "xhr" : "map"
293   end
294
295   def allow_thirdparty_images
296     append_content_security_policy_directives(:img_src => %w[*])
297   end
298
299   def preferred_editor
300     editor = if params[:editor]
301                params[:editor]
302              elsif current_user&.preferred_editor
303                current_user.preferred_editor
304              else
305                Settings.default_editor
306              end
307
308     editor
309   end
310
311   helper_method :preferred_editor
312
313   def update_totp
314     if Settings.key?(:totp_key)
315       cookies["_osm_totp_token"] = {
316         :value => ROTP::TOTP.new(Settings.totp_key, :interval => 3600).now,
317         :domain => "openstreetmap.org",
318         :expires => 1.hour.from_now
319       }
320     end
321   end
322
323   def better_errors_allow_inline
324     yield
325   rescue StandardError
326     append_content_security_policy_directives(
327       :script_src => %w['unsafe-inline'],
328       :style_src => %w['unsafe-inline']
329     )
330
331     raise
332   end
333
334   def current_ability
335     Ability.new(current_user)
336   end
337
338   def deny_access(_exception)
339     if current_token
340       set_locale
341       report_error t("oauth.permissions.missing"), :forbidden
342     elsif current_user
343       set_locale
344       respond_to do |format|
345         format.html { redirect_to :controller => "errors", :action => "forbidden" }
346         format.any { report_error t("application.permission_denied"), :forbidden }
347       end
348     elsif request.get?
349       respond_to do |format|
350         format.html { redirect_to :controller => "users", :action => "login", :referer => request.fullpath }
351         format.any { head :forbidden }
352       end
353     else
354       head :forbidden
355     end
356   end
357
358   # extract authorisation credentials from headers, returns user = nil if none
359   def get_auth_data
360     if request.env.key? "X-HTTP_AUTHORIZATION" # where mod_rewrite might have put it
361       authdata = request.env["X-HTTP_AUTHORIZATION"].to_s.split
362     elsif request.env.key? "REDIRECT_X_HTTP_AUTHORIZATION" # mod_fcgi
363       authdata = request.env["REDIRECT_X_HTTP_AUTHORIZATION"].to_s.split
364     elsif request.env.key? "HTTP_AUTHORIZATION" # regular location
365       authdata = request.env["HTTP_AUTHORIZATION"].to_s.split
366     end
367     # only basic authentication supported
368     user, pass = Base64.decode64(authdata[1]).split(":", 2) if authdata && authdata[0] == "Basic"
369     [user, pass]
370   end
371
372   # override to stop oauth plugin sending errors
373   def invalid_oauth_response; end
374 end