Merge branch 'master' into 2257-inequality-conditions
[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     @objects ||= model_class.limit(200).all
62     respond_to do |f|
63       f.json { render json: @objects }
64       f.html { render }
65       f.js { render }
66     end
67   end
68
69   def show
70     if !@object
71       return render_not_found("object not found")
72     end
73     respond_to do |f|
74       f.json { render json: @object }
75       f.html {
76         if request.method == 'GET'
77           render
78         else
79           redirect_to params[:return_to] || @object
80         end
81       }
82       f.js { render }
83     end
84   end
85
86   def render_content
87     if !@object
88       return render_not_found("object not found")
89     end
90   end
91
92   def new
93     @object = model_class.new
94   end
95
96   def update
97     updates = params[@object.class.to_s.underscore.singularize.to_sym]
98     updates.keys.each do |attr|
99       if @object.send(attr).is_a? Hash and updates[attr].is_a? String
100         updates[attr] = Oj.load updates[attr]
101       end
102     end
103     if @object.update_attributes updates
104       show
105     else
106       self.render_error status: 422
107     end
108   end
109
110   def create
111     @object ||= model_class.new params[model_class.to_s.underscore.singularize]
112     @object.save!
113
114     respond_to do |f|
115       f.json { render json: @object }
116       f.html {
117         redirect_to(params[:return_to] || @object)
118       }
119       f.js { render }
120     end
121   end
122
123   def destroy
124     if @object.destroy
125       respond_to do |f|
126         f.json { render json: @object }
127         f.html {
128           redirect_to(params[:return_to] || :back)
129         }
130         f.js { render }
131       end
132     else
133       self.render_error status: 422
134     end
135   end
136
137   def current_user
138     if Thread.current[:arvados_api_token]
139       Thread.current[:user] ||= User.current
140     else
141       logger.error "No API token in Thread"
142       return nil
143     end
144   end
145
146   def model_class
147     controller_name.classify.constantize
148   end
149
150   def breadcrumb_page_name
151     (@breadcrumb_page_name ||
152      (@object.friendly_link_name if @object.respond_to? :friendly_link_name))
153   end
154
155   def index_pane_list
156     %w(Recent)
157   end
158
159   def show_pane_list
160     %w(Attributes Metadata JSON API)
161   end
162
163   protected
164     
165   def find_object_by_uuid
166     if params[:id] and params[:id].match /\D/
167       params[:uuid] = params.delete :id
168     end
169     if params[:uuid].is_a? String
170       @object = model_class.find(params[:uuid])
171     else
172       @object = model_class.where(uuid: params[:uuid]).first
173     end
174   end
175
176   def thread_clear
177     Thread.current[:arvados_api_token] = nil
178     Thread.current[:user] = nil
179     Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
180     yield
181     Rails.cache.delete_matched(/^request_#{Thread.current.object_id}_/)
182   end
183
184   def thread_with_api_token(login_optional = false)
185     begin
186       try_redirect_to_login = true
187       if params[:api_token]
188         try_redirect_to_login = false
189         Thread.current[:arvados_api_token] = params[:api_token]
190         # Before copying the token into session[], do a simple API
191         # call to verify its authenticity.
192         if verify_api_token
193           session[:arvados_api_token] = params[:api_token]
194           if !request.format.json? and request.method == 'GET'
195             # Repeat this request with api_token in the (new) session
196             # cookie instead of the query string.  This prevents API
197             # tokens from appearing in (and being inadvisedly copied
198             # and pasted from) browser Location bars.
199             redirect_to request.fullpath.sub(%r{([&\?]api_token=)[^&\?]*}, '')
200           else
201             yield
202           end
203         else
204           @errors = ['Invalid API token']
205           self.render_error status: 401
206         end
207       elsif session[:arvados_api_token]
208         # In this case, the token must have already verified at some
209         # point, but it might have been revoked since.  We'll try
210         # using it, and catch the exception if it doesn't work.
211         try_redirect_to_login = false
212         Thread.current[:arvados_api_token] = session[:arvados_api_token]
213         begin
214           yield
215         rescue ArvadosApiClient::NotLoggedInException
216           try_redirect_to_login = true
217         end
218       else
219         logger.debug "No token received, session is #{session.inspect}"
220       end
221       if try_redirect_to_login
222         unless login_optional
223           respond_to do |f|
224             f.html {
225               if request.method == 'GET'
226                 redirect_to $arvados_api_client.arvados_login_url(return_to: request.url)
227               else
228                 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."
229                 redirect_to :back
230               end
231             }
232             f.json {
233               @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.']
234               self.render_error status: 422
235             }
236           end
237         else
238           # login is optional for this route so go on to the regular controller
239           Thread.current[:arvados_api_token] = nil
240           yield
241         end
242       end
243     ensure
244       # Remove token in case this Thread is used for anything else.
245       Thread.current[:arvados_api_token] = nil
246     end
247   end
248
249   def thread_with_mandatory_api_token
250     thread_with_api_token do
251       yield
252     end
253   end
254
255   # This runs after thread_with_mandatory_api_token in the filter chain.
256   def thread_with_optional_api_token
257     if Thread.current[:arvados_api_token]
258       # We are already inside thread_with_mandatory_api_token.
259       yield
260     else
261       # We skipped thread_with_mandatory_api_token. Use the optional version.
262       thread_with_api_token(true) do 
263         yield
264       end
265     end
266   end
267
268   def verify_api_token
269     begin
270       Link.where(uuid: 'just-verifying-my-api-token')
271       true
272     rescue ArvadosApiClient::NotLoggedInException
273       false
274     end
275   end
276
277   def ensure_current_user_is_admin
278     unless current_user and current_user.is_admin
279       @errors = ['Permission denied']
280       self.render_error status: 401
281     end
282   end
283
284   def check_user_agreements
285     if current_user && !current_user.is_active && current_user.is_invited
286       signatures = UserAgreement.signatures
287       @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
288       @required_user_agreements = UserAgreement.all.map do |ua|
289         if not @signed_ua_uuids.index ua.uuid
290           Collection.find(ua.uuid)
291         end
292       end.compact
293       if @required_user_agreements.empty?
294         # No agreements to sign. Perhaps we just need to ask?
295         current_user.activate
296         if !current_user.is_active
297           logger.warn "#{current_user.uuid.inspect}: " +
298             "No user agreements to sign, but activate failed!"
299         end
300       end
301       if !current_user.is_active
302         render 'user_agreements/index'
303       end
304     end
305     true
306   end
307
308   def select_theme
309     return Rails.configuration.arvados_theme
310   end
311
312   @@notification_tests = []
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/ssh_key_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