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