##// END OF EJS Templates
Remove autologin cookie on unverified request....
Jean-Philippe Lang -
r6196:b81149fa47ed
parent child
Show More
@@ -1,518 +1,521
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2011 Jean-Philippe Lang
2 # Copyright (C) 2006-2011 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 layout 'base'
26 layout 'base'
27 exempt_from_layout 'builder', 'rsb'
27 exempt_from_layout 'builder', 'rsb'
28
28
29 protect_from_forgery
29 protect_from_forgery
30
30 def handle_unverified_request
31 super
32 cookies.delete(:autologin)
33 end
31 # Remove broken cookie after upgrade from 0.8.x (#4292)
34 # Remove broken cookie after upgrade from 0.8.x (#4292)
32 # See https://rails.lighthouseapp.com/projects/8994/tickets/3360
35 # See https://rails.lighthouseapp.com/projects/8994/tickets/3360
33 # TODO: remove it when Rails is fixed
36 # TODO: remove it when Rails is fixed
34 before_filter :delete_broken_cookies
37 before_filter :delete_broken_cookies
35 def delete_broken_cookies
38 def delete_broken_cookies
36 if cookies['_redmine_session'] && cookies['_redmine_session'] !~ /--/
39 if cookies['_redmine_session'] && cookies['_redmine_session'] !~ /--/
37 cookies.delete '_redmine_session'
40 cookies.delete '_redmine_session'
38 redirect_to home_path
41 redirect_to home_path
39 return false
42 return false
40 end
43 end
41 end
44 end
42
45
43 before_filter :user_setup, :check_if_login_required, :set_localization
46 before_filter :user_setup, :check_if_login_required, :set_localization
44 filter_parameter_logging :password
47 filter_parameter_logging :password
45
48
46 rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token
49 rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token
47 rescue_from ::Unauthorized, :with => :deny_access
50 rescue_from ::Unauthorized, :with => :deny_access
48
51
49 include Redmine::Search::Controller
52 include Redmine::Search::Controller
50 include Redmine::MenuManager::MenuController
53 include Redmine::MenuManager::MenuController
51 helper Redmine::MenuManager::MenuHelper
54 helper Redmine::MenuManager::MenuHelper
52
55
53 Redmine::Scm::Base.all.each do |scm|
56 Redmine::Scm::Base.all.each do |scm|
54 require_dependency "repository/#{scm.underscore}"
57 require_dependency "repository/#{scm.underscore}"
55 end
58 end
56
59
57 def user_setup
60 def user_setup
58 # Check the settings cache for each request
61 # Check the settings cache for each request
59 Setting.check_cache
62 Setting.check_cache
60 # Find the current user
63 # Find the current user
61 User.current = find_current_user
64 User.current = find_current_user
62 end
65 end
63
66
64 # Returns the current user or nil if no user is logged in
67 # Returns the current user or nil if no user is logged in
65 # and starts a session if needed
68 # and starts a session if needed
66 def find_current_user
69 def find_current_user
67 if session[:user_id]
70 if session[:user_id]
68 # existing session
71 # existing session
69 (User.active.find(session[:user_id]) rescue nil)
72 (User.active.find(session[:user_id]) rescue nil)
70 elsif cookies[:autologin] && Setting.autologin?
73 elsif cookies[:autologin] && Setting.autologin?
71 # auto-login feature starts a new session
74 # auto-login feature starts a new session
72 user = User.try_to_autologin(cookies[:autologin])
75 user = User.try_to_autologin(cookies[:autologin])
73 session[:user_id] = user.id if user
76 session[:user_id] = user.id if user
74 user
77 user
75 elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
78 elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
76 # RSS key authentication does not start a session
79 # RSS key authentication does not start a session
77 User.find_by_rss_key(params[:key])
80 User.find_by_rss_key(params[:key])
78 elsif Setting.rest_api_enabled? && accept_api_auth?
81 elsif Setting.rest_api_enabled? && accept_api_auth?
79 if (key = api_key_from_request)
82 if (key = api_key_from_request)
80 # Use API key
83 # Use API key
81 User.find_by_api_key(key)
84 User.find_by_api_key(key)
82 else
85 else
83 # HTTP Basic, either username/password or API key/random
86 # HTTP Basic, either username/password or API key/random
84 authenticate_with_http_basic do |username, password|
87 authenticate_with_http_basic do |username, password|
85 User.try_to_login(username, password) || User.find_by_api_key(username)
88 User.try_to_login(username, password) || User.find_by_api_key(username)
86 end
89 end
87 end
90 end
88 end
91 end
89 end
92 end
90
93
91 # Sets the logged in user
94 # Sets the logged in user
92 def logged_user=(user)
95 def logged_user=(user)
93 reset_session
96 reset_session
94 if user && user.is_a?(User)
97 if user && user.is_a?(User)
95 User.current = user
98 User.current = user
96 session[:user_id] = user.id
99 session[:user_id] = user.id
97 else
100 else
98 User.current = User.anonymous
101 User.current = User.anonymous
99 end
102 end
100 end
103 end
101
104
102 # check if login is globally required to access the application
105 # check if login is globally required to access the application
103 def check_if_login_required
106 def check_if_login_required
104 # no check needed if user is already logged in
107 # no check needed if user is already logged in
105 return true if User.current.logged?
108 return true if User.current.logged?
106 require_login if Setting.login_required?
109 require_login if Setting.login_required?
107 end
110 end
108
111
109 def set_localization
112 def set_localization
110 lang = nil
113 lang = nil
111 if User.current.logged?
114 if User.current.logged?
112 lang = find_language(User.current.language)
115 lang = find_language(User.current.language)
113 end
116 end
114 if lang.nil? && request.env['HTTP_ACCEPT_LANGUAGE']
117 if lang.nil? && request.env['HTTP_ACCEPT_LANGUAGE']
115 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
118 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
116 if !accept_lang.blank?
119 if !accept_lang.blank?
117 accept_lang = accept_lang.downcase
120 accept_lang = accept_lang.downcase
118 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
121 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
119 end
122 end
120 end
123 end
121 lang ||= Setting.default_language
124 lang ||= Setting.default_language
122 set_language_if_valid(lang)
125 set_language_if_valid(lang)
123 end
126 end
124
127
125 def require_login
128 def require_login
126 if !User.current.logged?
129 if !User.current.logged?
127 # Extract only the basic url parameters on non-GET requests
130 # Extract only the basic url parameters on non-GET requests
128 if request.get?
131 if request.get?
129 url = url_for(params)
132 url = url_for(params)
130 else
133 else
131 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
134 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
132 end
135 end
133 respond_to do |format|
136 respond_to do |format|
134 format.html { redirect_to :controller => "account", :action => "login", :back_url => url }
137 format.html { redirect_to :controller => "account", :action => "login", :back_url => url }
135 format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
138 format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
136 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
139 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
137 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
140 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
138 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
141 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
139 end
142 end
140 return false
143 return false
141 end
144 end
142 true
145 true
143 end
146 end
144
147
145 def require_admin
148 def require_admin
146 return unless require_login
149 return unless require_login
147 if !User.current.admin?
150 if !User.current.admin?
148 render_403
151 render_403
149 return false
152 return false
150 end
153 end
151 true
154 true
152 end
155 end
153
156
154 def deny_access
157 def deny_access
155 User.current.logged? ? render_403 : require_login
158 User.current.logged? ? render_403 : require_login
156 end
159 end
157
160
158 # Authorize the user for the requested action
161 # Authorize the user for the requested action
159 def authorize(ctrl = params[:controller], action = params[:action], global = false)
162 def authorize(ctrl = params[:controller], action = params[:action], global = false)
160 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
163 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
161 if allowed
164 if allowed
162 true
165 true
163 else
166 else
164 if @project && @project.archived?
167 if @project && @project.archived?
165 render_403 :message => :notice_not_authorized_archived_project
168 render_403 :message => :notice_not_authorized_archived_project
166 else
169 else
167 deny_access
170 deny_access
168 end
171 end
169 end
172 end
170 end
173 end
171
174
172 # Authorize the user for the requested action outside a project
175 # Authorize the user for the requested action outside a project
173 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
176 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
174 authorize(ctrl, action, global)
177 authorize(ctrl, action, global)
175 end
178 end
176
179
177 # Find project of id params[:id]
180 # Find project of id params[:id]
178 def find_project
181 def find_project
179 @project = Project.find(params[:id])
182 @project = Project.find(params[:id])
180 rescue ActiveRecord::RecordNotFound
183 rescue ActiveRecord::RecordNotFound
181 render_404
184 render_404
182 end
185 end
183
186
184 # Find project of id params[:project_id]
187 # Find project of id params[:project_id]
185 def find_project_by_project_id
188 def find_project_by_project_id
186 @project = Project.find(params[:project_id])
189 @project = Project.find(params[:project_id])
187 rescue ActiveRecord::RecordNotFound
190 rescue ActiveRecord::RecordNotFound
188 render_404
191 render_404
189 end
192 end
190
193
191 # Find a project based on params[:project_id]
194 # Find a project based on params[:project_id]
192 # TODO: some subclasses override this, see about merging their logic
195 # TODO: some subclasses override this, see about merging their logic
193 def find_optional_project
196 def find_optional_project
194 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
197 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
195 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
198 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
196 allowed ? true : deny_access
199 allowed ? true : deny_access
197 rescue ActiveRecord::RecordNotFound
200 rescue ActiveRecord::RecordNotFound
198 render_404
201 render_404
199 end
202 end
200
203
201 # Finds and sets @project based on @object.project
204 # Finds and sets @project based on @object.project
202 def find_project_from_association
205 def find_project_from_association
203 render_404 unless @object.present?
206 render_404 unless @object.present?
204
207
205 @project = @object.project
208 @project = @object.project
206 rescue ActiveRecord::RecordNotFound
209 rescue ActiveRecord::RecordNotFound
207 render_404
210 render_404
208 end
211 end
209
212
210 def find_model_object
213 def find_model_object
211 model = self.class.read_inheritable_attribute('model_object')
214 model = self.class.read_inheritable_attribute('model_object')
212 if model
215 if model
213 @object = model.find(params[:id])
216 @object = model.find(params[:id])
214 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
217 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
215 end
218 end
216 rescue ActiveRecord::RecordNotFound
219 rescue ActiveRecord::RecordNotFound
217 render_404
220 render_404
218 end
221 end
219
222
220 def self.model_object(model)
223 def self.model_object(model)
221 write_inheritable_attribute('model_object', model)
224 write_inheritable_attribute('model_object', model)
222 end
225 end
223
226
224 # Filter for bulk issue operations
227 # Filter for bulk issue operations
225 def find_issues
228 def find_issues
226 @issues = Issue.find_all_by_id(params[:id] || params[:ids])
229 @issues = Issue.find_all_by_id(params[:id] || params[:ids])
227 raise ActiveRecord::RecordNotFound if @issues.empty?
230 raise ActiveRecord::RecordNotFound if @issues.empty?
228 if @issues.detect {|issue| !issue.visible?}
231 if @issues.detect {|issue| !issue.visible?}
229 deny_access
232 deny_access
230 return
233 return
231 end
234 end
232 @projects = @issues.collect(&:project).compact.uniq
235 @projects = @issues.collect(&:project).compact.uniq
233 @project = @projects.first if @projects.size == 1
236 @project = @projects.first if @projects.size == 1
234 rescue ActiveRecord::RecordNotFound
237 rescue ActiveRecord::RecordNotFound
235 render_404
238 render_404
236 end
239 end
237
240
238 # Check if project is unique before bulk operations
241 # Check if project is unique before bulk operations
239 def check_project_uniqueness
242 def check_project_uniqueness
240 unless @project
243 unless @project
241 # TODO: let users bulk edit/move/destroy issues from different projects
244 # TODO: let users bulk edit/move/destroy issues from different projects
242 render_error 'Can not bulk edit/move/destroy issues from different projects'
245 render_error 'Can not bulk edit/move/destroy issues from different projects'
243 return false
246 return false
244 end
247 end
245 end
248 end
246
249
247 # make sure that the user is a member of the project (or admin) if project is private
250 # make sure that the user is a member of the project (or admin) if project is private
248 # used as a before_filter for actions that do not require any particular permission on the project
251 # used as a before_filter for actions that do not require any particular permission on the project
249 def check_project_privacy
252 def check_project_privacy
250 if @project && @project.active?
253 if @project && @project.active?
251 if @project.is_public? || User.current.member_of?(@project) || User.current.admin?
254 if @project.is_public? || User.current.member_of?(@project) || User.current.admin?
252 true
255 true
253 else
256 else
254 User.current.logged? ? render_403 : require_login
257 User.current.logged? ? render_403 : require_login
255 end
258 end
256 else
259 else
257 @project = nil
260 @project = nil
258 render_404
261 render_404
259 false
262 false
260 end
263 end
261 end
264 end
262
265
263 def back_url
266 def back_url
264 params[:back_url] || request.env['HTTP_REFERER']
267 params[:back_url] || request.env['HTTP_REFERER']
265 end
268 end
266
269
267 def redirect_back_or_default(default)
270 def redirect_back_or_default(default)
268 back_url = CGI.unescape(params[:back_url].to_s)
271 back_url = CGI.unescape(params[:back_url].to_s)
269 if !back_url.blank?
272 if !back_url.blank?
270 begin
273 begin
271 uri = URI.parse(back_url)
274 uri = URI.parse(back_url)
272 # do not redirect user to another host or to the login or register page
275 # do not redirect user to another host or to the login or register page
273 if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})
276 if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})
274 redirect_to(back_url)
277 redirect_to(back_url)
275 return
278 return
276 end
279 end
277 rescue URI::InvalidURIError
280 rescue URI::InvalidURIError
278 # redirect to default
281 # redirect to default
279 end
282 end
280 end
283 end
281 redirect_to default
284 redirect_to default
282 false
285 false
283 end
286 end
284
287
285 def render_403(options={})
288 def render_403(options={})
286 @project = nil
289 @project = nil
287 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
290 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
288 return false
291 return false
289 end
292 end
290
293
291 def render_404(options={})
294 def render_404(options={})
292 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
295 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
293 return false
296 return false
294 end
297 end
295
298
296 # Renders an error response
299 # Renders an error response
297 def render_error(arg)
300 def render_error(arg)
298 arg = {:message => arg} unless arg.is_a?(Hash)
301 arg = {:message => arg} unless arg.is_a?(Hash)
299
302
300 @message = arg[:message]
303 @message = arg[:message]
301 @message = l(@message) if @message.is_a?(Symbol)
304 @message = l(@message) if @message.is_a?(Symbol)
302 @status = arg[:status] || 500
305 @status = arg[:status] || 500
303
306
304 respond_to do |format|
307 respond_to do |format|
305 format.html {
308 format.html {
306 render :template => 'common/error', :layout => use_layout, :status => @status
309 render :template => 'common/error', :layout => use_layout, :status => @status
307 }
310 }
308 format.atom { head @status }
311 format.atom { head @status }
309 format.xml { head @status }
312 format.xml { head @status }
310 format.js { head @status }
313 format.js { head @status }
311 format.json { head @status }
314 format.json { head @status }
312 end
315 end
313 end
316 end
314
317
315 # Picks which layout to use based on the request
318 # Picks which layout to use based on the request
316 #
319 #
317 # @return [boolean, string] name of the layout to use or false for no layout
320 # @return [boolean, string] name of the layout to use or false for no layout
318 def use_layout
321 def use_layout
319 request.xhr? ? false : 'base'
322 request.xhr? ? false : 'base'
320 end
323 end
321
324
322 def invalid_authenticity_token
325 def invalid_authenticity_token
323 if api_request?
326 if api_request?
324 logger.error "Form authenticity token is missing or is invalid. API calls must include a proper Content-type header (text/xml or text/json)."
327 logger.error "Form authenticity token is missing or is invalid. API calls must include a proper Content-type header (text/xml or text/json)."
325 end
328 end
326 render_error "Invalid form authenticity token."
329 render_error "Invalid form authenticity token."
327 end
330 end
328
331
329 def render_feed(items, options={})
332 def render_feed(items, options={})
330 @items = items || []
333 @items = items || []
331 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
334 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
332 @items = @items.slice(0, Setting.feeds_limit.to_i)
335 @items = @items.slice(0, Setting.feeds_limit.to_i)
333 @title = options[:title] || Setting.app_title
336 @title = options[:title] || Setting.app_title
334 render :template => "common/feed.atom.rxml", :layout => false, :content_type => 'application/atom+xml'
337 render :template => "common/feed.atom.rxml", :layout => false, :content_type => 'application/atom+xml'
335 end
338 end
336
339
337 # TODO: remove in Redmine 1.4
340 # TODO: remove in Redmine 1.4
338 def self.accept_key_auth(*actions)
341 def self.accept_key_auth(*actions)
339 ActiveSupport::Deprecation.warn "ApplicationController.accept_key_auth is deprecated and will be removed in Redmine 1.4. Use accept_rss_auth (or accept_api_auth) instead."
342 ActiveSupport::Deprecation.warn "ApplicationController.accept_key_auth is deprecated and will be removed in Redmine 1.4. Use accept_rss_auth (or accept_api_auth) instead."
340 accept_rss_auth(*actions)
343 accept_rss_auth(*actions)
341 end
344 end
342
345
343 # TODO: remove in Redmine 1.4
346 # TODO: remove in Redmine 1.4
344 def accept_key_auth_actions
347 def accept_key_auth_actions
345 ActiveSupport::Deprecation.warn "ApplicationController.accept_key_auth_actions is deprecated and will be removed in Redmine 1.4. Use accept_rss_auth (or accept_api_auth) instead."
348 ActiveSupport::Deprecation.warn "ApplicationController.accept_key_auth_actions is deprecated and will be removed in Redmine 1.4. Use accept_rss_auth (or accept_api_auth) instead."
346 self.class.accept_rss_auth
349 self.class.accept_rss_auth
347 end
350 end
348
351
349 def self.accept_rss_auth(*actions)
352 def self.accept_rss_auth(*actions)
350 if actions.any?
353 if actions.any?
351 write_inheritable_attribute('accept_rss_auth_actions', actions)
354 write_inheritable_attribute('accept_rss_auth_actions', actions)
352 else
355 else
353 read_inheritable_attribute('accept_rss_auth_actions') || []
356 read_inheritable_attribute('accept_rss_auth_actions') || []
354 end
357 end
355 end
358 end
356
359
357 def accept_rss_auth?(action=action_name)
360 def accept_rss_auth?(action=action_name)
358 self.class.accept_rss_auth.include?(action.to_sym)
361 self.class.accept_rss_auth.include?(action.to_sym)
359 end
362 end
360
363
361 def self.accept_api_auth(*actions)
364 def self.accept_api_auth(*actions)
362 if actions.any?
365 if actions.any?
363 write_inheritable_attribute('accept_api_auth_actions', actions)
366 write_inheritable_attribute('accept_api_auth_actions', actions)
364 else
367 else
365 read_inheritable_attribute('accept_api_auth_actions') || []
368 read_inheritable_attribute('accept_api_auth_actions') || []
366 end
369 end
367 end
370 end
368
371
369 def accept_api_auth?(action=action_name)
372 def accept_api_auth?(action=action_name)
370 self.class.accept_api_auth.include?(action.to_sym)
373 self.class.accept_api_auth.include?(action.to_sym)
371 end
374 end
372
375
373 # Returns the number of objects that should be displayed
376 # Returns the number of objects that should be displayed
374 # on the paginated list
377 # on the paginated list
375 def per_page_option
378 def per_page_option
376 per_page = nil
379 per_page = nil
377 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
380 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
378 per_page = params[:per_page].to_s.to_i
381 per_page = params[:per_page].to_s.to_i
379 session[:per_page] = per_page
382 session[:per_page] = per_page
380 elsif session[:per_page]
383 elsif session[:per_page]
381 per_page = session[:per_page]
384 per_page = session[:per_page]
382 else
385 else
383 per_page = Setting.per_page_options_array.first || 25
386 per_page = Setting.per_page_options_array.first || 25
384 end
387 end
385 per_page
388 per_page
386 end
389 end
387
390
388 # Returns offset and limit used to retrieve objects
391 # Returns offset and limit used to retrieve objects
389 # for an API response based on offset, limit and page parameters
392 # for an API response based on offset, limit and page parameters
390 def api_offset_and_limit(options=params)
393 def api_offset_and_limit(options=params)
391 if options[:offset].present?
394 if options[:offset].present?
392 offset = options[:offset].to_i
395 offset = options[:offset].to_i
393 if offset < 0
396 if offset < 0
394 offset = 0
397 offset = 0
395 end
398 end
396 end
399 end
397 limit = options[:limit].to_i
400 limit = options[:limit].to_i
398 if limit < 1
401 if limit < 1
399 limit = 25
402 limit = 25
400 elsif limit > 100
403 elsif limit > 100
401 limit = 100
404 limit = 100
402 end
405 end
403 if offset.nil? && options[:page].present?
406 if offset.nil? && options[:page].present?
404 offset = (options[:page].to_i - 1) * limit
407 offset = (options[:page].to_i - 1) * limit
405 offset = 0 if offset < 0
408 offset = 0 if offset < 0
406 end
409 end
407 offset ||= 0
410 offset ||= 0
408
411
409 [offset, limit]
412 [offset, limit]
410 end
413 end
411
414
412 # qvalues http header parser
415 # qvalues http header parser
413 # code taken from webrick
416 # code taken from webrick
414 def parse_qvalues(value)
417 def parse_qvalues(value)
415 tmp = []
418 tmp = []
416 if value
419 if value
417 parts = value.split(/,\s*/)
420 parts = value.split(/,\s*/)
418 parts.each {|part|
421 parts.each {|part|
419 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
422 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
420 val = m[1]
423 val = m[1]
421 q = (m[2] or 1).to_f
424 q = (m[2] or 1).to_f
422 tmp.push([val, q])
425 tmp.push([val, q])
423 end
426 end
424 }
427 }
425 tmp = tmp.sort_by{|val, q| -q}
428 tmp = tmp.sort_by{|val, q| -q}
426 tmp.collect!{|val, q| val}
429 tmp.collect!{|val, q| val}
427 end
430 end
428 return tmp
431 return tmp
429 rescue
432 rescue
430 nil
433 nil
431 end
434 end
432
435
433 # Returns a string that can be used as filename value in Content-Disposition header
436 # Returns a string that can be used as filename value in Content-Disposition header
434 def filename_for_content_disposition(name)
437 def filename_for_content_disposition(name)
435 request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name
438 request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name
436 end
439 end
437
440
438 def api_request?
441 def api_request?
439 %w(xml json).include? params[:format]
442 %w(xml json).include? params[:format]
440 end
443 end
441
444
442 # Returns the API key present in the request
445 # Returns the API key present in the request
443 def api_key_from_request
446 def api_key_from_request
444 if params[:key].present?
447 if params[:key].present?
445 params[:key]
448 params[:key]
446 elsif request.headers["X-Redmine-API-Key"].present?
449 elsif request.headers["X-Redmine-API-Key"].present?
447 request.headers["X-Redmine-API-Key"]
450 request.headers["X-Redmine-API-Key"]
448 end
451 end
449 end
452 end
450
453
451 # Renders a warning flash if obj has unsaved attachments
454 # Renders a warning flash if obj has unsaved attachments
452 def render_attachment_warning_if_needed(obj)
455 def render_attachment_warning_if_needed(obj)
453 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
456 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
454 end
457 end
455
458
456 # Sets the `flash` notice or error based the number of issues that did not save
459 # Sets the `flash` notice or error based the number of issues that did not save
457 #
460 #
458 # @param [Array, Issue] issues all of the saved and unsaved Issues
461 # @param [Array, Issue] issues all of the saved and unsaved Issues
459 # @param [Array, Integer] unsaved_issue_ids the issue ids that were not saved
462 # @param [Array, Integer] unsaved_issue_ids the issue ids that were not saved
460 def set_flash_from_bulk_issue_save(issues, unsaved_issue_ids)
463 def set_flash_from_bulk_issue_save(issues, unsaved_issue_ids)
461 if unsaved_issue_ids.empty?
464 if unsaved_issue_ids.empty?
462 flash[:notice] = l(:notice_successful_update) unless issues.empty?
465 flash[:notice] = l(:notice_successful_update) unless issues.empty?
463 else
466 else
464 flash[:error] = l(:notice_failed_to_save_issues,
467 flash[:error] = l(:notice_failed_to_save_issues,
465 :count => unsaved_issue_ids.size,
468 :count => unsaved_issue_ids.size,
466 :total => issues.size,
469 :total => issues.size,
467 :ids => '#' + unsaved_issue_ids.join(', #'))
470 :ids => '#' + unsaved_issue_ids.join(', #'))
468 end
471 end
469 end
472 end
470
473
471 # Rescues an invalid query statement. Just in case...
474 # Rescues an invalid query statement. Just in case...
472 def query_statement_invalid(exception)
475 def query_statement_invalid(exception)
473 logger.error "Query::StatementInvalid: #{exception.message}" if logger
476 logger.error "Query::StatementInvalid: #{exception.message}" if logger
474 session.delete(:query)
477 session.delete(:query)
475 sort_clear if respond_to?(:sort_clear)
478 sort_clear if respond_to?(:sort_clear)
476 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
479 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
477 end
480 end
478
481
479 # Converts the errors on an ActiveRecord object into a common JSON format
482 # Converts the errors on an ActiveRecord object into a common JSON format
480 def object_errors_to_json(object)
483 def object_errors_to_json(object)
481 object.errors.collect do |attribute, error|
484 object.errors.collect do |attribute, error|
482 { attribute => error }
485 { attribute => error }
483 end.to_json
486 end.to_json
484 end
487 end
485
488
486 # Renders API response on validation failure
489 # Renders API response on validation failure
487 def render_validation_errors(object)
490 def render_validation_errors(object)
488 options = { :status => :unprocessable_entity, :layout => false }
491 options = { :status => :unprocessable_entity, :layout => false }
489 options.merge!(case params[:format]
492 options.merge!(case params[:format]
490 when 'xml'; { :xml => object.errors }
493 when 'xml'; { :xml => object.errors }
491 when 'json'; { :json => {'errors' => object.errors} } # ActiveResource client compliance
494 when 'json'; { :json => {'errors' => object.errors} } # ActiveResource client compliance
492 else
495 else
493 raise "Unknown format #{params[:format]} in #render_validation_errors"
496 raise "Unknown format #{params[:format]} in #render_validation_errors"
494 end
497 end
495 )
498 )
496 render options
499 render options
497 end
500 end
498
501
499 # Overrides #default_template so that the api template
502 # Overrides #default_template so that the api template
500 # is used automatically if it exists
503 # is used automatically if it exists
501 def default_template(action_name = self.action_name)
504 def default_template(action_name = self.action_name)
502 if api_request?
505 if api_request?
503 begin
506 begin
504 return self.view_paths.find_template(default_template_name(action_name), 'api')
507 return self.view_paths.find_template(default_template_name(action_name), 'api')
505 rescue ::ActionView::MissingTemplate
508 rescue ::ActionView::MissingTemplate
506 # the api template was not found
509 # the api template was not found
507 # fallback to the default behaviour
510 # fallback to the default behaviour
508 end
511 end
509 end
512 end
510 super
513 super
511 end
514 end
512
515
513 # Overrides #pick_layout so that #render with no arguments
516 # Overrides #pick_layout so that #render with no arguments
514 # doesn't use the layout for api requests
517 # doesn't use the layout for api requests
515 def pick_layout(*args)
518 def pick_layout(*args)
516 api_request? ? nil : super
519 api_request? ? nil : super
517 end
520 end
518 end
521 end
General Comments 0
You need to be logged in to leave comments. Login now