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