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