]> git.openstreetmap.org Git - rails.git/blob - app/controllers/traces_controller.rb
Avoid CSP issues with OpenID login
[rails.git] / app / controllers / traces_controller.rb
1 class TracesController < ApplicationController
2   layout "site", :except => :georss
3
4   skip_before_action :verify_authenticity_token, :only => [:api_create, :api_read, :api_update, :api_delete, :api_data]
5   before_action :authorize_web
6   before_action :set_locale
7   before_action :authorize, :only => [:api_create, :api_read, :api_update, :api_delete, :api_data]
8   before_action :api_deny_access_handler, :only => [:api_create, :api_read, :api_update, :api_delete, :api_data]
9
10   authorize_resource
11
12   before_action :check_database_readable, :except => [:api_read, :api_data]
13   before_action :check_database_writable, :only => [:new, :create, :edit, :delete, :api_create, :api_update, :api_delete]
14   before_action :check_api_readable, :only => [:api_read, :api_data]
15   before_action :check_api_writable, :only => [:api_create, :api_update, :api_delete]
16   before_action :offline_warning, :only => [:mine, :show]
17   before_action :offline_redirect, :only => [:new, :create, :edit, :delete, :data, :api_create, :api_delete, :api_data]
18   around_action :api_call_handle_error, :only => [:api_create, :api_read, :api_update, :api_delete, :api_data]
19
20   # Counts and selects pages of GPX traces for various criteria (by user, tags, public etc.).
21   #  target_user - if set, specifies the user to fetch traces for.  if not set will fetch all traces
22   def index
23     # from display name, pick up user id if one user's traces only
24     display_name = params[:display_name]
25     if display_name.present?
26       target_user = User.active.where(:display_name => display_name).first
27       if target_user.nil?
28         render_unknown_user display_name
29         return
30       end
31     end
32
33     # set title
34     @title = if target_user.nil?
35                t ".public_traces"
36              elsif current_user && current_user == target_user
37                t ".my_traces"
38              else
39                t ".public_traces_from", :user => target_user.display_name
40              end
41
42     @title += t ".tagged_with", :tags => params[:tag] if params[:tag]
43
44     # four main cases:
45     # 1 - all traces, logged in = all public traces + all user's (i.e + all mine)
46     # 2 - all traces, not logged in = all public traces
47     # 3 - user's traces, logged in as same user = all user's traces
48     # 4 - user's traces, not logged in as that user = all user's public traces
49     @traces = if target_user.nil? # all traces
50                 if current_user
51                   Trace.visible_to(current_user) # 1
52                 else
53                   Trace.visible_to_all # 2
54                 end
55               elsif current_user && current_user == target_user
56                 current_user.traces # 3 (check vs user id, so no join + can't pick up non-public traces by changing name)
57               else
58                 target_user.traces.visible_to_all # 4
59               end
60
61     @traces = @traces.tagged(params[:tag]) if params[:tag]
62
63     @params = params.permit(:display_name, :tag)
64
65     @page = (params[:page] || 1).to_i
66     @page_size = 20
67
68     @traces = @traces.visible
69     @traces = @traces.order(:id => :desc)
70     @traces = @traces.offset((@page - 1) * @page_size)
71     @traces = @traces.limit(@page_size)
72     @traces = @traces.includes(:user, :tags)
73
74     # put together SET of tags across traces, for related links
75     tagset = {}
76     @traces.each do |trace|
77       trace.tags.reload if params[:tag] # if searched by tag, ActiveRecord won't bring back other tags, so do explicitly here
78       trace.tags.each do |tag|
79         tagset[tag.tag] = tag.tag
80       end
81     end
82
83     # final helper vars for view
84     @target_user = target_user
85     @display_name = target_user.display_name if target_user
86     @all_tags = tagset.values
87   end
88
89   def mine
90     redirect_to :action => :index, :display_name => current_user.display_name
91   end
92
93   def show
94     @trace = Trace.find(params[:id])
95
96     if @trace&.visible? &&
97        (@trace&.public? || @trace&.user == current_user)
98       @title = t ".title", :name => @trace.name
99     else
100       flash[:error] = t ".trace_not_found"
101       redirect_to :action => "index"
102     end
103   rescue ActiveRecord::RecordNotFound
104     flash[:error] = t ".trace_not_found"
105     redirect_to :action => "index"
106   end
107
108   def new
109     @title = t ".upload_trace"
110     @trace = Trace.new(:visibility => default_visibility)
111   end
112
113   def create
114     @title = t ".upload_trace"
115
116     logger.info(params[:trace][:gpx_file].class.name)
117
118     if params[:trace][:gpx_file].respond_to?(:read)
119       begin
120         @trace = do_create(params[:trace][:gpx_file], params[:trace][:tagstring],
121                            params[:trace][:description], params[:trace][:visibility])
122       rescue StandardError => ex
123         logger.debug ex
124       end
125
126       if @trace.id
127         flash[:notice] = t ".trace_uploaded"
128         flash[:warning] = t ".traces_waiting", :count => current_user.traces.where(:inserted => false).count if current_user.traces.where(:inserted => false).count > 4
129
130         TraceImporterJob.perform_later(@trace) if TRACE_USE_JOB_QUEUE
131         redirect_to :action => :index, :display_name => current_user.display_name
132       else
133         flash[:error] = t("traces.create.upload_failed") if @trace.valid?
134
135         render :action => "new"
136       end
137     else
138       @trace = Trace.new(:name => "Dummy",
139                          :tagstring => params[:trace][:tagstring],
140                          :description => params[:trace][:description],
141                          :visibility => params[:trace][:visibility],
142                          :inserted => false, :user => current_user,
143                          :timestamp => Time.now.getutc)
144       @trace.valid?
145       @trace.errors.add(:gpx_file, "can't be blank")
146
147       render :action => "new"
148     end
149   end
150
151   def data
152     trace = Trace.find(params[:id])
153
154     if trace.visible? && (trace.public? || (current_user && current_user == trace.user))
155       if Acl.no_trace_download(request.remote_ip)
156         head :forbidden
157       elsif request.format == Mime[:xml]
158         send_data(trace.xml_file.read, :filename => "#{trace.id}.xml", :type => request.format.to_s, :disposition => "attachment")
159       elsif request.format == Mime[:gpx]
160         send_data(trace.xml_file.read, :filename => "#{trace.id}.gpx", :type => request.format.to_s, :disposition => "attachment")
161       else
162         send_file(trace.trace_name, :filename => "#{trace.id}#{trace.extension_name}", :type => trace.mime_type, :disposition => "attachment")
163       end
164     else
165       head :not_found
166     end
167   rescue ActiveRecord::RecordNotFound
168     head :not_found
169   end
170
171   def edit
172     @trace = Trace.find(params[:id])
173
174     if !@trace.visible?
175       head :not_found
176     elsif current_user.nil? || @trace.user != current_user
177       head :forbidden
178     else
179       @title = t ".title", :name => @trace.name
180     end
181   rescue ActiveRecord::RecordNotFound
182     head :not_found
183   end
184
185   def update
186     @trace = Trace.find(params[:id])
187
188     if !@trace.visible?
189       head :not_found
190     elsif current_user.nil? || @trace.user != current_user
191       head :forbidden
192     elsif @trace.update(trace_params)
193       flash[:notice] = t ".updated"
194       redirect_to :action => "show", :display_name => current_user.display_name
195     else
196       @title = t ".title", :name => @trace.name
197       render :action => "edit"
198     end
199   rescue ActiveRecord::RecordNotFound
200     head :not_found
201   end
202
203   def delete
204     trace = Trace.find(params[:id])
205
206     if !trace.visible?
207       head :not_found
208     elsif current_user.nil? || (trace.user != current_user && !current_user.administrator? && !current_user.moderator?)
209       head :forbidden
210     else
211       trace.visible = false
212       trace.save
213       flash[:notice] = t ".scheduled_for_deletion"
214       TraceDestroyerJob.perform_later(trace) if TRACE_USE_JOB_QUEUE
215       redirect_to :action => :index, :display_name => trace.user.display_name
216     end
217   rescue ActiveRecord::RecordNotFound
218     head :not_found
219   end
220
221   def georss
222     @traces = Trace.visible_to_all.visible
223
224     @traces = @traces.joins(:user).where(:users => { :display_name => params[:display_name] }) if params[:display_name]
225
226     @traces = @traces.tagged(params[:tag]) if params[:tag]
227     @traces = @traces.order("timestamp DESC")
228     @traces = @traces.limit(20)
229     @traces = @traces.includes(:user)
230   end
231
232   def picture
233     trace = Trace.find(params[:id])
234
235     if trace.visible? && trace.inserted?
236       if trace.public? || (current_user && current_user == trace.user)
237         expires_in 7.days, :private => !trace.public?, :public => trace.public?
238         send_file(trace.large_picture_name, :filename => "#{trace.id}.gif", :type => "image/gif", :disposition => "inline")
239       else
240         head :forbidden
241       end
242     else
243       head :not_found
244     end
245   rescue ActiveRecord::RecordNotFound
246     head :not_found
247   end
248
249   def icon
250     trace = Trace.find(params[:id])
251
252     if trace.visible? && trace.inserted?
253       if trace.public? || (current_user && current_user == trace.user)
254         expires_in 7.days, :private => !trace.public?, :public => trace.public?
255         send_file(trace.icon_picture_name, :filename => "#{trace.id}_icon.gif", :type => "image/gif", :disposition => "inline")
256       else
257         head :forbidden
258       end
259     else
260       head :not_found
261     end
262   rescue ActiveRecord::RecordNotFound
263     head :not_found
264   end
265
266   def api_read
267     trace = Trace.visible.find(params[:id])
268
269     if trace.public? || trace.user == current_user
270       render :xml => trace.to_xml.to_s
271     else
272       head :forbidden
273     end
274   end
275
276   def api_update
277     trace = Trace.visible.find(params[:id])
278
279     if trace.user == current_user
280       trace.update_from_xml(request.raw_post)
281       trace.save!
282
283       head :ok
284     else
285       head :forbidden
286     end
287   end
288
289   def api_delete
290     trace = Trace.visible.find(params[:id])
291
292     if trace.user == current_user
293       trace.visible = false
294       trace.save!
295
296       head :ok
297     else
298       head :forbidden
299     end
300   end
301
302   def api_data
303     trace = Trace.visible.find(params[:id])
304
305     if trace.public? || trace.user == current_user
306       if request.format == Mime[:xml]
307         send_data(trace.xml_file.read, :filename => "#{trace.id}.xml", :type => request.format.to_s, :disposition => "attachment")
308       elsif request.format == Mime[:gpx]
309         send_data(trace.xml_file.read, :filename => "#{trace.id}.gpx", :type => request.format.to_s, :disposition => "attachment")
310       else
311         send_file(trace.trace_name, :filename => "#{trace.id}#{trace.extension_name}", :type => trace.mime_type, :disposition => "attachment")
312       end
313     else
314       head :forbidden
315     end
316   end
317
318   def api_create
319     tags = params[:tags] || ""
320     description = params[:description] || ""
321     visibility = params[:visibility]
322
323     if visibility.nil?
324       visibility = if params[:public]&.to_i&.nonzero?
325                      "public"
326                    else
327                      "private"
328                    end
329     end
330
331     if params[:file].respond_to?(:read)
332       trace = do_create(params[:file], tags, description, visibility)
333
334       if trace.id
335         render :plain => trace.id.to_s
336       elsif trace.valid?
337         head :internal_server_error
338       else
339         head :bad_request
340       end
341     else
342       head :bad_request
343     end
344   end
345
346   private
347
348   def do_create(file, tags, description, visibility)
349     # Sanitise the user's filename
350     name = file.original_filename.gsub(/[^a-zA-Z0-9.]/, "_")
351
352     # Get a temporary filename...
353     filename = "/tmp/#{rand}"
354
355     # ...and save the uploaded file to that location
356     File.open(filename, "wb") { |f| f.write(file.read) }
357
358     # Create the trace object, falsely marked as already
359     # inserted to stop the import daemon trying to load it
360     trace = Trace.new(
361       :name => name,
362       :tagstring => tags,
363       :description => description,
364       :visibility => visibility,
365       :inserted => true,
366       :user => current_user,
367       :timestamp => Time.now.getutc
368     )
369
370     if trace.valid?
371       Trace.transaction do
372         begin
373           # Save the trace object
374           trace.save!
375
376           # Rename the temporary file to the final name
377           FileUtils.mv(filename, trace.trace_name)
378         rescue StandardError
379           # Remove the file as we have failed to update the database
380           FileUtils.rm_f(filename)
381
382           # Pass the exception on
383           raise
384         end
385
386         begin
387           # Clear the inserted flag to make the import daemon load the trace
388           trace.inserted = false
389           trace.save!
390         rescue StandardError
391           # Remove the file as we have failed to update the database
392           FileUtils.rm_f(trace.trace_name)
393
394           # Pass the exception on
395           raise
396         end
397       end
398     end
399
400     # Finally save the user's preferred privacy level
401     if pref = current_user.preferences.where(:k => "gps.trace.visibility").first
402       pref.v = visibility
403       pref.save
404     else
405       current_user.preferences.create(:k => "gps.trace.visibility", :v => visibility)
406     end
407
408     trace
409   end
410
411   def offline_warning
412     flash.now[:warning] = t "traces.offline_warning.message" if STATUS == :gpx_offline
413   end
414
415   def offline_redirect
416     redirect_to :action => :offline if STATUS == :gpx_offline
417   end
418
419   def default_visibility
420     visibility = current_user.preferences.where(:k => "gps.trace.visibility").first
421
422     if visibility
423       visibility.v
424     elsif current_user.preferences.where(:k => "gps.trace.public", :v => "default").first.nil?
425       "private"
426     else
427       "public"
428     end
429   end
430
431   def trace_params
432     params.require(:trace).permit(:description, :tagstring, :visibility)
433   end
434 end