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