Merge remote-tracking branch 'origin' into 1692-redesign-dashboard
[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 ::AbstractController::ActionNotFound,
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 {
66         if request.method == 'GET'
67           render
68         else
69           redirect_to params[:return_to] || @object
70         end
71       }
72     end
73   end
74
75   def render_content
76     if !@object
77       return render_not_found("object not found")
78     end
79   end
80
81   def new
82     @object = model_class.new
83   end
84
85   def update
86     updates = params[@object.class.to_s.underscore.singularize.to_sym]
87     updates.keys.each do |attr|
88       if @object.send(attr).is_a? Hash and updates[attr].is_a? String
89         updates[attr] = Oj.load updates[attr]
90       end
91     end
92     if @object.update_attributes updates
93       show
94     else
95       self.render_error status: 422
96     end
97   end
98
99   def create
100     @object ||= model_class.new params[model_class.to_s.singularize.to_sym]
101     @object.save!
102     redirect_to(params[:return_to] || @object)
103   end
104
105   def destroy
106     if @object.destroy
107       redirect_to(params[:return_to] || :back)
108     else
109       self.render_error status: 422
110     end
111   end
112
113   def current_user
114     if Thread.current[:arvados_api_token]
115       Thread.current[:user] ||= User.current
116     else
117       logger.error "No API token in Thread"
118       return nil
119     end
120   end
121
122   def model_class
123     controller_name.classify.constantize
124   end
125
126   protected
127     
128   def find_object_by_uuid
129     if params[:id] and params[:id].match /\D/
130       params[:uuid] = params.delete :id
131     end
132     if params[:uuid].is_a? String
133       @object = model_class.find(params[:uuid])
134     else
135       @object = model_class.where(uuid: params[:uuid]).first
136     end
137   end
138
139   def thread_clear
140     Thread.current[:arvados_api_token] = nil
141     Thread.current[:user] = nil
142     yield
143   end
144
145   def thread_with_api_token(login_optional = false)
146     begin
147       try_redirect_to_login = true
148       if params[:api_token]
149         try_redirect_to_login = false
150         Thread.current[:arvados_api_token] = params[:api_token]
151         # Before copying the token into session[], do a simple API
152         # call to verify its authenticity.
153         if verify_api_token
154           session[:arvados_api_token] = params[:api_token]
155           if !request.format.json? and request.method == 'GET'
156             # Repeat this request with api_token in the (new) session
157             # cookie instead of the query string.  This prevents API
158             # tokens from appearing in (and being inadvisedly copied
159             # and pasted from) browser Location bars.
160             redirect_to request.fullpath.sub(%r{([&\?]api_token=)[^&\?]*}, '')
161           else
162             yield
163           end
164         else
165           @errors = ['Invalid API token']
166           self.render_error status: 401
167         end
168       elsif session[:arvados_api_token]
169         # In this case, the token must have already verified at some
170         # point, but it might have been revoked since.  We'll try
171         # using it, and catch the exception if it doesn't work.
172         try_redirect_to_login = false
173         Thread.current[:arvados_api_token] = session[:arvados_api_token]
174         begin
175           yield
176         rescue ArvadosApiClient::NotLoggedInException
177           try_redirect_to_login = true
178         end
179       else
180         logger.debug "No token received, session is #{session.inspect}"
181       end
182       if try_redirect_to_login
183         unless login_optional
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         else
199           # login is optional for this route so go on to the regular controller
200           Thread.current[:arvados_api_token] = nil
201           yield
202         end
203       end
204     ensure
205       # Remove token in case this Thread is used for anything else.
206       Thread.current[:arvados_api_token] = nil
207     end
208   end
209
210   def thread_with_optional_api_token 
211     thread_with_api_token(true) do 
212       yield
213     end
214   end
215
216   def verify_api_token
217     begin
218       Link.where(uuid: 'just-verifying-my-api-token')
219       true
220     rescue ArvadosApiClient::NotLoggedInException
221       false
222     end
223   end
224
225   def ensure_current_user_is_admin
226     unless current_user and current_user.is_admin
227       @errors = ['Permission denied']
228       self.render_error status: 401
229     end
230   end
231 end