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