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