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