rename projects
[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     end
55   end
56
57   def show
58     if !@object
59       return render_not_found("object not found")
60     end
61     respond_to do |f|
62       f.json { render json: @object }
63       f.html { render }
64     end
65   end
66
67   def current_user
68     if Thread.current[:arvados_api_token]
69       @current_user ||= User.current
70     else
71       logger.error "No API token in Thread"
72       return nil
73     end
74   end
75
76   protected
77     
78   def model_class
79     controller_name.classify.constantize
80   end
81
82   def find_object_by_uuid
83     if params[:id] and params[:id].match /\D/
84       params[:uuid] = params.delete :id
85     end
86     @object = model_class.where(uuid: params[:uuid]).first
87   end
88
89   def thread_with_api_token
90     begin
91       try_redirect_to_login = true
92       if params[:api_token]
93         try_redirect_to_login = false
94         Thread.current[:arvados_api_token] = params[:api_token]
95         # Before copying the token into session[], do a simple API
96         # call to verify its authenticity.
97         if verify_api_token
98           session[:arvados_api_token] = params[:api_token]
99           if !request.format.json? and request.method == 'GET'
100             # Repeat this request with api_token in the (new) session
101             # cookie instead of the query string.  This prevents API
102             # tokens from appearing in (and being inadvisedly copied
103             # and pasted from) browser Location bars.
104             redirect_to request.fullpath.sub(%r{([&\?]api_token=)[^&\?]*}, '')
105           else
106             yield
107           end
108         else
109           @errors = ['Invalid API token']
110           self.render_error status: 401
111         end
112       elsif session[:arvados_api_token]
113         # In this case, the token must have already verified at some
114         # point, but it might have been revoked since.  We'll try
115         # using it, and catch the exception if it doesn't work.
116         try_redirect_to_login = false
117         Thread.current[:arvados_api_token] = session[:arvados_api_token]
118         begin
119           yield
120         rescue ArvadosApiClient::NotLoggedInException
121           try_redirect_to_login = true
122         end
123       end
124       if try_redirect_to_login
125         respond_to do |f|
126           f.html {
127             redirect_to $arvados_api_client.arvados_login_url(return_to: request.url)
128           }
129           f.json {
130             @errors = ['No API token supplied -- can\'t really do anything.']
131             self.render_error status: 422
132           }
133         end
134       end
135     ensure
136       # Remove token in case this Thread is used for anything else.
137       Thread.current[:arvados_api_token] = nil
138     end
139   end
140
141   def verify_api_token
142     begin
143       Link.where(uuid: 'just-verifying-my-api-token')
144       true
145     rescue ArvadosApiClient::NotLoggedInException
146       false
147     end
148   end
149
150   def ensure_current_user_is_admin
151     unless current_user and current_user.is_admin
152       @errors = ['Permission denied']
153       self.render_error status: 401
154     end
155   end
156 end