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