##// END OF EJS Templates
Adds an optional X-Redmine-Switch-User header to let admin users swicth user in API calls (#11755)....
Jean-Philippe Lang -
r10397:5344a35f723b
parent child
Show More
@@ -1,560 +1,575
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2012 Jean-Philippe Lang
2 # Copyright (C) 2006-2012 Jean-Philippe Lang
3 #
3 #
4 # This program is free software; you can redistribute it and/or
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
7 # of the License, or (at your option) any later version.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU General Public License
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
17
18 require 'uri'
18 require 'uri'
19 require 'cgi'
19 require 'cgi'
20
20
21 class Unauthorized < Exception; end
21 class Unauthorized < Exception; end
22
22
23 class ApplicationController < ActionController::Base
23 class ApplicationController < ActionController::Base
24 include Redmine::I18n
24 include Redmine::I18n
25
25
26 class_attribute :accept_api_auth_actions
26 class_attribute :accept_api_auth_actions
27 class_attribute :accept_rss_auth_actions
27 class_attribute :accept_rss_auth_actions
28 class_attribute :model_object
28 class_attribute :model_object
29
29
30 layout 'base'
30 layout 'base'
31
31
32 protect_from_forgery
32 protect_from_forgery
33 def handle_unverified_request
33 def handle_unverified_request
34 super
34 super
35 cookies.delete(:autologin)
35 cookies.delete(:autologin)
36 end
36 end
37
37
38 before_filter :session_expiration, :user_setup, :check_if_login_required, :set_localization
38 before_filter :session_expiration, :user_setup, :check_if_login_required, :set_localization
39
39
40 rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token
40 rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token
41 rescue_from ::Unauthorized, :with => :deny_access
41 rescue_from ::Unauthorized, :with => :deny_access
42 rescue_from ::ActionView::MissingTemplate, :with => :missing_template
42 rescue_from ::ActionView::MissingTemplate, :with => :missing_template
43
43
44 include Redmine::Search::Controller
44 include Redmine::Search::Controller
45 include Redmine::MenuManager::MenuController
45 include Redmine::MenuManager::MenuController
46 helper Redmine::MenuManager::MenuHelper
46 helper Redmine::MenuManager::MenuHelper
47
47
48 def session_expiration
48 def session_expiration
49 if session[:user_id]
49 if session[:user_id]
50 if session_expired? && !try_to_autologin
50 if session_expired? && !try_to_autologin
51 reset_session
51 reset_session
52 flash[:error] = l(:error_session_expired)
52 flash[:error] = l(:error_session_expired)
53 redirect_to signin_url
53 redirect_to signin_url
54 else
54 else
55 session[:atime] = Time.now.utc.to_i
55 session[:atime] = Time.now.utc.to_i
56 end
56 end
57 end
57 end
58 end
58 end
59
59
60 def session_expired?
60 def session_expired?
61 if Setting.session_lifetime?
61 if Setting.session_lifetime?
62 unless session[:ctime] && (Time.now.utc.to_i - session[:ctime].to_i <= Setting.session_lifetime.to_i * 60)
62 unless session[:ctime] && (Time.now.utc.to_i - session[:ctime].to_i <= Setting.session_lifetime.to_i * 60)
63 return true
63 return true
64 end
64 end
65 end
65 end
66 if Setting.session_timeout?
66 if Setting.session_timeout?
67 unless session[:atime] && (Time.now.utc.to_i - session[:atime].to_i <= Setting.session_timeout.to_i * 60)
67 unless session[:atime] && (Time.now.utc.to_i - session[:atime].to_i <= Setting.session_timeout.to_i * 60)
68 return true
68 return true
69 end
69 end
70 end
70 end
71 false
71 false
72 end
72 end
73
73
74 def start_user_session(user)
74 def start_user_session(user)
75 session[:user_id] = user.id
75 session[:user_id] = user.id
76 session[:ctime] = Time.now.utc.to_i
76 session[:ctime] = Time.now.utc.to_i
77 session[:atime] = Time.now.utc.to_i
77 session[:atime] = Time.now.utc.to_i
78 end
78 end
79
79
80 def user_setup
80 def user_setup
81 # Check the settings cache for each request
81 # Check the settings cache for each request
82 Setting.check_cache
82 Setting.check_cache
83 # Find the current user
83 # Find the current user
84 User.current = find_current_user
84 User.current = find_current_user
85 logger.info(" Current user: " + (User.current.logged? ? "#{User.current.login} (id=#{User.current.id})" : "anonymous")) if logger
85 logger.info(" Current user: " + (User.current.logged? ? "#{User.current.login} (id=#{User.current.id})" : "anonymous")) if logger
86 end
86 end
87
87
88 # Returns the current user or nil if no user is logged in
88 # Returns the current user or nil if no user is logged in
89 # and starts a session if needed
89 # and starts a session if needed
90 def find_current_user
90 def find_current_user
91 user = nil
91 user = nil
92 unless api_request?
92 unless api_request?
93 if session[:user_id]
93 if session[:user_id]
94 # existing session
94 # existing session
95 user = (User.active.find(session[:user_id]) rescue nil)
95 user = (User.active.find(session[:user_id]) rescue nil)
96 elsif autologin_user = try_to_autologin
96 elsif autologin_user = try_to_autologin
97 user = autologin_user
97 user = autologin_user
98 elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
98 elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
99 # RSS key authentication does not start a session
99 # RSS key authentication does not start a session
100 user = User.find_by_rss_key(params[:key])
100 user = User.find_by_rss_key(params[:key])
101 end
101 end
102 end
102 end
103 if user.nil? && Setting.rest_api_enabled? && accept_api_auth?
103 if user.nil? && Setting.rest_api_enabled? && accept_api_auth?
104 if (key = api_key_from_request)
104 if (key = api_key_from_request)
105 # Use API key
105 # Use API key
106 user = User.find_by_api_key(key)
106 user = User.find_by_api_key(key)
107 else
107 else
108 # HTTP Basic, either username/password or API key/random
108 # HTTP Basic, either username/password or API key/random
109 authenticate_with_http_basic do |username, password|
109 authenticate_with_http_basic do |username, password|
110 user = User.try_to_login(username, password) || User.find_by_api_key(username)
110 user = User.try_to_login(username, password) || User.find_by_api_key(username)
111 end
111 end
112 end
112 end
113 # Switch user if requested by an admin user
114 if user && user.admin? && (username = api_switch_user_from_request)
115 su = User.find_by_login(username)
116 if su && su.active?
117 logger.info(" User switched by: #{user.login} (id=#{user.id})") if logger
118 user = su
119 else
120 render_error :message => 'Invalid X-Redmine-Switch-User header', :status => 412
121 end
122 end
113 end
123 end
114 user
124 user
115 end
125 end
116
126
117 def try_to_autologin
127 def try_to_autologin
118 if cookies[:autologin] && Setting.autologin?
128 if cookies[:autologin] && Setting.autologin?
119 # auto-login feature starts a new session
129 # auto-login feature starts a new session
120 user = User.try_to_autologin(cookies[:autologin])
130 user = User.try_to_autologin(cookies[:autologin])
121 if user
131 if user
122 reset_session
132 reset_session
123 start_user_session(user)
133 start_user_session(user)
124 end
134 end
125 user
135 user
126 end
136 end
127 end
137 end
128
138
129 # Sets the logged in user
139 # Sets the logged in user
130 def logged_user=(user)
140 def logged_user=(user)
131 reset_session
141 reset_session
132 if user && user.is_a?(User)
142 if user && user.is_a?(User)
133 User.current = user
143 User.current = user
134 start_user_session(user)
144 start_user_session(user)
135 else
145 else
136 User.current = User.anonymous
146 User.current = User.anonymous
137 end
147 end
138 end
148 end
139
149
140 # Logs out current user
150 # Logs out current user
141 def logout_user
151 def logout_user
142 if User.current.logged?
152 if User.current.logged?
143 cookies.delete :autologin
153 cookies.delete :autologin
144 Token.delete_all(["user_id = ? AND action = ?", User.current.id, 'autologin'])
154 Token.delete_all(["user_id = ? AND action = ?", User.current.id, 'autologin'])
145 self.logged_user = nil
155 self.logged_user = nil
146 end
156 end
147 end
157 end
148
158
149 # check if login is globally required to access the application
159 # check if login is globally required to access the application
150 def check_if_login_required
160 def check_if_login_required
151 # no check needed if user is already logged in
161 # no check needed if user is already logged in
152 return true if User.current.logged?
162 return true if User.current.logged?
153 require_login if Setting.login_required?
163 require_login if Setting.login_required?
154 end
164 end
155
165
156 def set_localization
166 def set_localization
157 lang = nil
167 lang = nil
158 if User.current.logged?
168 if User.current.logged?
159 lang = find_language(User.current.language)
169 lang = find_language(User.current.language)
160 end
170 end
161 if lang.nil? && request.env['HTTP_ACCEPT_LANGUAGE']
171 if lang.nil? && request.env['HTTP_ACCEPT_LANGUAGE']
162 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
172 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
163 if !accept_lang.blank?
173 if !accept_lang.blank?
164 accept_lang = accept_lang.downcase
174 accept_lang = accept_lang.downcase
165 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
175 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
166 end
176 end
167 end
177 end
168 lang ||= Setting.default_language
178 lang ||= Setting.default_language
169 set_language_if_valid(lang)
179 set_language_if_valid(lang)
170 end
180 end
171
181
172 def require_login
182 def require_login
173 if !User.current.logged?
183 if !User.current.logged?
174 # Extract only the basic url parameters on non-GET requests
184 # Extract only the basic url parameters on non-GET requests
175 if request.get?
185 if request.get?
176 url = url_for(params)
186 url = url_for(params)
177 else
187 else
178 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
188 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
179 end
189 end
180 respond_to do |format|
190 respond_to do |format|
181 format.html { redirect_to :controller => "account", :action => "login", :back_url => url }
191 format.html { redirect_to :controller => "account", :action => "login", :back_url => url }
182 format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
192 format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
183 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
193 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
184 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
194 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
185 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
195 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
186 end
196 end
187 return false
197 return false
188 end
198 end
189 true
199 true
190 end
200 end
191
201
192 def require_admin
202 def require_admin
193 return unless require_login
203 return unless require_login
194 if !User.current.admin?
204 if !User.current.admin?
195 render_403
205 render_403
196 return false
206 return false
197 end
207 end
198 true
208 true
199 end
209 end
200
210
201 def deny_access
211 def deny_access
202 User.current.logged? ? render_403 : require_login
212 User.current.logged? ? render_403 : require_login
203 end
213 end
204
214
205 # Authorize the user for the requested action
215 # Authorize the user for the requested action
206 def authorize(ctrl = params[:controller], action = params[:action], global = false)
216 def authorize(ctrl = params[:controller], action = params[:action], global = false)
207 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
217 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
208 if allowed
218 if allowed
209 true
219 true
210 else
220 else
211 if @project && @project.archived?
221 if @project && @project.archived?
212 render_403 :message => :notice_not_authorized_archived_project
222 render_403 :message => :notice_not_authorized_archived_project
213 else
223 else
214 deny_access
224 deny_access
215 end
225 end
216 end
226 end
217 end
227 end
218
228
219 # Authorize the user for the requested action outside a project
229 # Authorize the user for the requested action outside a project
220 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
230 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
221 authorize(ctrl, action, global)
231 authorize(ctrl, action, global)
222 end
232 end
223
233
224 # Find project of id params[:id]
234 # Find project of id params[:id]
225 def find_project
235 def find_project
226 @project = Project.find(params[:id])
236 @project = Project.find(params[:id])
227 rescue ActiveRecord::RecordNotFound
237 rescue ActiveRecord::RecordNotFound
228 render_404
238 render_404
229 end
239 end
230
240
231 # Find project of id params[:project_id]
241 # Find project of id params[:project_id]
232 def find_project_by_project_id
242 def find_project_by_project_id
233 @project = Project.find(params[:project_id])
243 @project = Project.find(params[:project_id])
234 rescue ActiveRecord::RecordNotFound
244 rescue ActiveRecord::RecordNotFound
235 render_404
245 render_404
236 end
246 end
237
247
238 # Find a project based on params[:project_id]
248 # Find a project based on params[:project_id]
239 # TODO: some subclasses override this, see about merging their logic
249 # TODO: some subclasses override this, see about merging their logic
240 def find_optional_project
250 def find_optional_project
241 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
251 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
242 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
252 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
243 allowed ? true : deny_access
253 allowed ? true : deny_access
244 rescue ActiveRecord::RecordNotFound
254 rescue ActiveRecord::RecordNotFound
245 render_404
255 render_404
246 end
256 end
247
257
248 # Finds and sets @project based on @object.project
258 # Finds and sets @project based on @object.project
249 def find_project_from_association
259 def find_project_from_association
250 render_404 unless @object.present?
260 render_404 unless @object.present?
251
261
252 @project = @object.project
262 @project = @object.project
253 end
263 end
254
264
255 def find_model_object
265 def find_model_object
256 model = self.class.model_object
266 model = self.class.model_object
257 if model
267 if model
258 @object = model.find(params[:id])
268 @object = model.find(params[:id])
259 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
269 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
260 end
270 end
261 rescue ActiveRecord::RecordNotFound
271 rescue ActiveRecord::RecordNotFound
262 render_404
272 render_404
263 end
273 end
264
274
265 def self.model_object(model)
275 def self.model_object(model)
266 self.model_object = model
276 self.model_object = model
267 end
277 end
268
278
269 # Filter for bulk issue operations
279 # Filter for bulk issue operations
270 def find_issues
280 def find_issues
271 @issues = Issue.find_all_by_id(params[:id] || params[:ids])
281 @issues = Issue.find_all_by_id(params[:id] || params[:ids])
272 raise ActiveRecord::RecordNotFound if @issues.empty?
282 raise ActiveRecord::RecordNotFound if @issues.empty?
273 if @issues.detect {|issue| !issue.visible?}
283 if @issues.detect {|issue| !issue.visible?}
274 deny_access
284 deny_access
275 return
285 return
276 end
286 end
277 @projects = @issues.collect(&:project).compact.uniq
287 @projects = @issues.collect(&:project).compact.uniq
278 @project = @projects.first if @projects.size == 1
288 @project = @projects.first if @projects.size == 1
279 rescue ActiveRecord::RecordNotFound
289 rescue ActiveRecord::RecordNotFound
280 render_404
290 render_404
281 end
291 end
282
292
283 # make sure that the user is a member of the project (or admin) if project is private
293 # make sure that the user is a member of the project (or admin) if project is private
284 # used as a before_filter for actions that do not require any particular permission on the project
294 # used as a before_filter for actions that do not require any particular permission on the project
285 def check_project_privacy
295 def check_project_privacy
286 if @project && !@project.archived?
296 if @project && !@project.archived?
287 if @project.visible?
297 if @project.visible?
288 true
298 true
289 else
299 else
290 deny_access
300 deny_access
291 end
301 end
292 else
302 else
293 @project = nil
303 @project = nil
294 render_404
304 render_404
295 false
305 false
296 end
306 end
297 end
307 end
298
308
299 def back_url
309 def back_url
300 url = params[:back_url]
310 url = params[:back_url]
301 if url.nil? && referer = request.env['HTTP_REFERER']
311 if url.nil? && referer = request.env['HTTP_REFERER']
302 url = CGI.unescape(referer.to_s)
312 url = CGI.unescape(referer.to_s)
303 end
313 end
304 url
314 url
305 end
315 end
306
316
307 def redirect_back_or_default(default)
317 def redirect_back_or_default(default)
308 back_url = params[:back_url].to_s
318 back_url = params[:back_url].to_s
309 if back_url.present?
319 if back_url.present?
310 begin
320 begin
311 uri = URI.parse(back_url)
321 uri = URI.parse(back_url)
312 # do not redirect user to another host or to the login or register page
322 # do not redirect user to another host or to the login or register page
313 if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})
323 if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})
314 redirect_to(back_url)
324 redirect_to(back_url)
315 return
325 return
316 end
326 end
317 rescue URI::InvalidURIError
327 rescue URI::InvalidURIError
318 logger.warn("Could not redirect to invalid URL #{back_url}")
328 logger.warn("Could not redirect to invalid URL #{back_url}")
319 # redirect to default
329 # redirect to default
320 end
330 end
321 end
331 end
322 redirect_to default
332 redirect_to default
323 false
333 false
324 end
334 end
325
335
326 # Redirects to the request referer if present, redirects to args or call block otherwise.
336 # Redirects to the request referer if present, redirects to args or call block otherwise.
327 def redirect_to_referer_or(*args, &block)
337 def redirect_to_referer_or(*args, &block)
328 redirect_to :back
338 redirect_to :back
329 rescue ::ActionController::RedirectBackError
339 rescue ::ActionController::RedirectBackError
330 if args.any?
340 if args.any?
331 redirect_to *args
341 redirect_to *args
332 elsif block_given?
342 elsif block_given?
333 block.call
343 block.call
334 else
344 else
335 raise "#redirect_to_referer_or takes arguments or a block"
345 raise "#redirect_to_referer_or takes arguments or a block"
336 end
346 end
337 end
347 end
338
348
339 def render_403(options={})
349 def render_403(options={})
340 @project = nil
350 @project = nil
341 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
351 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
342 return false
352 return false
343 end
353 end
344
354
345 def render_404(options={})
355 def render_404(options={})
346 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
356 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
347 return false
357 return false
348 end
358 end
349
359
350 # Renders an error response
360 # Renders an error response
351 def render_error(arg)
361 def render_error(arg)
352 arg = {:message => arg} unless arg.is_a?(Hash)
362 arg = {:message => arg} unless arg.is_a?(Hash)
353
363
354 @message = arg[:message]
364 @message = arg[:message]
355 @message = l(@message) if @message.is_a?(Symbol)
365 @message = l(@message) if @message.is_a?(Symbol)
356 @status = arg[:status] || 500
366 @status = arg[:status] || 500
357
367
358 respond_to do |format|
368 respond_to do |format|
359 format.html {
369 format.html {
360 render :template => 'common/error', :layout => use_layout, :status => @status
370 render :template => 'common/error', :layout => use_layout, :status => @status
361 }
371 }
362 format.any { head @status }
372 format.any { head @status }
363 end
373 end
364 end
374 end
365
375
366 # Handler for ActionView::MissingTemplate exception
376 # Handler for ActionView::MissingTemplate exception
367 def missing_template
377 def missing_template
368 logger.warn "Missing template, responding with 404"
378 logger.warn "Missing template, responding with 404"
369 @project = nil
379 @project = nil
370 render_404
380 render_404
371 end
381 end
372
382
373 # Filter for actions that provide an API response
383 # Filter for actions that provide an API response
374 # but have no HTML representation for non admin users
384 # but have no HTML representation for non admin users
375 def require_admin_or_api_request
385 def require_admin_or_api_request
376 return true if api_request?
386 return true if api_request?
377 if User.current.admin?
387 if User.current.admin?
378 true
388 true
379 elsif User.current.logged?
389 elsif User.current.logged?
380 render_error(:status => 406)
390 render_error(:status => 406)
381 else
391 else
382 deny_access
392 deny_access
383 end
393 end
384 end
394 end
385
395
386 # Picks which layout to use based on the request
396 # Picks which layout to use based on the request
387 #
397 #
388 # @return [boolean, string] name of the layout to use or false for no layout
398 # @return [boolean, string] name of the layout to use or false for no layout
389 def use_layout
399 def use_layout
390 request.xhr? ? false : 'base'
400 request.xhr? ? false : 'base'
391 end
401 end
392
402
393 def invalid_authenticity_token
403 def invalid_authenticity_token
394 if api_request?
404 if api_request?
395 logger.error "Form authenticity token is missing or is invalid. API calls must include a proper Content-type header (text/xml or text/json)."
405 logger.error "Form authenticity token is missing or is invalid. API calls must include a proper Content-type header (text/xml or text/json)."
396 end
406 end
397 render_error "Invalid form authenticity token."
407 render_error "Invalid form authenticity token."
398 end
408 end
399
409
400 def render_feed(items, options={})
410 def render_feed(items, options={})
401 @items = items || []
411 @items = items || []
402 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
412 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
403 @items = @items.slice(0, Setting.feeds_limit.to_i)
413 @items = @items.slice(0, Setting.feeds_limit.to_i)
404 @title = options[:title] || Setting.app_title
414 @title = options[:title] || Setting.app_title
405 render :template => "common/feed", :formats => [:atom], :layout => false,
415 render :template => "common/feed", :formats => [:atom], :layout => false,
406 :content_type => 'application/atom+xml'
416 :content_type => 'application/atom+xml'
407 end
417 end
408
418
409 def self.accept_rss_auth(*actions)
419 def self.accept_rss_auth(*actions)
410 if actions.any?
420 if actions.any?
411 self.accept_rss_auth_actions = actions
421 self.accept_rss_auth_actions = actions
412 else
422 else
413 self.accept_rss_auth_actions || []
423 self.accept_rss_auth_actions || []
414 end
424 end
415 end
425 end
416
426
417 def accept_rss_auth?(action=action_name)
427 def accept_rss_auth?(action=action_name)
418 self.class.accept_rss_auth.include?(action.to_sym)
428 self.class.accept_rss_auth.include?(action.to_sym)
419 end
429 end
420
430
421 def self.accept_api_auth(*actions)
431 def self.accept_api_auth(*actions)
422 if actions.any?
432 if actions.any?
423 self.accept_api_auth_actions = actions
433 self.accept_api_auth_actions = actions
424 else
434 else
425 self.accept_api_auth_actions || []
435 self.accept_api_auth_actions || []
426 end
436 end
427 end
437 end
428
438
429 def accept_api_auth?(action=action_name)
439 def accept_api_auth?(action=action_name)
430 self.class.accept_api_auth.include?(action.to_sym)
440 self.class.accept_api_auth.include?(action.to_sym)
431 end
441 end
432
442
433 # Returns the number of objects that should be displayed
443 # Returns the number of objects that should be displayed
434 # on the paginated list
444 # on the paginated list
435 def per_page_option
445 def per_page_option
436 per_page = nil
446 per_page = nil
437 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
447 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
438 per_page = params[:per_page].to_s.to_i
448 per_page = params[:per_page].to_s.to_i
439 session[:per_page] = per_page
449 session[:per_page] = per_page
440 elsif session[:per_page]
450 elsif session[:per_page]
441 per_page = session[:per_page]
451 per_page = session[:per_page]
442 else
452 else
443 per_page = Setting.per_page_options_array.first || 25
453 per_page = Setting.per_page_options_array.first || 25
444 end
454 end
445 per_page
455 per_page
446 end
456 end
447
457
448 # Returns offset and limit used to retrieve objects
458 # Returns offset and limit used to retrieve objects
449 # for an API response based on offset, limit and page parameters
459 # for an API response based on offset, limit and page parameters
450 def api_offset_and_limit(options=params)
460 def api_offset_and_limit(options=params)
451 if options[:offset].present?
461 if options[:offset].present?
452 offset = options[:offset].to_i
462 offset = options[:offset].to_i
453 if offset < 0
463 if offset < 0
454 offset = 0
464 offset = 0
455 end
465 end
456 end
466 end
457 limit = options[:limit].to_i
467 limit = options[:limit].to_i
458 if limit < 1
468 if limit < 1
459 limit = 25
469 limit = 25
460 elsif limit > 100
470 elsif limit > 100
461 limit = 100
471 limit = 100
462 end
472 end
463 if offset.nil? && options[:page].present?
473 if offset.nil? && options[:page].present?
464 offset = (options[:page].to_i - 1) * limit
474 offset = (options[:page].to_i - 1) * limit
465 offset = 0 if offset < 0
475 offset = 0 if offset < 0
466 end
476 end
467 offset ||= 0
477 offset ||= 0
468
478
469 [offset, limit]
479 [offset, limit]
470 end
480 end
471
481
472 # qvalues http header parser
482 # qvalues http header parser
473 # code taken from webrick
483 # code taken from webrick
474 def parse_qvalues(value)
484 def parse_qvalues(value)
475 tmp = []
485 tmp = []
476 if value
486 if value
477 parts = value.split(/,\s*/)
487 parts = value.split(/,\s*/)
478 parts.each {|part|
488 parts.each {|part|
479 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
489 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
480 val = m[1]
490 val = m[1]
481 q = (m[2] or 1).to_f
491 q = (m[2] or 1).to_f
482 tmp.push([val, q])
492 tmp.push([val, q])
483 end
493 end
484 }
494 }
485 tmp = tmp.sort_by{|val, q| -q}
495 tmp = tmp.sort_by{|val, q| -q}
486 tmp.collect!{|val, q| val}
496 tmp.collect!{|val, q| val}
487 end
497 end
488 return tmp
498 return tmp
489 rescue
499 rescue
490 nil
500 nil
491 end
501 end
492
502
493 # Returns a string that can be used as filename value in Content-Disposition header
503 # Returns a string that can be used as filename value in Content-Disposition header
494 def filename_for_content_disposition(name)
504 def filename_for_content_disposition(name)
495 request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name
505 request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name
496 end
506 end
497
507
498 def api_request?
508 def api_request?
499 %w(xml json).include? params[:format]
509 %w(xml json).include? params[:format]
500 end
510 end
501
511
502 # Returns the API key present in the request
512 # Returns the API key present in the request
503 def api_key_from_request
513 def api_key_from_request
504 if params[:key].present?
514 if params[:key].present?
505 params[:key].to_s
515 params[:key].to_s
506 elsif request.headers["X-Redmine-API-Key"].present?
516 elsif request.headers["X-Redmine-API-Key"].present?
507 request.headers["X-Redmine-API-Key"].to_s
517 request.headers["X-Redmine-API-Key"].to_s
508 end
518 end
509 end
519 end
510
520
521 # Returns the API 'switch user' value if present
522 def api_switch_user_from_request
523 request.headers["X-Redmine-Switch-User"].to_s.presence
524 end
525
511 # Renders a warning flash if obj has unsaved attachments
526 # Renders a warning flash if obj has unsaved attachments
512 def render_attachment_warning_if_needed(obj)
527 def render_attachment_warning_if_needed(obj)
513 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
528 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
514 end
529 end
515
530
516 # Sets the `flash` notice or error based the number of issues that did not save
531 # Sets the `flash` notice or error based the number of issues that did not save
517 #
532 #
518 # @param [Array, Issue] issues all of the saved and unsaved Issues
533 # @param [Array, Issue] issues all of the saved and unsaved Issues
519 # @param [Array, Integer] unsaved_issue_ids the issue ids that were not saved
534 # @param [Array, Integer] unsaved_issue_ids the issue ids that were not saved
520 def set_flash_from_bulk_issue_save(issues, unsaved_issue_ids)
535 def set_flash_from_bulk_issue_save(issues, unsaved_issue_ids)
521 if unsaved_issue_ids.empty?
536 if unsaved_issue_ids.empty?
522 flash[:notice] = l(:notice_successful_update) unless issues.empty?
537 flash[:notice] = l(:notice_successful_update) unless issues.empty?
523 else
538 else
524 flash[:error] = l(:notice_failed_to_save_issues,
539 flash[:error] = l(:notice_failed_to_save_issues,
525 :count => unsaved_issue_ids.size,
540 :count => unsaved_issue_ids.size,
526 :total => issues.size,
541 :total => issues.size,
527 :ids => '#' + unsaved_issue_ids.join(', #'))
542 :ids => '#' + unsaved_issue_ids.join(', #'))
528 end
543 end
529 end
544 end
530
545
531 # Rescues an invalid query statement. Just in case...
546 # Rescues an invalid query statement. Just in case...
532 def query_statement_invalid(exception)
547 def query_statement_invalid(exception)
533 logger.error "Query::StatementInvalid: #{exception.message}" if logger
548 logger.error "Query::StatementInvalid: #{exception.message}" if logger
534 session.delete(:query)
549 session.delete(:query)
535 sort_clear if respond_to?(:sort_clear)
550 sort_clear if respond_to?(:sort_clear)
536 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
551 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
537 end
552 end
538
553
539 # Renders a 200 response for successfull updates or deletions via the API
554 # Renders a 200 response for successfull updates or deletions via the API
540 def render_api_ok
555 def render_api_ok
541 # head :ok would return a response body with one space
556 # head :ok would return a response body with one space
542 render :text => '', :status => :ok, :layout => nil
557 render :text => '', :status => :ok, :layout => nil
543 end
558 end
544
559
545 # Renders API response on validation failure
560 # Renders API response on validation failure
546 def render_validation_errors(objects)
561 def render_validation_errors(objects)
547 if objects.is_a?(Array)
562 if objects.is_a?(Array)
548 @error_messages = objects.map {|object| object.errors.full_messages}.flatten
563 @error_messages = objects.map {|object| object.errors.full_messages}.flatten
549 else
564 else
550 @error_messages = objects.errors.full_messages
565 @error_messages = objects.errors.full_messages
551 end
566 end
552 render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
567 render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
553 end
568 end
554
569
555 # Overrides #_include_layout? so that #render with no arguments
570 # Overrides #_include_layout? so that #render with no arguments
556 # doesn't use the layout for api requests
571 # doesn't use the layout for api requests
557 def _include_layout?(*args)
572 def _include_layout?(*args)
558 api_request? ? false : super
573 api_request? ? false : super
559 end
574 end
560 end
575 end
@@ -1,32 +1,73
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2012 Jean-Philippe Lang
2 # Copyright (C) 2006-2012 Jean-Philippe Lang
3 #
3 #
4 # This program is free software; you can redistribute it and/or
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License
5 # modify it under the terms of the GNU General Public License
6 # as published by the Free Software Foundation; either version 2
6 # as published by the Free Software Foundation; either version 2
7 # of the License, or (at your option) any later version.
7 # of the License, or (at your option) any later version.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU General Public License
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17
17
18 require File.expand_path('../../../test_helper', __FILE__)
18 require File.expand_path('../../../test_helper', __FILE__)
19
19
20 class ApiTest::AuthenticationTest < ActionController::IntegrationTest
20 class ApiTest::AuthenticationTest < ActionController::IntegrationTest
21 fixtures :users
21 fixtures :users
22
22
23 def setup
24 Setting.rest_api_enabled = '1'
25 end
26
27 def teardown
28 Setting.rest_api_enabled = '0'
29 end
30
23 def test_api_request_should_not_use_user_session
31 def test_api_request_should_not_use_user_session
24 log_user('jsmith', 'jsmith')
32 log_user('jsmith', 'jsmith')
25
33
26 get '/users/current'
34 get '/users/current'
27 assert_response :success
35 assert_response :success
28
36
29 get '/users/current.json'
37 get '/users/current.json'
30 assert_response 401
38 assert_response 401
31 end
39 end
40
41 def test_api_should_accept_switch_user_header_for_admin_user
42 user = User.find(1)
43 su = User.find(4)
44
45 get '/users/current', {}, {'X-Redmine-API-Key' => user.api_key, 'X-Redmine-Switch-User' => su.login}
46 assert_response :success
47 assert_equal su, assigns(:user)
48 assert_equal su, User.current
49 end
50
51 def test_api_should_respond_with_412_when_trying_to_switch_to_a_invalid_user
52 get '/users/current', {}, {'X-Redmine-API-Key' => User.find(1).api_key, 'X-Redmine-Switch-User' => 'foobar'}
53 assert_response 412
54 end
55
56 def test_api_should_respond_with_412_when_trying_to_switch_to_a_locked_user
57 user = User.find(5)
58 assert user.locked?
59
60 get '/users/current', {}, {'X-Redmine-API-Key' => User.find(1).api_key, 'X-Redmine-Switch-User' => user.login}
61 assert_response 412
62 end
63
64 def test_api_should_not_accept_switch_user_header_for_non_admin_user
65 user = User.find(2)
66 su = User.find(4)
67
68 get '/users/current', {}, {'X-Redmine-API-Key' => user.api_key, 'X-Redmine-Switch-User' => su.login}
69 assert_response :success
70 assert_equal user, assigns(:user)
71 assert_equal user, User.current
72 end
32 end
73 end
General Comments 0
You need to be logged in to leave comments. Login now