Merge branch '1979-workbench-ui-TC'
[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(1000).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.singularize.to_sym]
111     @object.save!
112     redirect_to(params[:return_to] || @object)
113   end
114
115   def destroy
116     if @object.destroy
117       respond_to do |f|
118         f.html {
119           redirect_to(params[:return_to] || :back)
120         }
121         f.js { render }
122       end
123     else
124       self.render_error status: 422
125     end
126   end
127
128   def current_user
129     if Thread.current[:arvados_api_token]
130       Thread.current[:user] ||= User.current
131     else
132       logger.error "No API token in Thread"
133       return nil
134     end
135   end
136
137   def model_class
138     controller_name.classify.constantize
139   end
140
141   def breadcrumb_page_name
142     (@breadcrumb_page_name ||
143      (@object.friendly_link_name if @object.respond_to? :friendly_link_name))
144   end
145
146   def index_pane_list
147     %w(Recent)
148   end
149
150   def show_pane_list
151     %w(Attributes Metadata JSON API)
152   end
153
154   protected
155     
156   def find_object_by_uuid
157     if params[:id] and params[:id].match /\D/
158       params[:uuid] = params.delete :id
159     end
160     if params[:uuid].is_a? String
161       @object = model_class.find(params[:uuid])
162     else
163       @object = model_class.where(uuid: params[:uuid]).first
164     end
165   end
166
167   def thread_clear
168     Thread.current[:arvados_api_token] = nil
169     Thread.current[:user] = nil
170     Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
171     yield
172     Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
173   end
174
175   def thread_with_api_token(login_optional = false)
176     begin
177       try_redirect_to_login = true
178       if params[:api_token]
179         try_redirect_to_login = false
180         Thread.current[:arvados_api_token] = params[:api_token]
181         # Before copying the token into session[], do a simple API
182         # call to verify its authenticity.
183         if verify_api_token
184           session[:arvados_api_token] = params[:api_token]
185           if !request.format.json? and request.method == 'GET'
186             # Repeat this request with api_token in the (new) session
187             # cookie instead of the query string.  This prevents API
188             # tokens from appearing in (and being inadvisedly copied
189             # and pasted from) browser Location bars.
190             redirect_to request.fullpath.sub(%r{([&\?]api_token=)[^&\?]*}, '')
191           else
192             yield
193           end
194         else
195           @errors = ['Invalid API token']
196           self.render_error status: 401
197         end
198       elsif session[:arvados_api_token]
199         # In this case, the token must have already verified at some
200         # point, but it might have been revoked since.  We'll try
201         # using it, and catch the exception if it doesn't work.
202         try_redirect_to_login = false
203         Thread.current[:arvados_api_token] = session[:arvados_api_token]
204         begin
205           yield
206         rescue ArvadosApiClient::NotLoggedInException
207           try_redirect_to_login = true
208         end
209       else
210         logger.debug "No token received, session is #{session.inspect}"
211       end
212       if try_redirect_to_login
213         unless login_optional
214           respond_to do |f|
215             f.html {
216               if request.method == 'GET'
217                 redirect_to $arvados_api_client.arvados_login_url(return_to: request.url)
218               else
219                 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."
220                 redirect_to :back
221               end
222             }
223             f.json {
224               @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.']
225               self.render_error status: 422
226             }
227           end
228         else
229           # login is optional for this route so go on to the regular controller
230           Thread.current[:arvados_api_token] = nil
231           yield
232         end
233       end
234     ensure
235       # Remove token in case this Thread is used for anything else.
236       Thread.current[:arvados_api_token] = nil
237     end
238   end
239
240   def thread_with_mandatory_api_token
241     thread_with_api_token do
242       yield
243     end
244   end
245
246   # This runs after thread_with_mandatory_api_token in the filter chain.
247   def thread_with_optional_api_token
248     if Thread.current[:arvados_api_token]
249       # We are already inside thread_with_mandatory_api_token.
250       yield
251     else
252       # We skipped thread_with_mandatory_api_token. Use the optional version.
253       thread_with_api_token(true) do 
254         yield
255       end
256     end
257   end
258
259   def verify_api_token
260     begin
261       Link.where(uuid: 'just-verifying-my-api-token')
262       true
263     rescue ArvadosApiClient::NotLoggedInException
264       false
265     end
266   end
267
268   def ensure_current_user_is_admin
269     unless current_user and current_user.is_admin
270       @errors = ['Permission denied']
271       self.render_error status: 401
272     end
273   end
274
275   def check_user_agreements
276     if current_user && !current_user.is_active && current_user.is_invited
277       signatures = UserAgreement.signatures
278       @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
279       @required_user_agreements = UserAgreement.all.map do |ua|
280         if not @signed_ua_uuids.index ua.uuid
281           Collection.find(ua.uuid)
282         end
283       end.compact
284       if @required_user_agreements.empty?
285         # No agreements to sign. Perhaps we just need to ask?
286         current_user.activate
287         if !current_user.is_active
288           logger.warn "#{current_user.uuid.inspect}: " +
289             "No user agreements to sign, but activate failed!"
290         end
291       end
292       if !current_user.is_active
293         render 'user_agreements/index'
294       end
295     end
296     true
297   end
298
299   def select_theme
300     return Rails.configuration.arvados_theme
301   end
302
303   @@notification_tests = []
304
305   @@notification_tests.push lambda { |controller, current_user|
306     AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do   
307       return nil
308     end
309     return lambda { |view|
310       view.render partial: 'notifications/ssh_key_notification'
311     }
312   }
313
314   @@notification_tests.push lambda { |controller, current_user|
315     AuthorizedKey.limit(1).where(authorized_user_uuid: current_user.uuid).each do
316       return nil
317     end
318     return lambda { |view|
319       view.render partial: 'notifications/jobs_notification'
320     }
321   }
322
323   @@notification_tests.push lambda { |controller, current_user|
324     Job.limit(1).where(created_by: current_user.uuid).each do
325       return nil
326     end
327     return lambda { |view|
328       view.render partial: 'notifications/jobs_notification'
329     }
330   }
331
332   @@notification_tests.push lambda { |controller, current_user|
333     Collection.limit(1).where(created_by: current_user.uuid).each do
334       return nil
335     end
336     return lambda { |view|
337       view.render partial: 'notifications/collections_notification'
338     }
339   }
340
341   @@notification_tests.push lambda { |controller, current_user|
342     PipelineInstance.limit(1).where(created_by: current_user.uuid).each do
343       return nil
344     end
345     return lambda { |view|
346       view.render partial: 'notifications/pipelines_notification'
347     }
348   }
349
350   def check_user_notifications
351     @notification_count = 0
352     @notifications = []
353
354     if current_user
355       @showallalerts = false      
356       @@notification_tests.each do |t|
357         a = t.call(self, current_user)
358         if a
359           @notification_count += 1
360           @notifications.push a
361         end
362       end
363     end
364
365     if @notification_count == 0
366       @notification_count = ''
367     end
368   end
369 end