##// END OF EJS Templates
Log current user on each request....
Jean-Philippe Lang -
r10156:3b5fd45faecb
parent child
Show More
@@ -1,559 +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 end
86 end
86
87
87 # 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
88 # and starts a session if needed
89 # and starts a session if needed
89 def find_current_user
90 def find_current_user
90 user = nil
91 user = nil
91 unless api_request?
92 unless api_request?
92 if session[:user_id]
93 if session[:user_id]
93 # existing session
94 # existing session
94 user = (User.active.find(session[:user_id]) rescue nil)
95 user = (User.active.find(session[:user_id]) rescue nil)
95 elsif autologin_user = try_to_autologin
96 elsif autologin_user = try_to_autologin
96 user = autologin_user
97 user = autologin_user
97 elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
98 elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
98 # RSS key authentication does not start a session
99 # RSS key authentication does not start a session
99 user = User.find_by_rss_key(params[:key])
100 user = User.find_by_rss_key(params[:key])
100 end
101 end
101 end
102 end
102 if user.nil? && Setting.rest_api_enabled? && accept_api_auth?
103 if user.nil? && Setting.rest_api_enabled? && accept_api_auth?
103 if (key = api_key_from_request)
104 if (key = api_key_from_request)
104 # Use API key
105 # Use API key
105 user = User.find_by_api_key(key)
106 user = User.find_by_api_key(key)
106 else
107 else
107 # HTTP Basic, either username/password or API key/random
108 # HTTP Basic, either username/password or API key/random
108 authenticate_with_http_basic do |username, password|
109 authenticate_with_http_basic do |username, password|
109 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)
110 end
111 end
111 end
112 end
112 end
113 end
113 user
114 user
114 end
115 end
115
116
116 def try_to_autologin
117 def try_to_autologin
117 if cookies[:autologin] && Setting.autologin?
118 if cookies[:autologin] && Setting.autologin?
118 # auto-login feature starts a new session
119 # auto-login feature starts a new session
119 user = User.try_to_autologin(cookies[:autologin])
120 user = User.try_to_autologin(cookies[:autologin])
120 if user
121 if user
121 reset_session
122 reset_session
122 start_user_session(user)
123 start_user_session(user)
123 end
124 end
124 user
125 user
125 end
126 end
126 end
127 end
127
128
128 # Sets the logged in user
129 # Sets the logged in user
129 def logged_user=(user)
130 def logged_user=(user)
130 reset_session
131 reset_session
131 if user && user.is_a?(User)
132 if user && user.is_a?(User)
132 User.current = user
133 User.current = user
133 start_user_session(user)
134 start_user_session(user)
134 else
135 else
135 User.current = User.anonymous
136 User.current = User.anonymous
136 end
137 end
137 end
138 end
138
139
139 # Logs out current user
140 # Logs out current user
140 def logout_user
141 def logout_user
141 if User.current.logged?
142 if User.current.logged?
142 cookies.delete :autologin
143 cookies.delete :autologin
143 Token.delete_all(["user_id = ? AND action = ?", User.current.id, 'autologin'])
144 Token.delete_all(["user_id = ? AND action = ?", User.current.id, 'autologin'])
144 self.logged_user = nil
145 self.logged_user = nil
145 end
146 end
146 end
147 end
147
148
148 # check if login is globally required to access the application
149 # check if login is globally required to access the application
149 def check_if_login_required
150 def check_if_login_required
150 # no check needed if user is already logged in
151 # no check needed if user is already logged in
151 return true if User.current.logged?
152 return true if User.current.logged?
152 require_login if Setting.login_required?
153 require_login if Setting.login_required?
153 end
154 end
154
155
155 def set_localization
156 def set_localization
156 lang = nil
157 lang = nil
157 if User.current.logged?
158 if User.current.logged?
158 lang = find_language(User.current.language)
159 lang = find_language(User.current.language)
159 end
160 end
160 if lang.nil? && request.env['HTTP_ACCEPT_LANGUAGE']
161 if lang.nil? && request.env['HTTP_ACCEPT_LANGUAGE']
161 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
162 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
162 if !accept_lang.blank?
163 if !accept_lang.blank?
163 accept_lang = accept_lang.downcase
164 accept_lang = accept_lang.downcase
164 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
165 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
165 end
166 end
166 end
167 end
167 lang ||= Setting.default_language
168 lang ||= Setting.default_language
168 set_language_if_valid(lang)
169 set_language_if_valid(lang)
169 end
170 end
170
171
171 def require_login
172 def require_login
172 if !User.current.logged?
173 if !User.current.logged?
173 # Extract only the basic url parameters on non-GET requests
174 # Extract only the basic url parameters on non-GET requests
174 if request.get?
175 if request.get?
175 url = url_for(params)
176 url = url_for(params)
176 else
177 else
177 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])
178 end
179 end
179 respond_to do |format|
180 respond_to do |format|
180 format.html { redirect_to :controller => "account", :action => "login", :back_url => url }
181 format.html { redirect_to :controller => "account", :action => "login", :back_url => url }
181 format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
182 format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
182 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
183 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
183 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
184 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
184 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
185 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
185 end
186 end
186 return false
187 return false
187 end
188 end
188 true
189 true
189 end
190 end
190
191
191 def require_admin
192 def require_admin
192 return unless require_login
193 return unless require_login
193 if !User.current.admin?
194 if !User.current.admin?
194 render_403
195 render_403
195 return false
196 return false
196 end
197 end
197 true
198 true
198 end
199 end
199
200
200 def deny_access
201 def deny_access
201 User.current.logged? ? render_403 : require_login
202 User.current.logged? ? render_403 : require_login
202 end
203 end
203
204
204 # Authorize the user for the requested action
205 # Authorize the user for the requested action
205 def authorize(ctrl = params[:controller], action = params[:action], global = false)
206 def authorize(ctrl = params[:controller], action = params[:action], global = false)
206 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)
207 if allowed
208 if allowed
208 true
209 true
209 else
210 else
210 if @project && @project.archived?
211 if @project && @project.archived?
211 render_403 :message => :notice_not_authorized_archived_project
212 render_403 :message => :notice_not_authorized_archived_project
212 else
213 else
213 deny_access
214 deny_access
214 end
215 end
215 end
216 end
216 end
217 end
217
218
218 # Authorize the user for the requested action outside a project
219 # Authorize the user for the requested action outside a project
219 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
220 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
220 authorize(ctrl, action, global)
221 authorize(ctrl, action, global)
221 end
222 end
222
223
223 # Find project of id params[:id]
224 # Find project of id params[:id]
224 def find_project
225 def find_project
225 @project = Project.find(params[:id])
226 @project = Project.find(params[:id])
226 rescue ActiveRecord::RecordNotFound
227 rescue ActiveRecord::RecordNotFound
227 render_404
228 render_404
228 end
229 end
229
230
230 # Find project of id params[:project_id]
231 # Find project of id params[:project_id]
231 def find_project_by_project_id
232 def find_project_by_project_id
232 @project = Project.find(params[:project_id])
233 @project = Project.find(params[:project_id])
233 rescue ActiveRecord::RecordNotFound
234 rescue ActiveRecord::RecordNotFound
234 render_404
235 render_404
235 end
236 end
236
237
237 # Find a project based on params[:project_id]
238 # Find a project based on params[:project_id]
238 # TODO: some subclasses override this, see about merging their logic
239 # TODO: some subclasses override this, see about merging their logic
239 def find_optional_project
240 def find_optional_project
240 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
241 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
241 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)
242 allowed ? true : deny_access
243 allowed ? true : deny_access
243 rescue ActiveRecord::RecordNotFound
244 rescue ActiveRecord::RecordNotFound
244 render_404
245 render_404
245 end
246 end
246
247
247 # Finds and sets @project based on @object.project
248 # Finds and sets @project based on @object.project
248 def find_project_from_association
249 def find_project_from_association
249 render_404 unless @object.present?
250 render_404 unless @object.present?
250
251
251 @project = @object.project
252 @project = @object.project
252 end
253 end
253
254
254 def find_model_object
255 def find_model_object
255 model = self.class.model_object
256 model = self.class.model_object
256 if model
257 if model
257 @object = model.find(params[:id])
258 @object = model.find(params[:id])
258 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
259 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
259 end
260 end
260 rescue ActiveRecord::RecordNotFound
261 rescue ActiveRecord::RecordNotFound
261 render_404
262 render_404
262 end
263 end
263
264
264 def self.model_object(model)
265 def self.model_object(model)
265 self.model_object = model
266 self.model_object = model
266 end
267 end
267
268
268 # Filter for bulk issue operations
269 # Filter for bulk issue operations
269 def find_issues
270 def find_issues
270 @issues = Issue.find_all_by_id(params[:id] || params[:ids])
271 @issues = Issue.find_all_by_id(params[:id] || params[:ids])
271 raise ActiveRecord::RecordNotFound if @issues.empty?
272 raise ActiveRecord::RecordNotFound if @issues.empty?
272 if @issues.detect {|issue| !issue.visible?}
273 if @issues.detect {|issue| !issue.visible?}
273 deny_access
274 deny_access
274 return
275 return
275 end
276 end
276 @projects = @issues.collect(&:project).compact.uniq
277 @projects = @issues.collect(&:project).compact.uniq
277 @project = @projects.first if @projects.size == 1
278 @project = @projects.first if @projects.size == 1
278 rescue ActiveRecord::RecordNotFound
279 rescue ActiveRecord::RecordNotFound
279 render_404
280 render_404
280 end
281 end
281
282
282 # 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
283 # 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
284 def check_project_privacy
285 def check_project_privacy
285 if @project && !@project.archived?
286 if @project && !@project.archived?
286 if @project.visible?
287 if @project.visible?
287 true
288 true
288 else
289 else
289 deny_access
290 deny_access
290 end
291 end
291 else
292 else
292 @project = nil
293 @project = nil
293 render_404
294 render_404
294 false
295 false
295 end
296 end
296 end
297 end
297
298
298 def back_url
299 def back_url
299 url = params[:back_url]
300 url = params[:back_url]
300 if url.nil? && referer = request.env['HTTP_REFERER']
301 if url.nil? && referer = request.env['HTTP_REFERER']
301 url = CGI.unescape(referer.to_s)
302 url = CGI.unescape(referer.to_s)
302 end
303 end
303 url
304 url
304 end
305 end
305
306
306 def redirect_back_or_default(default)
307 def redirect_back_or_default(default)
307 back_url = params[:back_url].to_s
308 back_url = params[:back_url].to_s
308 if back_url.present?
309 if back_url.present?
309 begin
310 begin
310 uri = URI.parse(back_url)
311 uri = URI.parse(back_url)
311 # 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
312 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)})
313 redirect_to(back_url)
314 redirect_to(back_url)
314 return
315 return
315 end
316 end
316 rescue URI::InvalidURIError
317 rescue URI::InvalidURIError
317 logger.warn("Could not redirect to invalid URL #{back_url}")
318 logger.warn("Could not redirect to invalid URL #{back_url}")
318 # redirect to default
319 # redirect to default
319 end
320 end
320 end
321 end
321 redirect_to default
322 redirect_to default
322 false
323 false
323 end
324 end
324
325
325 # 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.
326 def redirect_to_referer_or(*args, &block)
327 def redirect_to_referer_or(*args, &block)
327 redirect_to :back
328 redirect_to :back
328 rescue ::ActionController::RedirectBackError
329 rescue ::ActionController::RedirectBackError
329 if args.any?
330 if args.any?
330 redirect_to *args
331 redirect_to *args
331 elsif block_given?
332 elsif block_given?
332 block.call
333 block.call
333 else
334 else
334 raise "#redirect_to_referer_or takes arguments or a block"
335 raise "#redirect_to_referer_or takes arguments or a block"
335 end
336 end
336 end
337 end
337
338
338 def render_403(options={})
339 def render_403(options={})
339 @project = nil
340 @project = nil
340 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
341 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
341 return false
342 return false
342 end
343 end
343
344
344 def render_404(options={})
345 def render_404(options={})
345 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
346 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
346 return false
347 return false
347 end
348 end
348
349
349 # Renders an error response
350 # Renders an error response
350 def render_error(arg)
351 def render_error(arg)
351 arg = {:message => arg} unless arg.is_a?(Hash)
352 arg = {:message => arg} unless arg.is_a?(Hash)
352
353
353 @message = arg[:message]
354 @message = arg[:message]
354 @message = l(@message) if @message.is_a?(Symbol)
355 @message = l(@message) if @message.is_a?(Symbol)
355 @status = arg[:status] || 500
356 @status = arg[:status] || 500
356
357
357 respond_to do |format|
358 respond_to do |format|
358 format.html {
359 format.html {
359 render :template => 'common/error', :layout => use_layout, :status => @status
360 render :template => 'common/error', :layout => use_layout, :status => @status
360 }
361 }
361 format.any { head @status }
362 format.any { head @status }
362 end
363 end
363 end
364 end
364
365
365 # Handler for ActionView::MissingTemplate exception
366 # Handler for ActionView::MissingTemplate exception
366 def missing_template
367 def missing_template
367 logger.warn "Missing template, responding with 404"
368 logger.warn "Missing template, responding with 404"
368 @project = nil
369 @project = nil
369 render_404
370 render_404
370 end
371 end
371
372
372 # Filter for actions that provide an API response
373 # Filter for actions that provide an API response
373 # but have no HTML representation for non admin users
374 # but have no HTML representation for non admin users
374 def require_admin_or_api_request
375 def require_admin_or_api_request
375 return true if api_request?
376 return true if api_request?
376 if User.current.admin?
377 if User.current.admin?
377 true
378 true
378 elsif User.current.logged?
379 elsif User.current.logged?
379 render_error(:status => 406)
380 render_error(:status => 406)
380 else
381 else
381 deny_access
382 deny_access
382 end
383 end
383 end
384 end
384
385
385 # Picks which layout to use based on the request
386 # Picks which layout to use based on the request
386 #
387 #
387 # @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
388 def use_layout
389 def use_layout
389 request.xhr? ? false : 'base'
390 request.xhr? ? false : 'base'
390 end
391 end
391
392
392 def invalid_authenticity_token
393 def invalid_authenticity_token
393 if api_request?
394 if api_request?
394 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)."
395 end
396 end
396 render_error "Invalid form authenticity token."
397 render_error "Invalid form authenticity token."
397 end
398 end
398
399
399 def render_feed(items, options={})
400 def render_feed(items, options={})
400 @items = items || []
401 @items = items || []
401 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
402 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
402 @items = @items.slice(0, Setting.feeds_limit.to_i)
403 @items = @items.slice(0, Setting.feeds_limit.to_i)
403 @title = options[:title] || Setting.app_title
404 @title = options[:title] || Setting.app_title
404 render :template => "common/feed.atom", :layout => false,
405 render :template => "common/feed.atom", :layout => false,
405 :content_type => 'application/atom+xml'
406 :content_type => 'application/atom+xml'
406 end
407 end
407
408
408 def self.accept_rss_auth(*actions)
409 def self.accept_rss_auth(*actions)
409 if actions.any?
410 if actions.any?
410 self.accept_rss_auth_actions = actions
411 self.accept_rss_auth_actions = actions
411 else
412 else
412 self.accept_rss_auth_actions || []
413 self.accept_rss_auth_actions || []
413 end
414 end
414 end
415 end
415
416
416 def accept_rss_auth?(action=action_name)
417 def accept_rss_auth?(action=action_name)
417 self.class.accept_rss_auth.include?(action.to_sym)
418 self.class.accept_rss_auth.include?(action.to_sym)
418 end
419 end
419
420
420 def self.accept_api_auth(*actions)
421 def self.accept_api_auth(*actions)
421 if actions.any?
422 if actions.any?
422 self.accept_api_auth_actions = actions
423 self.accept_api_auth_actions = actions
423 else
424 else
424 self.accept_api_auth_actions || []
425 self.accept_api_auth_actions || []
425 end
426 end
426 end
427 end
427
428
428 def accept_api_auth?(action=action_name)
429 def accept_api_auth?(action=action_name)
429 self.class.accept_api_auth.include?(action.to_sym)
430 self.class.accept_api_auth.include?(action.to_sym)
430 end
431 end
431
432
432 # Returns the number of objects that should be displayed
433 # Returns the number of objects that should be displayed
433 # on the paginated list
434 # on the paginated list
434 def per_page_option
435 def per_page_option
435 per_page = nil
436 per_page = nil
436 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)
437 per_page = params[:per_page].to_s.to_i
438 per_page = params[:per_page].to_s.to_i
438 session[:per_page] = per_page
439 session[:per_page] = per_page
439 elsif session[:per_page]
440 elsif session[:per_page]
440 per_page = session[:per_page]
441 per_page = session[:per_page]
441 else
442 else
442 per_page = Setting.per_page_options_array.first || 25
443 per_page = Setting.per_page_options_array.first || 25
443 end
444 end
444 per_page
445 per_page
445 end
446 end
446
447
447 # Returns offset and limit used to retrieve objects
448 # Returns offset and limit used to retrieve objects
448 # for an API response based on offset, limit and page parameters
449 # for an API response based on offset, limit and page parameters
449 def api_offset_and_limit(options=params)
450 def api_offset_and_limit(options=params)
450 if options[:offset].present?
451 if options[:offset].present?
451 offset = options[:offset].to_i
452 offset = options[:offset].to_i
452 if offset < 0
453 if offset < 0
453 offset = 0
454 offset = 0
454 end
455 end
455 end
456 end
456 limit = options[:limit].to_i
457 limit = options[:limit].to_i
457 if limit < 1
458 if limit < 1
458 limit = 25
459 limit = 25
459 elsif limit > 100
460 elsif limit > 100
460 limit = 100
461 limit = 100
461 end
462 end
462 if offset.nil? && options[:page].present?
463 if offset.nil? && options[:page].present?
463 offset = (options[:page].to_i - 1) * limit
464 offset = (options[:page].to_i - 1) * limit
464 offset = 0 if offset < 0
465 offset = 0 if offset < 0
465 end
466 end
466 offset ||= 0
467 offset ||= 0
467
468
468 [offset, limit]
469 [offset, limit]
469 end
470 end
470
471
471 # qvalues http header parser
472 # qvalues http header parser
472 # code taken from webrick
473 # code taken from webrick
473 def parse_qvalues(value)
474 def parse_qvalues(value)
474 tmp = []
475 tmp = []
475 if value
476 if value
476 parts = value.split(/,\s*/)
477 parts = value.split(/,\s*/)
477 parts.each {|part|
478 parts.each {|part|
478 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
479 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
479 val = m[1]
480 val = m[1]
480 q = (m[2] or 1).to_f
481 q = (m[2] or 1).to_f
481 tmp.push([val, q])
482 tmp.push([val, q])
482 end
483 end
483 }
484 }
484 tmp = tmp.sort_by{|val, q| -q}
485 tmp = tmp.sort_by{|val, q| -q}
485 tmp.collect!{|val, q| val}
486 tmp.collect!{|val, q| val}
486 end
487 end
487 return tmp
488 return tmp
488 rescue
489 rescue
489 nil
490 nil
490 end
491 end
491
492
492 # 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
493 def filename_for_content_disposition(name)
494 def filename_for_content_disposition(name)
494 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
495 end
496 end
496
497
497 def api_request?
498 def api_request?
498 %w(xml json).include? params[:format]
499 %w(xml json).include? params[:format]
499 end
500 end
500
501
501 # Returns the API key present in the request
502 # Returns the API key present in the request
502 def api_key_from_request
503 def api_key_from_request
503 if params[:key].present?
504 if params[:key].present?
504 params[:key].to_s
505 params[:key].to_s
505 elsif request.headers["X-Redmine-API-Key"].present?
506 elsif request.headers["X-Redmine-API-Key"].present?
506 request.headers["X-Redmine-API-Key"].to_s
507 request.headers["X-Redmine-API-Key"].to_s
507 end
508 end
508 end
509 end
509
510
510 # Renders a warning flash if obj has unsaved attachments
511 # Renders a warning flash if obj has unsaved attachments
511 def render_attachment_warning_if_needed(obj)
512 def render_attachment_warning_if_needed(obj)
512 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?
513 end
514 end
514
515
515 # 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
516 #
517 #
517 # @param [Array, Issue] issues all of the saved and unsaved Issues
518 # @param [Array, Issue] issues all of the saved and unsaved Issues
518 # @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
519 def set_flash_from_bulk_issue_save(issues, unsaved_issue_ids)
520 def set_flash_from_bulk_issue_save(issues, unsaved_issue_ids)
520 if unsaved_issue_ids.empty?
521 if unsaved_issue_ids.empty?
521 flash[:notice] = l(:notice_successful_update) unless issues.empty?
522 flash[:notice] = l(:notice_successful_update) unless issues.empty?
522 else
523 else
523 flash[:error] = l(:notice_failed_to_save_issues,
524 flash[:error] = l(:notice_failed_to_save_issues,
524 :count => unsaved_issue_ids.size,
525 :count => unsaved_issue_ids.size,
525 :total => issues.size,
526 :total => issues.size,
526 :ids => '#' + unsaved_issue_ids.join(', #'))
527 :ids => '#' + unsaved_issue_ids.join(', #'))
527 end
528 end
528 end
529 end
529
530
530 # Rescues an invalid query statement. Just in case...
531 # Rescues an invalid query statement. Just in case...
531 def query_statement_invalid(exception)
532 def query_statement_invalid(exception)
532 logger.error "Query::StatementInvalid: #{exception.message}" if logger
533 logger.error "Query::StatementInvalid: #{exception.message}" if logger
533 session.delete(:query)
534 session.delete(:query)
534 sort_clear if respond_to?(:sort_clear)
535 sort_clear if respond_to?(:sort_clear)
535 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."
536 end
537 end
537
538
538 # 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
539 def render_api_ok
540 def render_api_ok
540 # head :ok would return a response body with one space
541 # head :ok would return a response body with one space
541 render :text => '', :status => :ok, :layout => nil
542 render :text => '', :status => :ok, :layout => nil
542 end
543 end
543
544
544 # Renders API response on validation failure
545 # Renders API response on validation failure
545 def render_validation_errors(objects)
546 def render_validation_errors(objects)
546 if objects.is_a?(Array)
547 if objects.is_a?(Array)
547 @error_messages = objects.map {|object| object.errors.full_messages}.flatten
548 @error_messages = objects.map {|object| object.errors.full_messages}.flatten
548 else
549 else
549 @error_messages = objects.errors.full_messages
550 @error_messages = objects.errors.full_messages
550 end
551 end
551 render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
552 render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
552 end
553 end
553
554
554 # Overrides #_include_layout? so that #render with no arguments
555 # Overrides #_include_layout? so that #render with no arguments
555 # doesn't use the layout for api requests
556 # doesn't use the layout for api requests
556 def _include_layout?(*args)
557 def _include_layout?(*args)
557 api_request? ? false : super
558 api_request? ? false : super
558 end
559 end
559 end
560 end
General Comments 0
You need to be logged in to leave comments. Login now