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