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