fix active/admin editables
[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 render_content
70     if !@object
71       return render_not_found("object not found")
72     end
73   end
74
75   def new
76     @object = model_class.new
77   end
78
79   def update
80     if @object.update_attributes params[@object.class.to_s.underscore.singularize.to_sym]
81       show
82     else
83       self.render_error status: 422
84     end
85   end
86
87   def create
88     @object ||= model_class.new params[model_class.to_s.singularize.to_sym]
89     @object.save!
90     redirect_to @object
91   end
92
93   def destroy
94     if @object.destroy
95       redirect_to(params[:return_to] || :back)
96     else
97       self.render_error status: 422
98     end
99   end
100
101   def current_user
102     if Thread.current[:arvados_api_token]
103       Thread.current[:user] ||= User.current
104     else
105       logger.error "No API token in Thread"
106       return nil
107     end
108   end
109
110   def model_class
111     controller_name.classify.constantize
112   end
113
114   protected
115     
116   def find_object_by_uuid
117     if params[:id] and params[:id].match /\D/
118       params[:uuid] = params.delete :id
119     end
120     @object = model_class.where(uuid: params[:uuid]).first
121   end
122
123   def thread_clear
124     Thread.current[:arvados_api_token] = nil
125     Thread.current[:user] = nil
126     yield
127   end
128
129   def thread_with_api_token
130     begin
131       try_redirect_to_login = true
132       if params[:api_token]
133         try_redirect_to_login = false
134         Thread.current[:arvados_api_token] = params[:api_token]
135         # Before copying the token into session[], do a simple API
136         # call to verify its authenticity.
137         if verify_api_token
138           session[:arvados_api_token] = params[:api_token]
139           if !request.format.json? and request.method == 'GET'
140             # Repeat this request with api_token in the (new) session
141             # cookie instead of the query string.  This prevents API
142             # tokens from appearing in (and being inadvisedly copied
143             # and pasted from) browser Location bars.
144             redirect_to request.fullpath.sub(%r{([&\?]api_token=)[^&\?]*}, '')
145           else
146             yield
147           end
148         else
149           @errors = ['Invalid API token']
150           self.render_error status: 401
151         end
152       elsif session[:arvados_api_token]
153         # In this case, the token must have already verified at some
154         # point, but it might have been revoked since.  We'll try
155         # using it, and catch the exception if it doesn't work.
156         try_redirect_to_login = false
157         Thread.current[:arvados_api_token] = session[:arvados_api_token]
158         begin
159           yield
160         rescue ArvadosApiClient::NotLoggedInException
161           try_redirect_to_login = true
162         end
163       else
164         logger.debug "No token received, session is #{session.inspect}"
165       end
166       if try_redirect_to_login
167         respond_to do |f|
168           f.html {
169             if request.method == 'GET'
170               redirect_to $arvados_api_client.arvados_login_url(return_to: request.url)
171             else
172               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."
173               redirect_to :back
174             end
175           }
176           f.json {
177             @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.']
178             self.render_error status: 422
179           }
180         end
181       end
182     ensure
183       # Remove token in case this Thread is used for anything else.
184       Thread.current[:arvados_api_token] = nil
185     end
186   end
187
188   def verify_api_token
189     begin
190       Link.where(uuid: 'just-verifying-my-api-token')
191       true
192     rescue ArvadosApiClient::NotLoggedInException
193       false
194     end
195   end
196
197   def ensure_current_user_is_admin
198     unless current_user and current_user.is_admin
199       @errors = ['Permission denied']
200       self.render_error status: 401
201     end
202   end
203 end