Merge branch '1976-pipeline-progress'
[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
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   protected
146     
147   def find_object_by_uuid
148     if params[:id] and params[:id].match /\D/
149       params[:uuid] = params.delete :id
150     end
151     if params[:uuid].is_a? String
152       @object = model_class.find(params[:uuid])
153     else
154       @object = model_class.where(uuid: params[:uuid]).first
155     end
156   end
157
158   def thread_clear
159     Thread.current[:arvados_api_token] = nil
160     Thread.current[:user] = nil
161     yield
162   end
163
164   def thread_with_api_token(login_optional = false)
165     begin
166       try_redirect_to_login = true
167       if params[:api_token]
168         try_redirect_to_login = false
169         Thread.current[:arvados_api_token] = params[:api_token]
170         # Before copying the token into session[], do a simple API
171         # call to verify its authenticity.
172         if verify_api_token
173           session[:arvados_api_token] = params[:api_token]
174           if !request.format.json? and request.method == 'GET'
175             # Repeat this request with api_token in the (new) session
176             # cookie instead of the query string.  This prevents API
177             # tokens from appearing in (and being inadvisedly copied
178             # and pasted from) browser Location bars.
179             redirect_to request.fullpath.sub(%r{([&\?]api_token=)[^&\?]*}, '')
180           else
181             yield
182           end
183         else
184           @errors = ['Invalid API token']
185           self.render_error status: 401
186         end
187       elsif session[:arvados_api_token]
188         # In this case, the token must have already verified at some
189         # point, but it might have been revoked since.  We'll try
190         # using it, and catch the exception if it doesn't work.
191         try_redirect_to_login = false
192         Thread.current[:arvados_api_token] = session[:arvados_api_token]
193         begin
194           yield
195         rescue ArvadosApiClient::NotLoggedInException
196           try_redirect_to_login = true
197         end
198       else
199         logger.debug "No token received, session is #{session.inspect}"
200       end
201       if try_redirect_to_login
202         unless login_optional
203           respond_to do |f|
204             f.html {
205               if request.method == 'GET'
206                 redirect_to $arvados_api_client.arvados_login_url(return_to: request.url)
207               else
208                 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."
209                 redirect_to :back
210               end
211             }
212             f.json {
213               @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.']
214               self.render_error status: 422
215             }
216           end
217         else
218           # login is optional for this route so go on to the regular controller
219           Thread.current[:arvados_api_token] = nil
220           yield
221         end
222       end
223     ensure
224       # Remove token in case this Thread is used for anything else.
225       Thread.current[:arvados_api_token] = nil
226     end
227   end
228
229   def thread_with_optional_api_token 
230     thread_with_api_token(true) do 
231       yield
232     end
233   end
234
235   def verify_api_token
236     begin
237       Link.where(uuid: 'just-verifying-my-api-token')
238       true
239     rescue ArvadosApiClient::NotLoggedInException
240       false
241     end
242   end
243
244   def ensure_current_user_is_admin
245     unless current_user and current_user.is_admin
246       @errors = ['Permission denied']
247       self.render_error status: 401
248     end
249   end
250
251   def check_user_agreements
252     if current_user && !current_user.is_active && current_user.is_invited
253       signatures = UserAgreement.signatures
254       @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
255       @required_user_agreements = UserAgreement.all.map do |ua|
256         if not @signed_ua_uuids.index ua.uuid
257           Collection.find(ua.uuid)
258         end
259       end.compact
260       if @required_user_agreements.empty?
261         # No agreements to sign. Perhaps we just need to ask?
262         current_user.activate
263         if !current_user.is_active
264           logger.warn "#{current_user.uuid.inspect}: " +
265             "No user agreements to sign, but activate failed!"
266         end
267       end
268       if !current_user.is_active
269         render 'user_agreements/index'
270       end
271     end
272     true
273   end
274
275   def select_theme
276     return Rails.configuration.arvados_theme
277   end
278 end