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