##// END OF EJS Templates
Preload issues custom values for bulk operations....
Jean-Philippe Lang -
r14348:4714b310022d
parent child
Show More
@@ -1,681 +1,684
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2015 Jean-Philippe Lang
2 # Copyright (C) 2006-2015 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 include Redmine::Pagination
25 include Redmine::Pagination
26 include Redmine::Hook::Helper
26 include Redmine::Hook::Helper
27 include RoutesHelper
27 include RoutesHelper
28 helper :routes
28 helper :routes
29
29
30 class_attribute :accept_api_auth_actions
30 class_attribute :accept_api_auth_actions
31 class_attribute :accept_rss_auth_actions
31 class_attribute :accept_rss_auth_actions
32 class_attribute :model_object
32 class_attribute :model_object
33
33
34 layout 'base'
34 layout 'base'
35
35
36 protect_from_forgery
36 protect_from_forgery
37
37
38 def verify_authenticity_token
38 def verify_authenticity_token
39 unless api_request?
39 unless api_request?
40 super
40 super
41 end
41 end
42 end
42 end
43
43
44 def handle_unverified_request
44 def handle_unverified_request
45 unless api_request?
45 unless api_request?
46 super
46 super
47 cookies.delete(autologin_cookie_name)
47 cookies.delete(autologin_cookie_name)
48 self.logged_user = nil
48 self.logged_user = nil
49 set_localization
49 set_localization
50 render_error :status => 422, :message => "Invalid form authenticity token."
50 render_error :status => 422, :message => "Invalid form authenticity token."
51 end
51 end
52 end
52 end
53
53
54 before_filter :session_expiration, :user_setup, :force_logout_if_password_changed, :check_if_login_required, :check_password_change, :set_localization
54 before_filter :session_expiration, :user_setup, :force_logout_if_password_changed, :check_if_login_required, :check_password_change, :set_localization
55
55
56 rescue_from ::Unauthorized, :with => :deny_access
56 rescue_from ::Unauthorized, :with => :deny_access
57 rescue_from ::ActionView::MissingTemplate, :with => :missing_template
57 rescue_from ::ActionView::MissingTemplate, :with => :missing_template
58
58
59 include Redmine::Search::Controller
59 include Redmine::Search::Controller
60 include Redmine::MenuManager::MenuController
60 include Redmine::MenuManager::MenuController
61 helper Redmine::MenuManager::MenuHelper
61 helper Redmine::MenuManager::MenuHelper
62
62
63 include Redmine::SudoMode::Controller
63 include Redmine::SudoMode::Controller
64
64
65 def session_expiration
65 def session_expiration
66 if session[:user_id]
66 if session[:user_id]
67 if session_expired? && !try_to_autologin
67 if session_expired? && !try_to_autologin
68 set_localization(User.active.find_by_id(session[:user_id]))
68 set_localization(User.active.find_by_id(session[:user_id]))
69 self.logged_user = nil
69 self.logged_user = nil
70 flash[:error] = l(:error_session_expired)
70 flash[:error] = l(:error_session_expired)
71 require_login
71 require_login
72 else
72 else
73 session[:atime] = Time.now.utc.to_i
73 session[:atime] = Time.now.utc.to_i
74 end
74 end
75 end
75 end
76 end
76 end
77
77
78 def session_expired?
78 def session_expired?
79 if Setting.session_lifetime?
79 if Setting.session_lifetime?
80 unless session[:ctime] && (Time.now.utc.to_i - session[:ctime].to_i <= Setting.session_lifetime.to_i * 60)
80 unless session[:ctime] && (Time.now.utc.to_i - session[:ctime].to_i <= Setting.session_lifetime.to_i * 60)
81 return true
81 return true
82 end
82 end
83 end
83 end
84 if Setting.session_timeout?
84 if Setting.session_timeout?
85 unless session[:atime] && (Time.now.utc.to_i - session[:atime].to_i <= Setting.session_timeout.to_i * 60)
85 unless session[:atime] && (Time.now.utc.to_i - session[:atime].to_i <= Setting.session_timeout.to_i * 60)
86 return true
86 return true
87 end
87 end
88 end
88 end
89 false
89 false
90 end
90 end
91
91
92 def start_user_session(user)
92 def start_user_session(user)
93 session[:user_id] = user.id
93 session[:user_id] = user.id
94 session[:ctime] = Time.now.utc.to_i
94 session[:ctime] = Time.now.utc.to_i
95 session[:atime] = Time.now.utc.to_i
95 session[:atime] = Time.now.utc.to_i
96 if user.must_change_password?
96 if user.must_change_password?
97 session[:pwd] = '1'
97 session[:pwd] = '1'
98 end
98 end
99 end
99 end
100
100
101 def user_setup
101 def user_setup
102 # Check the settings cache for each request
102 # Check the settings cache for each request
103 Setting.check_cache
103 Setting.check_cache
104 # Find the current user
104 # Find the current user
105 User.current = find_current_user
105 User.current = find_current_user
106 logger.info(" Current user: " + (User.current.logged? ? "#{User.current.login} (id=#{User.current.id})" : "anonymous")) if logger
106 logger.info(" Current user: " + (User.current.logged? ? "#{User.current.login} (id=#{User.current.id})" : "anonymous")) if logger
107 end
107 end
108
108
109 # Returns the current user or nil if no user is logged in
109 # Returns the current user or nil if no user is logged in
110 # and starts a session if needed
110 # and starts a session if needed
111 def find_current_user
111 def find_current_user
112 user = nil
112 user = nil
113 unless api_request?
113 unless api_request?
114 if session[:user_id]
114 if session[:user_id]
115 # existing session
115 # existing session
116 user = (User.active.find(session[:user_id]) rescue nil)
116 user = (User.active.find(session[:user_id]) rescue nil)
117 elsif autologin_user = try_to_autologin
117 elsif autologin_user = try_to_autologin
118 user = autologin_user
118 user = autologin_user
119 elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
119 elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
120 # RSS key authentication does not start a session
120 # RSS key authentication does not start a session
121 user = User.find_by_rss_key(params[:key])
121 user = User.find_by_rss_key(params[:key])
122 end
122 end
123 end
123 end
124 if user.nil? && Setting.rest_api_enabled? && accept_api_auth?
124 if user.nil? && Setting.rest_api_enabled? && accept_api_auth?
125 if (key = api_key_from_request)
125 if (key = api_key_from_request)
126 # Use API key
126 # Use API key
127 user = User.find_by_api_key(key)
127 user = User.find_by_api_key(key)
128 elsif request.authorization.to_s =~ /\ABasic /i
128 elsif request.authorization.to_s =~ /\ABasic /i
129 # HTTP Basic, either username/password or API key/random
129 # HTTP Basic, either username/password or API key/random
130 authenticate_with_http_basic do |username, password|
130 authenticate_with_http_basic do |username, password|
131 user = User.try_to_login(username, password) || User.find_by_api_key(username)
131 user = User.try_to_login(username, password) || User.find_by_api_key(username)
132 end
132 end
133 if user && user.must_change_password?
133 if user && user.must_change_password?
134 render_error :message => 'You must change your password', :status => 403
134 render_error :message => 'You must change your password', :status => 403
135 return
135 return
136 end
136 end
137 end
137 end
138 # Switch user if requested by an admin user
138 # Switch user if requested by an admin user
139 if user && user.admin? && (username = api_switch_user_from_request)
139 if user && user.admin? && (username = api_switch_user_from_request)
140 su = User.find_by_login(username)
140 su = User.find_by_login(username)
141 if su && su.active?
141 if su && su.active?
142 logger.info(" User switched by: #{user.login} (id=#{user.id})") if logger
142 logger.info(" User switched by: #{user.login} (id=#{user.id})") if logger
143 user = su
143 user = su
144 else
144 else
145 render_error :message => 'Invalid X-Redmine-Switch-User header', :status => 412
145 render_error :message => 'Invalid X-Redmine-Switch-User header', :status => 412
146 end
146 end
147 end
147 end
148 end
148 end
149 user
149 user
150 end
150 end
151
151
152 def force_logout_if_password_changed
152 def force_logout_if_password_changed
153 passwd_changed_on = User.current.passwd_changed_on || Time.at(0)
153 passwd_changed_on = User.current.passwd_changed_on || Time.at(0)
154 # Make sure we force logout only for web browser sessions, not API calls
154 # Make sure we force logout only for web browser sessions, not API calls
155 # if the password was changed after the session creation.
155 # if the password was changed after the session creation.
156 if session[:user_id] && passwd_changed_on.utc.to_i > session[:ctime].to_i
156 if session[:user_id] && passwd_changed_on.utc.to_i > session[:ctime].to_i
157 reset_session
157 reset_session
158 set_localization
158 set_localization
159 flash[:error] = l(:error_session_expired)
159 flash[:error] = l(:error_session_expired)
160 redirect_to signin_url
160 redirect_to signin_url
161 end
161 end
162 end
162 end
163
163
164 def autologin_cookie_name
164 def autologin_cookie_name
165 Redmine::Configuration['autologin_cookie_name'].presence || 'autologin'
165 Redmine::Configuration['autologin_cookie_name'].presence || 'autologin'
166 end
166 end
167
167
168 def try_to_autologin
168 def try_to_autologin
169 if cookies[autologin_cookie_name] && Setting.autologin?
169 if cookies[autologin_cookie_name] && Setting.autologin?
170 # auto-login feature starts a new session
170 # auto-login feature starts a new session
171 user = User.try_to_autologin(cookies[autologin_cookie_name])
171 user = User.try_to_autologin(cookies[autologin_cookie_name])
172 if user
172 if user
173 reset_session
173 reset_session
174 start_user_session(user)
174 start_user_session(user)
175 end
175 end
176 user
176 user
177 end
177 end
178 end
178 end
179
179
180 # Sets the logged in user
180 # Sets the logged in user
181 def logged_user=(user)
181 def logged_user=(user)
182 reset_session
182 reset_session
183 if user && user.is_a?(User)
183 if user && user.is_a?(User)
184 User.current = user
184 User.current = user
185 start_user_session(user)
185 start_user_session(user)
186 else
186 else
187 User.current = User.anonymous
187 User.current = User.anonymous
188 end
188 end
189 end
189 end
190
190
191 # Logs out current user
191 # Logs out current user
192 def logout_user
192 def logout_user
193 if User.current.logged?
193 if User.current.logged?
194 cookies.delete(autologin_cookie_name)
194 cookies.delete(autologin_cookie_name)
195 Token.delete_all(["user_id = ? AND action = ?", User.current.id, 'autologin'])
195 Token.delete_all(["user_id = ? AND action = ?", User.current.id, 'autologin'])
196 self.logged_user = nil
196 self.logged_user = nil
197 end
197 end
198 end
198 end
199
199
200 # check if login is globally required to access the application
200 # check if login is globally required to access the application
201 def check_if_login_required
201 def check_if_login_required
202 # no check needed if user is already logged in
202 # no check needed if user is already logged in
203 return true if User.current.logged?
203 return true if User.current.logged?
204 require_login if Setting.login_required?
204 require_login if Setting.login_required?
205 end
205 end
206
206
207 def check_password_change
207 def check_password_change
208 if session[:pwd]
208 if session[:pwd]
209 if User.current.must_change_password?
209 if User.current.must_change_password?
210 flash[:error] = l(:error_password_expired)
210 flash[:error] = l(:error_password_expired)
211 redirect_to my_password_path
211 redirect_to my_password_path
212 else
212 else
213 session.delete(:pwd)
213 session.delete(:pwd)
214 end
214 end
215 end
215 end
216 end
216 end
217
217
218 def set_localization(user=User.current)
218 def set_localization(user=User.current)
219 lang = nil
219 lang = nil
220 if user && user.logged?
220 if user && user.logged?
221 lang = find_language(user.language)
221 lang = find_language(user.language)
222 end
222 end
223 if lang.nil? && !Setting.force_default_language_for_anonymous? && request.env['HTTP_ACCEPT_LANGUAGE']
223 if lang.nil? && !Setting.force_default_language_for_anonymous? && request.env['HTTP_ACCEPT_LANGUAGE']
224 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
224 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
225 if !accept_lang.blank?
225 if !accept_lang.blank?
226 accept_lang = accept_lang.downcase
226 accept_lang = accept_lang.downcase
227 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
227 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
228 end
228 end
229 end
229 end
230 lang ||= Setting.default_language
230 lang ||= Setting.default_language
231 set_language_if_valid(lang)
231 set_language_if_valid(lang)
232 end
232 end
233
233
234 def require_login
234 def require_login
235 if !User.current.logged?
235 if !User.current.logged?
236 # Extract only the basic url parameters on non-GET requests
236 # Extract only the basic url parameters on non-GET requests
237 if request.get?
237 if request.get?
238 url = url_for(params)
238 url = url_for(params)
239 else
239 else
240 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
240 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
241 end
241 end
242 respond_to do |format|
242 respond_to do |format|
243 format.html {
243 format.html {
244 if request.xhr?
244 if request.xhr?
245 head :unauthorized
245 head :unauthorized
246 else
246 else
247 redirect_to signin_path(:back_url => url)
247 redirect_to signin_path(:back_url => url)
248 end
248 end
249 }
249 }
250 format.any(:atom, :pdf, :csv) {
250 format.any(:atom, :pdf, :csv) {
251 redirect_to signin_path(:back_url => url)
251 redirect_to signin_path(:back_url => url)
252 }
252 }
253 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
253 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
254 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
254 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
255 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
255 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
256 format.any { head :unauthorized }
256 format.any { head :unauthorized }
257 end
257 end
258 return false
258 return false
259 end
259 end
260 true
260 true
261 end
261 end
262
262
263 def require_admin
263 def require_admin
264 return unless require_login
264 return unless require_login
265 if !User.current.admin?
265 if !User.current.admin?
266 render_403
266 render_403
267 return false
267 return false
268 end
268 end
269 true
269 true
270 end
270 end
271
271
272 def deny_access
272 def deny_access
273 User.current.logged? ? render_403 : require_login
273 User.current.logged? ? render_403 : require_login
274 end
274 end
275
275
276 # Authorize the user for the requested action
276 # Authorize the user for the requested action
277 def authorize(ctrl = params[:controller], action = params[:action], global = false)
277 def authorize(ctrl = params[:controller], action = params[:action], global = false)
278 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
278 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
279 if allowed
279 if allowed
280 true
280 true
281 else
281 else
282 if @project && @project.archived?
282 if @project && @project.archived?
283 render_403 :message => :notice_not_authorized_archived_project
283 render_403 :message => :notice_not_authorized_archived_project
284 else
284 else
285 deny_access
285 deny_access
286 end
286 end
287 end
287 end
288 end
288 end
289
289
290 # Authorize the user for the requested action outside a project
290 # Authorize the user for the requested action outside a project
291 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
291 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
292 authorize(ctrl, action, global)
292 authorize(ctrl, action, global)
293 end
293 end
294
294
295 # Find project of id params[:id]
295 # Find project of id params[:id]
296 def find_project
296 def find_project
297 @project = Project.find(params[:id])
297 @project = Project.find(params[:id])
298 rescue ActiveRecord::RecordNotFound
298 rescue ActiveRecord::RecordNotFound
299 render_404
299 render_404
300 end
300 end
301
301
302 # Find project of id params[:project_id]
302 # Find project of id params[:project_id]
303 def find_project_by_project_id
303 def find_project_by_project_id
304 @project = Project.find(params[:project_id])
304 @project = Project.find(params[:project_id])
305 rescue ActiveRecord::RecordNotFound
305 rescue ActiveRecord::RecordNotFound
306 render_404
306 render_404
307 end
307 end
308
308
309 # Find a project based on params[:project_id]
309 # Find a project based on params[:project_id]
310 # TODO: some subclasses override this, see about merging their logic
310 # TODO: some subclasses override this, see about merging their logic
311 def find_optional_project
311 def find_optional_project
312 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
312 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
313 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
313 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
314 allowed ? true : deny_access
314 allowed ? true : deny_access
315 rescue ActiveRecord::RecordNotFound
315 rescue ActiveRecord::RecordNotFound
316 render_404
316 render_404
317 end
317 end
318
318
319 # Finds and sets @project based on @object.project
319 # Finds and sets @project based on @object.project
320 def find_project_from_association
320 def find_project_from_association
321 render_404 unless @object.present?
321 render_404 unless @object.present?
322
322
323 @project = @object.project
323 @project = @object.project
324 end
324 end
325
325
326 def find_model_object
326 def find_model_object
327 model = self.class.model_object
327 model = self.class.model_object
328 if model
328 if model
329 @object = model.find(params[:id])
329 @object = model.find(params[:id])
330 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
330 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
331 end
331 end
332 rescue ActiveRecord::RecordNotFound
332 rescue ActiveRecord::RecordNotFound
333 render_404
333 render_404
334 end
334 end
335
335
336 def self.model_object(model)
336 def self.model_object(model)
337 self.model_object = model
337 self.model_object = model
338 end
338 end
339
339
340 # Find the issue whose id is the :id parameter
340 # Find the issue whose id is the :id parameter
341 # Raises a Unauthorized exception if the issue is not visible
341 # Raises a Unauthorized exception if the issue is not visible
342 def find_issue
342 def find_issue
343 # Issue.visible.find(...) can not be used to redirect user to the login form
343 # Issue.visible.find(...) can not be used to redirect user to the login form
344 # if the issue actually exists but requires authentication
344 # if the issue actually exists but requires authentication
345 @issue = Issue.find(params[:id])
345 @issue = Issue.find(params[:id])
346 raise Unauthorized unless @issue.visible?
346 raise Unauthorized unless @issue.visible?
347 @project = @issue.project
347 @project = @issue.project
348 rescue ActiveRecord::RecordNotFound
348 rescue ActiveRecord::RecordNotFound
349 render_404
349 render_404
350 end
350 end
351
351
352 # Find issues with a single :id param or :ids array param
352 # Find issues with a single :id param or :ids array param
353 # Raises a Unauthorized exception if one of the issues is not visible
353 # Raises a Unauthorized exception if one of the issues is not visible
354 def find_issues
354 def find_issues
355 @issues = Issue.where(:id => (params[:id] || params[:ids])).preload(:project, :status, :tracker, :priority, :author, :assigned_to, :relations_to).to_a
355 @issues = Issue.
356 where(:id => (params[:id] || params[:ids])).
357 preload(:project, :status, :tracker, :priority, :author, :assigned_to, :relations_to, {:custom_values => :custom_field}).
358 to_a
356 raise ActiveRecord::RecordNotFound if @issues.empty?
359 raise ActiveRecord::RecordNotFound if @issues.empty?
357 raise Unauthorized unless @issues.all?(&:visible?)
360 raise Unauthorized unless @issues.all?(&:visible?)
358 @projects = @issues.collect(&:project).compact.uniq
361 @projects = @issues.collect(&:project).compact.uniq
359 @project = @projects.first if @projects.size == 1
362 @project = @projects.first if @projects.size == 1
360 rescue ActiveRecord::RecordNotFound
363 rescue ActiveRecord::RecordNotFound
361 render_404
364 render_404
362 end
365 end
363
366
364 def find_attachments
367 def find_attachments
365 if (attachments = params[:attachments]).present?
368 if (attachments = params[:attachments]).present?
366 att = attachments.values.collect do |attachment|
369 att = attachments.values.collect do |attachment|
367 Attachment.find_by_token( attachment[:token] ) if attachment[:token].present?
370 Attachment.find_by_token( attachment[:token] ) if attachment[:token].present?
368 end
371 end
369 att.compact!
372 att.compact!
370 end
373 end
371 @attachments = att || []
374 @attachments = att || []
372 end
375 end
373
376
374 # make sure that the user is a member of the project (or admin) if project is private
377 # make sure that the user is a member of the project (or admin) if project is private
375 # used as a before_filter for actions that do not require any particular permission on the project
378 # used as a before_filter for actions that do not require any particular permission on the project
376 def check_project_privacy
379 def check_project_privacy
377 if @project && !@project.archived?
380 if @project && !@project.archived?
378 if @project.visible?
381 if @project.visible?
379 true
382 true
380 else
383 else
381 deny_access
384 deny_access
382 end
385 end
383 else
386 else
384 @project = nil
387 @project = nil
385 render_404
388 render_404
386 false
389 false
387 end
390 end
388 end
391 end
389
392
390 def back_url
393 def back_url
391 url = params[:back_url]
394 url = params[:back_url]
392 if url.nil? && referer = request.env['HTTP_REFERER']
395 if url.nil? && referer = request.env['HTTP_REFERER']
393 url = CGI.unescape(referer.to_s)
396 url = CGI.unescape(referer.to_s)
394 end
397 end
395 url
398 url
396 end
399 end
397
400
398 def redirect_back_or_default(default, options={})
401 def redirect_back_or_default(default, options={})
399 back_url = params[:back_url].to_s
402 back_url = params[:back_url].to_s
400 if back_url.present? && valid_url = validate_back_url(back_url)
403 if back_url.present? && valid_url = validate_back_url(back_url)
401 redirect_to(valid_url)
404 redirect_to(valid_url)
402 return
405 return
403 elsif options[:referer]
406 elsif options[:referer]
404 redirect_to_referer_or default
407 redirect_to_referer_or default
405 return
408 return
406 end
409 end
407 redirect_to default
410 redirect_to default
408 false
411 false
409 end
412 end
410
413
411 # Returns a validated URL string if back_url is a valid url for redirection,
414 # Returns a validated URL string if back_url is a valid url for redirection,
412 # otherwise false
415 # otherwise false
413 def validate_back_url(back_url)
416 def validate_back_url(back_url)
414 if CGI.unescape(back_url).include?('..')
417 if CGI.unescape(back_url).include?('..')
415 return false
418 return false
416 end
419 end
417
420
418 begin
421 begin
419 uri = URI.parse(back_url)
422 uri = URI.parse(back_url)
420 rescue URI::InvalidURIError
423 rescue URI::InvalidURIError
421 return false
424 return false
422 end
425 end
423
426
424 [:scheme, :host, :port].each do |component|
427 [:scheme, :host, :port].each do |component|
425 if uri.send(component).present? && uri.send(component) != request.send(component)
428 if uri.send(component).present? && uri.send(component) != request.send(component)
426 return false
429 return false
427 end
430 end
428 uri.send(:"#{component}=", nil)
431 uri.send(:"#{component}=", nil)
429 end
432 end
430 # Always ignore basic user:password in the URL
433 # Always ignore basic user:password in the URL
431 uri.userinfo = nil
434 uri.userinfo = nil
432
435
433 path = uri.to_s
436 path = uri.to_s
434 # Ensure that the remaining URL starts with a slash, followed by a
437 # Ensure that the remaining URL starts with a slash, followed by a
435 # non-slash character or the end
438 # non-slash character or the end
436 if path !~ %r{\A/([^/]|\z)}
439 if path !~ %r{\A/([^/]|\z)}
437 return false
440 return false
438 end
441 end
439
442
440 if path.match(%r{/(login|account/register)})
443 if path.match(%r{/(login|account/register)})
441 return false
444 return false
442 end
445 end
443
446
444 if relative_url_root.present? && !path.starts_with?(relative_url_root)
447 if relative_url_root.present? && !path.starts_with?(relative_url_root)
445 return false
448 return false
446 end
449 end
447
450
448 return path
451 return path
449 end
452 end
450 private :validate_back_url
453 private :validate_back_url
451
454
452 def valid_back_url?(back_url)
455 def valid_back_url?(back_url)
453 !!validate_back_url(back_url)
456 !!validate_back_url(back_url)
454 end
457 end
455 private :valid_back_url?
458 private :valid_back_url?
456
459
457 # Redirects to the request referer if present, redirects to args or call block otherwise.
460 # Redirects to the request referer if present, redirects to args or call block otherwise.
458 def redirect_to_referer_or(*args, &block)
461 def redirect_to_referer_or(*args, &block)
459 redirect_to :back
462 redirect_to :back
460 rescue ::ActionController::RedirectBackError
463 rescue ::ActionController::RedirectBackError
461 if args.any?
464 if args.any?
462 redirect_to *args
465 redirect_to *args
463 elsif block_given?
466 elsif block_given?
464 block.call
467 block.call
465 else
468 else
466 raise "#redirect_to_referer_or takes arguments or a block"
469 raise "#redirect_to_referer_or takes arguments or a block"
467 end
470 end
468 end
471 end
469
472
470 def render_403(options={})
473 def render_403(options={})
471 @project = nil
474 @project = nil
472 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
475 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
473 return false
476 return false
474 end
477 end
475
478
476 def render_404(options={})
479 def render_404(options={})
477 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
480 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
478 return false
481 return false
479 end
482 end
480
483
481 # Renders an error response
484 # Renders an error response
482 def render_error(arg)
485 def render_error(arg)
483 arg = {:message => arg} unless arg.is_a?(Hash)
486 arg = {:message => arg} unless arg.is_a?(Hash)
484
487
485 @message = arg[:message]
488 @message = arg[:message]
486 @message = l(@message) if @message.is_a?(Symbol)
489 @message = l(@message) if @message.is_a?(Symbol)
487 @status = arg[:status] || 500
490 @status = arg[:status] || 500
488
491
489 respond_to do |format|
492 respond_to do |format|
490 format.html {
493 format.html {
491 render :template => 'common/error', :layout => use_layout, :status => @status
494 render :template => 'common/error', :layout => use_layout, :status => @status
492 }
495 }
493 format.any { head @status }
496 format.any { head @status }
494 end
497 end
495 end
498 end
496
499
497 # Handler for ActionView::MissingTemplate exception
500 # Handler for ActionView::MissingTemplate exception
498 def missing_template
501 def missing_template
499 logger.warn "Missing template, responding with 404"
502 logger.warn "Missing template, responding with 404"
500 @project = nil
503 @project = nil
501 render_404
504 render_404
502 end
505 end
503
506
504 # Filter for actions that provide an API response
507 # Filter for actions that provide an API response
505 # but have no HTML representation for non admin users
508 # but have no HTML representation for non admin users
506 def require_admin_or_api_request
509 def require_admin_or_api_request
507 return true if api_request?
510 return true if api_request?
508 if User.current.admin?
511 if User.current.admin?
509 true
512 true
510 elsif User.current.logged?
513 elsif User.current.logged?
511 render_error(:status => 406)
514 render_error(:status => 406)
512 else
515 else
513 deny_access
516 deny_access
514 end
517 end
515 end
518 end
516
519
517 # Picks which layout to use based on the request
520 # Picks which layout to use based on the request
518 #
521 #
519 # @return [boolean, string] name of the layout to use or false for no layout
522 # @return [boolean, string] name of the layout to use or false for no layout
520 def use_layout
523 def use_layout
521 request.xhr? ? false : 'base'
524 request.xhr? ? false : 'base'
522 end
525 end
523
526
524 def render_feed(items, options={})
527 def render_feed(items, options={})
525 @items = (items || []).to_a
528 @items = (items || []).to_a
526 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
529 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
527 @items = @items.slice(0, Setting.feeds_limit.to_i)
530 @items = @items.slice(0, Setting.feeds_limit.to_i)
528 @title = options[:title] || Setting.app_title
531 @title = options[:title] || Setting.app_title
529 render :template => "common/feed", :formats => [:atom], :layout => false,
532 render :template => "common/feed", :formats => [:atom], :layout => false,
530 :content_type => 'application/atom+xml'
533 :content_type => 'application/atom+xml'
531 end
534 end
532
535
533 def self.accept_rss_auth(*actions)
536 def self.accept_rss_auth(*actions)
534 if actions.any?
537 if actions.any?
535 self.accept_rss_auth_actions = actions
538 self.accept_rss_auth_actions = actions
536 else
539 else
537 self.accept_rss_auth_actions || []
540 self.accept_rss_auth_actions || []
538 end
541 end
539 end
542 end
540
543
541 def accept_rss_auth?(action=action_name)
544 def accept_rss_auth?(action=action_name)
542 self.class.accept_rss_auth.include?(action.to_sym)
545 self.class.accept_rss_auth.include?(action.to_sym)
543 end
546 end
544
547
545 def self.accept_api_auth(*actions)
548 def self.accept_api_auth(*actions)
546 if actions.any?
549 if actions.any?
547 self.accept_api_auth_actions = actions
550 self.accept_api_auth_actions = actions
548 else
551 else
549 self.accept_api_auth_actions || []
552 self.accept_api_auth_actions || []
550 end
553 end
551 end
554 end
552
555
553 def accept_api_auth?(action=action_name)
556 def accept_api_auth?(action=action_name)
554 self.class.accept_api_auth.include?(action.to_sym)
557 self.class.accept_api_auth.include?(action.to_sym)
555 end
558 end
556
559
557 # Returns the number of objects that should be displayed
560 # Returns the number of objects that should be displayed
558 # on the paginated list
561 # on the paginated list
559 def per_page_option
562 def per_page_option
560 per_page = nil
563 per_page = nil
561 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
564 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
562 per_page = params[:per_page].to_s.to_i
565 per_page = params[:per_page].to_s.to_i
563 session[:per_page] = per_page
566 session[:per_page] = per_page
564 elsif session[:per_page]
567 elsif session[:per_page]
565 per_page = session[:per_page]
568 per_page = session[:per_page]
566 else
569 else
567 per_page = Setting.per_page_options_array.first || 25
570 per_page = Setting.per_page_options_array.first || 25
568 end
571 end
569 per_page
572 per_page
570 end
573 end
571
574
572 # Returns offset and limit used to retrieve objects
575 # Returns offset and limit used to retrieve objects
573 # for an API response based on offset, limit and page parameters
576 # for an API response based on offset, limit and page parameters
574 def api_offset_and_limit(options=params)
577 def api_offset_and_limit(options=params)
575 if options[:offset].present?
578 if options[:offset].present?
576 offset = options[:offset].to_i
579 offset = options[:offset].to_i
577 if offset < 0
580 if offset < 0
578 offset = 0
581 offset = 0
579 end
582 end
580 end
583 end
581 limit = options[:limit].to_i
584 limit = options[:limit].to_i
582 if limit < 1
585 if limit < 1
583 limit = 25
586 limit = 25
584 elsif limit > 100
587 elsif limit > 100
585 limit = 100
588 limit = 100
586 end
589 end
587 if offset.nil? && options[:page].present?
590 if offset.nil? && options[:page].present?
588 offset = (options[:page].to_i - 1) * limit
591 offset = (options[:page].to_i - 1) * limit
589 offset = 0 if offset < 0
592 offset = 0 if offset < 0
590 end
593 end
591 offset ||= 0
594 offset ||= 0
592
595
593 [offset, limit]
596 [offset, limit]
594 end
597 end
595
598
596 # qvalues http header parser
599 # qvalues http header parser
597 # code taken from webrick
600 # code taken from webrick
598 def parse_qvalues(value)
601 def parse_qvalues(value)
599 tmp = []
602 tmp = []
600 if value
603 if value
601 parts = value.split(/,\s*/)
604 parts = value.split(/,\s*/)
602 parts.each {|part|
605 parts.each {|part|
603 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
606 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
604 val = m[1]
607 val = m[1]
605 q = (m[2] or 1).to_f
608 q = (m[2] or 1).to_f
606 tmp.push([val, q])
609 tmp.push([val, q])
607 end
610 end
608 }
611 }
609 tmp = tmp.sort_by{|val, q| -q}
612 tmp = tmp.sort_by{|val, q| -q}
610 tmp.collect!{|val, q| val}
613 tmp.collect!{|val, q| val}
611 end
614 end
612 return tmp
615 return tmp
613 rescue
616 rescue
614 nil
617 nil
615 end
618 end
616
619
617 # Returns a string that can be used as filename value in Content-Disposition header
620 # Returns a string that can be used as filename value in Content-Disposition header
618 def filename_for_content_disposition(name)
621 def filename_for_content_disposition(name)
619 request.env['HTTP_USER_AGENT'] =~ %r{(MSIE|Trident)} ? ERB::Util.url_encode(name) : name
622 request.env['HTTP_USER_AGENT'] =~ %r{(MSIE|Trident)} ? ERB::Util.url_encode(name) : name
620 end
623 end
621
624
622 def api_request?
625 def api_request?
623 %w(xml json).include? params[:format]
626 %w(xml json).include? params[:format]
624 end
627 end
625
628
626 # Returns the API key present in the request
629 # Returns the API key present in the request
627 def api_key_from_request
630 def api_key_from_request
628 if params[:key].present?
631 if params[:key].present?
629 params[:key].to_s
632 params[:key].to_s
630 elsif request.headers["X-Redmine-API-Key"].present?
633 elsif request.headers["X-Redmine-API-Key"].present?
631 request.headers["X-Redmine-API-Key"].to_s
634 request.headers["X-Redmine-API-Key"].to_s
632 end
635 end
633 end
636 end
634
637
635 # Returns the API 'switch user' value if present
638 # Returns the API 'switch user' value if present
636 def api_switch_user_from_request
639 def api_switch_user_from_request
637 request.headers["X-Redmine-Switch-User"].to_s.presence
640 request.headers["X-Redmine-Switch-User"].to_s.presence
638 end
641 end
639
642
640 # Renders a warning flash if obj has unsaved attachments
643 # Renders a warning flash if obj has unsaved attachments
641 def render_attachment_warning_if_needed(obj)
644 def render_attachment_warning_if_needed(obj)
642 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
645 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
643 end
646 end
644
647
645 # Rescues an invalid query statement. Just in case...
648 # Rescues an invalid query statement. Just in case...
646 def query_statement_invalid(exception)
649 def query_statement_invalid(exception)
647 logger.error "Query::StatementInvalid: #{exception.message}" if logger
650 logger.error "Query::StatementInvalid: #{exception.message}" if logger
648 session.delete(:query)
651 session.delete(:query)
649 sort_clear if respond_to?(:sort_clear)
652 sort_clear if respond_to?(:sort_clear)
650 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
653 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
651 end
654 end
652
655
653 # Renders a 200 response for successfull updates or deletions via the API
656 # Renders a 200 response for successfull updates or deletions via the API
654 def render_api_ok
657 def render_api_ok
655 render_api_head :ok
658 render_api_head :ok
656 end
659 end
657
660
658 # Renders a head API response
661 # Renders a head API response
659 def render_api_head(status)
662 def render_api_head(status)
660 # #head would return a response body with one space
663 # #head would return a response body with one space
661 render :text => '', :status => status, :layout => nil
664 render :text => '', :status => status, :layout => nil
662 end
665 end
663
666
664 # Renders API response on validation failure
667 # Renders API response on validation failure
665 # for an object or an array of objects
668 # for an object or an array of objects
666 def render_validation_errors(objects)
669 def render_validation_errors(objects)
667 messages = Array.wrap(objects).map {|object| object.errors.full_messages}.flatten
670 messages = Array.wrap(objects).map {|object| object.errors.full_messages}.flatten
668 render_api_errors(messages)
671 render_api_errors(messages)
669 end
672 end
670
673
671 def render_api_errors(*messages)
674 def render_api_errors(*messages)
672 @error_messages = messages.flatten
675 @error_messages = messages.flatten
673 render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
676 render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
674 end
677 end
675
678
676 # Overrides #_include_layout? so that #render with no arguments
679 # Overrides #_include_layout? so that #render with no arguments
677 # doesn't use the layout for api requests
680 # doesn't use the layout for api requests
678 def _include_layout?(*args)
681 def _include_layout?(*args)
679 api_request? ? false : super
682 api_request? ? false : super
680 end
683 end
681 end
684 end
General Comments 0
You need to be logged in to leave comments. Login now