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