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