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