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