Allow controller to override page name for breadcrumbs.
[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     end
63   end
64
65   def show
66     if !@object
67       return render_not_found("object not found")
68     end
69     respond_to do |f|
70       f.json { render json: @object }
71       f.html {
72         if request.method == 'GET'
73           render
74         else
75           redirect_to params[:return_to] || @object
76         end
77       }
78     end
79   end
80
81   def render_content
82     if !@object
83       return render_not_found("object not found")
84     end
85   end
86
87   def new
88     @object = model_class.new
89   end
90
91   def update
92     updates = params[@object.class.to_s.underscore.singularize.to_sym]
93     updates.keys.each do |attr|
94       if @object.send(attr).is_a? Hash and updates[attr].is_a? String
95         updates[attr] = Oj.load updates[attr]
96       end
97     end
98     if @object.update_attributes updates
99       show
100     else
101       self.render_error status: 422
102     end
103   end
104
105   def create
106     @object ||= model_class.new params[model_class.to_s.singularize.to_sym]
107     @object.save!
108     redirect_to(params[:return_to] || @object)
109   end
110
111   def destroy
112     if @object.destroy
113       redirect_to(params[:return_to] || :back)
114     else
115       self.render_error status: 422
116     end
117   end
118
119   def current_user
120     if Thread.current[:arvados_api_token]
121       Thread.current[:user] ||= User.current
122     else
123       logger.error "No API token in Thread"
124       return nil
125     end
126   end
127
128   def model_class
129     controller_name.classify.constantize
130   end
131
132   def breadcrumb_page_name
133     (@breadcrumb_page_name ||
134      (@object.friendly_link_name if @object.respond_to? :friendly_link_name))
135   end
136
137   protected
138     
139   def find_object_by_uuid
140     if params[:id] and params[:id].match /\D/
141       params[:uuid] = params.delete :id
142     end
143     if params[:uuid].is_a? String
144       @object = model_class.find(params[:uuid])
145     else
146       @object = model_class.where(uuid: params[:uuid]).first
147     end
148   end
149
150   def thread_clear
151     Thread.current[:arvados_api_token] = nil
152     Thread.current[:user] = nil
153     yield
154   end
155
156   def thread_with_api_token(login_optional = false)
157     begin
158       try_redirect_to_login = true
159       if params[:api_token]
160         try_redirect_to_login = false
161         Thread.current[:arvados_api_token] = params[:api_token]
162         # Before copying the token into session[], do a simple API
163         # call to verify its authenticity.
164         if verify_api_token
165           session[:arvados_api_token] = params[:api_token]
166           if !request.format.json? and request.method == 'GET'
167             # Repeat this request with api_token in the (new) session
168             # cookie instead of the query string.  This prevents API
169             # tokens from appearing in (and being inadvisedly copied
170             # and pasted from) browser Location bars.
171             redirect_to request.fullpath.sub(%r{([&\?]api_token=)[^&\?]*}, '')
172           else
173             yield
174           end
175         else
176           @errors = ['Invalid API token']
177           self.render_error status: 401
178         end
179       elsif session[:arvados_api_token]
180         # In this case, the token must have already verified at some
181         # point, but it might have been revoked since.  We'll try
182         # using it, and catch the exception if it doesn't work.
183         try_redirect_to_login = false
184         Thread.current[:arvados_api_token] = session[:arvados_api_token]
185         begin
186           yield
187         rescue ArvadosApiClient::NotLoggedInException
188           try_redirect_to_login = true
189         end
190       else
191         logger.debug "No token received, session is #{session.inspect}"
192       end
193       if try_redirect_to_login
194         unless login_optional
195           respond_to do |f|
196             f.html {
197               if request.method == 'GET'
198                 redirect_to $arvados_api_client.arvados_login_url(return_to: request.url)
199               else
200                 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."
201                 redirect_to :back
202               end
203             }
204             f.json {
205               @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.']
206               self.render_error status: 422
207             }
208           end
209         else
210           # login is optional for this route so go on to the regular controller
211           Thread.current[:arvados_api_token] = nil
212           yield
213         end
214       end
215     ensure
216       # Remove token in case this Thread is used for anything else.
217       Thread.current[:arvados_api_token] = nil
218     end
219   end
220
221   def thread_with_optional_api_token 
222     thread_with_api_token(true) do 
223       yield
224     end
225   end
226
227   def verify_api_token
228     begin
229       Link.where(uuid: 'just-verifying-my-api-token')
230       true
231     rescue ArvadosApiClient::NotLoggedInException
232       false
233     end
234   end
235
236   def ensure_current_user_is_admin
237     unless current_user and current_user.is_admin
238       @errors = ['Permission denied']
239       self.render_error status: 401
240     end
241   end
242
243   def check_user_agreements
244     if current_user && !current_user.is_active && current_user.is_invited
245       signatures = UserAgreement.signatures
246       @signed_ua_uuids = UserAgreement.signatures.map &:head_uuid
247       @required_user_agreements = UserAgreement.all.map do |ua|
248         if not @signed_ua_uuids.index ua.uuid
249           Collection.find(ua.uuid)
250         end
251       end.compact
252       if @required_user_agreements.empty?
253         # No agreements to sign. Perhaps we just need to ask?
254         current_user.activate
255         if !current_user.is_active
256           logger.warn "#{current_user.uuid.inspect}: " +
257             "No user agreements to sign, but activate failed!"
258         end
259       end
260       if !current_user.is_active
261         render 'user_agreements/index'
262       end
263     end
264     true
265   end
266
267   def select_theme
268     return Rails.configuration.arvados_theme
269   end
270 end