Advertise filters param in discovery doc.
[arvados.git] / apps / workbench / app / controllers / application_controller.rb
1 class ApplicationController < ActionController::Base
2   respond_to :html, :json, :js
3   protect_from_forgery
4   around_filter :thread_clear
5   around_filter :thread_with_mandatory_api_token, :except => [:render_exception, :render_not_found]
6   around_filter :thread_with_optional_api_token
7   before_filter :find_object_by_uuid, :except => [:index, :render_exception, :render_not_found]
8   before_filter :check_user_agreements, :except => [:render_exception, :render_not_found]
9   before_filter :check_user_notifications, :except => [:render_exception, :render_not_found]
10   theme :select_theme
11
12   begin
13     rescue_from Exception,
14     :with => :render_exception
15     rescue_from ActiveRecord::RecordNotFound,
16     :with => :render_not_found
17     rescue_from ActionController::RoutingError,
18     :with => :render_not_found
19     rescue_from ActionController::UnknownController,
20     :with => :render_not_found
21     rescue_from ::AbstractController::ActionNotFound,
22     :with => :render_not_found
23   end
24
25   def unprocessable(message=nil)
26     @errors ||= []
27     @errors << message if message
28     render_error status: 422
29   end
30
31   def render_error(opts)
32     respond_to do |f|
33       # json must come before html here, so it gets used as the
34       # default format when js is requested by the client. This lets
35       # ajax:error callback parse the response correctly, even though
36       # the browser can't.
37       f.json { render opts.merge(json: {success: false, errors: @errors}) }
38       f.html { render opts.merge(controller: 'application', action: 'error') }
39     end
40   end
41
42   def render_exception(e)
43     logger.error e.inspect
44     logger.error e.backtrace.collect { |x| x + "\n" }.join('') if e.backtrace
45     if @object.andand.errors.andand.full_messages.andand.any?
46       @errors = @object.errors.full_messages
47     else
48       @errors = [e.to_s]
49     end
50     self.render_error status: 422
51   end
52
53   def render_not_found(e=ActionController::RoutingError.new("Path not found"))
54     logger.error e.inspect
55     @errors = ["Path not found"]
56     self.render_error status: 404
57   end
58
59   def index
60     @objects ||= model_class.limit(200).all
61     respond_to do |f|
62       f.json { render json: @objects }
63       f.html { render }
64       f.js { render }
65     end
66   end
67
68   def show
69     if !@object
70       return render_not_found("object not found")
71     end
72     respond_to do |f|
73       f.json { render json: @object }
74       f.html {
75         if request.method == 'GET'
76           render
77         else
78           redirect_to params[:return_to] || @object
79         end
80       }
81       f.js { render }
82     end
83   end
84
85   def render_content
86     if !@object
87       return render_not_found("object not found")
88     end
89   end
90
91   def new
92     @object = model_class.new
93   end
94
95   def update
96     updates = params[@object.class.to_s.underscore.singularize.to_sym]
97     updates.keys.each do |attr|
98       if @object.send(attr).is_a? Hash and updates[attr].is_a? String
99         updates[attr] = Oj.load updates[attr]
100       end
101     end
102     if @object.update_attributes updates
103       show
104     else
105       self.render_error status: 422
106     end
107   end
108
109   def create
110     @object ||= model_class.new params[model_class.to_s.underscore.singularize]
111     @object.save!
112     respond_to do |f|
113       f.json { render json: @object }
114       f.html {
115         redirect_to(params[:return_to] || @object)
116       }
117       f.js { render }
118     end
119   end
120
121   def destroy
122     if @object.destroy
123       respond_to do |f|
124         f.json { render json: @object }
125         f.html {
126           redirect_to(params[:return_to] || :back)
127         }
128         f.js { render }
129       end
130     else
131       self.render_error status: 422
132     end
133   end
134
135   def current_user
136     if Thread.current[:arvados_api_token]
137       Thread.current[:user] ||= User.current
138     else
139       logger.error "No API token in Thread"
140       return nil
141     end
142   end
143
144   def model_class
145     controller_name.classify.constantize
146   end
147
148   def breadcrumb_page_name
149     (@breadcrumb_page_name ||
150      (@object.friendly_link_name if @object.respond_to? :friendly_link_name))
151   end
152
153   def index_pane_list
154     %w(Recent)
155   end
156
157   def show_pane_list
158     %w(Attributes Metadata JSON API)
159   end
160
161   protected
162     
163   def find_object_by_uuid
164     if params[:id] and params[:id].match /\D/
165       params[:uuid] = params.delete :id
166     end
167     if params[:uuid].is_a? String
168       @object = model_class.find(params[:uuid])
169     else
170       @object = model_class.where(uuid: params[:uuid]).first
171     end
172   end
173
174   def thread_clear
175     Thread.current[:arvados_api_token] = nil
176     Thread.current[:user] = nil
177     Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
178     yield
179     Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
180   end
181
182   def thread_with_api_token(login_optional = false)
183     begin
184       try_redirect_to_login = true
185       if params[:api_token]
186         try_redirect_to_login = false
187         Thread.current[:arvados_api_token] = params[:api_token]
188         # Before copying the token into session[], do a simple API
189         # call to verify its authenticity.
190         if verify_api_token
191           session[:arvados_api_token] = params[:api_token]
192           if !request.format.json? and request.method == 'GET'
193             # Repeat this request with api_token in the (new) session
194             # cookie instead of the query string.  This prevents API
195             # tokens from appearing in (and being inadvisedly copied
196             # and pasted from) browser Location bars.
197             redirect_to request.fullpath.sub(%r{([&\?]api_token=)[^&\?]*}, '')
198           else
199             yield
200           end
201         else
202           @errors = ['Invalid API token']
203           self.render_error status: 401
204         end
205       elsif session[:arvados_api_token]
206         # In this case, the token must have already verified at some
207         # point, but it might have been revoked since.  We'll try
208         # using it, and catch the exception if it doesn't work.
209         try_redirect_to_login = false
210         Thread.current[:arvados_api_token] = session[:arvados_api_token]
211         begin
212           yield
213         rescue ArvadosApiClient::NotLoggedInException
214           try_redirect_to_login = true
215         end
216       else
217         logger.debug "No token received, session is #{session.inspect}"
218       end
219       if try_redirect_to_login
220         unless login_optional
221           respond_to do |f|
222             f.html {
223               if request.method == 'GET'
224                 redirect_to $arvados_api_client.arvados_login_url(return_to: request.url)
225               else
226                 flash[:error] = "Either you are not logged in, or your session has timed out. I can't automatically log you in and re-attempt this request."
227                 redirect_to :back
228               end
229             }
230             f.json {
231               @errors = ['You do not seem to be logged in. You did not supply an API token with this request, and your session (if any) has timed out.']
232               self.render_error status: 422
233             }
234           end
235         else
236           # login is optional for this route so go on to the regular controller
237           Thread.current[:arvados_api_token] = nil
238           yield
239         end
240       end
241     ensure
242       # Remove token in case this Thread is used for anything else.
243       Thread.current[:arvados_api_token] = nil
244     end
245   end
246
247   def thread_with_mandatory_api_token
248     thread_with_api_token do
249       yield
250     end
251   end
252
253   # This runs after thread_with_mandatory_api_token in the filter chain.
254   def thread_with_optional_api_token
255     if Thread.current[:arvados_api_token]
256       # We are already inside thread_with_mandatory_api_token.
257       yield
258     else
259       # We skipped thread_with_mandatory_api_token. Use the optional version.
260       thread_with_api_token(true) do 
261         yield
262       end
263     end
264   end
265
266   def verify_api_token
267     begin
268       Link.where(uuid: 'just-verifying-my-api-token')
269       true
270     rescue ArvadosApiClient::NotLoggedInException
271       false
272     end
273   end
274
275   def ensure_current_user_is_admin
276     unless current_user and current_user.is_admin
277       @errors = ['Permission denied']
278       self.render_error status: 401
279     end
280   end
281
282   def check_user_agreements
283     if current_user && !current_user.is_active && current_user.is_invited
284       signatures = UserAgreement.signatures
285       @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
286       @required_user_agreements = UserAgreement.all.map do |ua|
287         if not @signed_ua_uuids.index ua.uuid
288           Collection.find(ua.uuid)
289         end
290       end.compact
291       if @required_user_agreements.empty?
292         # No agreements to sign. Perhaps we just need to ask?
293         current_user.activate
294         if !current_user.is_active
295           logger.warn "#{current_user.uuid.inspect}: " +
296             "No user agreements to sign, but activate failed!"
297         end
298       end
299       if !current_user.is_active
300         render 'user_agreements/index'
301       end
302     end
303     true
304   end
305
306   def select_theme
307     return Rails.configuration.arvados_theme
308   end
309
310   @@notification_tests = []
311
312   @@notification_tests.push lambda { |controller, current_user|
313     AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do   
314       return nil
315     end
316     return lambda { |view|
317       view.render partial: 'notifications/ssh_key_notification'
318     }
319   }
320
321   @@notification_tests.push lambda { |controller, current_user|
322     Job.limit(1).where(created_by: current_user.uuid).each do
323       return nil
324     end
325     return lambda { |view|
326       view.render partial: 'notifications/jobs_notification'
327     }
328   }
329
330   @@notification_tests.push lambda { |controller, current_user|
331     Collection.limit(1).where(created_by: current_user.uuid).each do
332       return nil
333     end
334     return lambda { |view|
335       view.render partial: 'notifications/collections_notification'
336     }
337   }
338
339   @@notification_tests.push lambda { |controller, current_user|
340     PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
341       return nil
342     end
343     return lambda { |view|
344       view.render partial: 'notifications/pipelines_notification'
345     }
346   }
347
348   def check_user_notifications
349     @notification_count = 0
350     @notifications = []
351
352     if current_user
353       @showallalerts = false      
354       @@notification_tests.each do |t|
355         a = t.call(self, current_user)
356         if a
357           @notification_count += 1
358           @notifications.push a
359         end
360       end
361     end
362
363     if @notification_count == 0
364       @notification_count = ''
365     end
366   end
367 end