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