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