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