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