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