##// END OF EJS Templates
Fixed that autologin is broken when using a custom cookie name (#13335)....
Jean-Philippe Lang -
r11289:08ef201cec0c
parent child
Show More
@@ -1,303 +1,302
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2013 Jean-Philippe Lang
2 # Copyright (C) 2006-2013 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 class AccountController < ApplicationController
18 class AccountController < ApplicationController
19 helper :custom_fields
19 helper :custom_fields
20 include CustomFieldsHelper
20 include CustomFieldsHelper
21
21
22 # prevents login action to be filtered by check_if_login_required application scope filter
22 # prevents login action to be filtered by check_if_login_required application scope filter
23 skip_before_filter :check_if_login_required
23 skip_before_filter :check_if_login_required
24
24
25 # Login request and validation
25 # Login request and validation
26 def login
26 def login
27 if request.get?
27 if request.get?
28 if User.current.logged?
28 if User.current.logged?
29 redirect_to home_url
29 redirect_to home_url
30 end
30 end
31 else
31 else
32 authenticate_user
32 authenticate_user
33 end
33 end
34 rescue AuthSourceException => e
34 rescue AuthSourceException => e
35 logger.error "An error occured when authenticating #{params[:username]}: #{e.message}"
35 logger.error "An error occured when authenticating #{params[:username]}: #{e.message}"
36 render_error :message => e.message
36 render_error :message => e.message
37 end
37 end
38
38
39 # Log out current user and redirect to welcome page
39 # Log out current user and redirect to welcome page
40 def logout
40 def logout
41 if User.current.anonymous?
41 if User.current.anonymous?
42 redirect_to home_url
42 redirect_to home_url
43 elsif request.post?
43 elsif request.post?
44 logout_user
44 logout_user
45 redirect_to home_url
45 redirect_to home_url
46 end
46 end
47 # display the logout form
47 # display the logout form
48 end
48 end
49
49
50 # Lets user choose a new password
50 # Lets user choose a new password
51 def lost_password
51 def lost_password
52 (redirect_to(home_url); return) unless Setting.lost_password?
52 (redirect_to(home_url); return) unless Setting.lost_password?
53 if params[:token]
53 if params[:token]
54 @token = Token.find_token("recovery", params[:token].to_s)
54 @token = Token.find_token("recovery", params[:token].to_s)
55 if @token.nil? || @token.expired?
55 if @token.nil? || @token.expired?
56 redirect_to home_url
56 redirect_to home_url
57 return
57 return
58 end
58 end
59 @user = @token.user
59 @user = @token.user
60 unless @user && @user.active?
60 unless @user && @user.active?
61 redirect_to home_url
61 redirect_to home_url
62 return
62 return
63 end
63 end
64 if request.post?
64 if request.post?
65 @user.password, @user.password_confirmation = params[:new_password], params[:new_password_confirmation]
65 @user.password, @user.password_confirmation = params[:new_password], params[:new_password_confirmation]
66 if @user.save
66 if @user.save
67 @token.destroy
67 @token.destroy
68 flash[:notice] = l(:notice_account_password_updated)
68 flash[:notice] = l(:notice_account_password_updated)
69 redirect_to signin_path
69 redirect_to signin_path
70 return
70 return
71 end
71 end
72 end
72 end
73 render :template => "account/password_recovery"
73 render :template => "account/password_recovery"
74 return
74 return
75 else
75 else
76 if request.post?
76 if request.post?
77 user = User.find_by_mail(params[:mail].to_s)
77 user = User.find_by_mail(params[:mail].to_s)
78 # user not found or not active
78 # user not found or not active
79 unless user && user.active?
79 unless user && user.active?
80 flash.now[:error] = l(:notice_account_unknown_email)
80 flash.now[:error] = l(:notice_account_unknown_email)
81 return
81 return
82 end
82 end
83 # user cannot change its password
83 # user cannot change its password
84 unless user.change_password_allowed?
84 unless user.change_password_allowed?
85 flash.now[:error] = l(:notice_can_t_change_password)
85 flash.now[:error] = l(:notice_can_t_change_password)
86 return
86 return
87 end
87 end
88 # create a new token for password recovery
88 # create a new token for password recovery
89 token = Token.new(:user => user, :action => "recovery")
89 token = Token.new(:user => user, :action => "recovery")
90 if token.save
90 if token.save
91 Mailer.lost_password(token).deliver
91 Mailer.lost_password(token).deliver
92 flash[:notice] = l(:notice_account_lost_email_sent)
92 flash[:notice] = l(:notice_account_lost_email_sent)
93 redirect_to signin_path
93 redirect_to signin_path
94 return
94 return
95 end
95 end
96 end
96 end
97 end
97 end
98 end
98 end
99
99
100 # User self-registration
100 # User self-registration
101 def register
101 def register
102 (redirect_to(home_url); return) unless Setting.self_registration? || session[:auth_source_registration]
102 (redirect_to(home_url); return) unless Setting.self_registration? || session[:auth_source_registration]
103 if request.get?
103 if request.get?
104 session[:auth_source_registration] = nil
104 session[:auth_source_registration] = nil
105 @user = User.new(:language => current_language.to_s)
105 @user = User.new(:language => current_language.to_s)
106 else
106 else
107 user_params = params[:user] || {}
107 user_params = params[:user] || {}
108 @user = User.new
108 @user = User.new
109 @user.safe_attributes = user_params
109 @user.safe_attributes = user_params
110 @user.admin = false
110 @user.admin = false
111 @user.register
111 @user.register
112 if session[:auth_source_registration]
112 if session[:auth_source_registration]
113 @user.activate
113 @user.activate
114 @user.login = session[:auth_source_registration][:login]
114 @user.login = session[:auth_source_registration][:login]
115 @user.auth_source_id = session[:auth_source_registration][:auth_source_id]
115 @user.auth_source_id = session[:auth_source_registration][:auth_source_id]
116 if @user.save
116 if @user.save
117 session[:auth_source_registration] = nil
117 session[:auth_source_registration] = nil
118 self.logged_user = @user
118 self.logged_user = @user
119 flash[:notice] = l(:notice_account_activated)
119 flash[:notice] = l(:notice_account_activated)
120 redirect_to my_account_path
120 redirect_to my_account_path
121 end
121 end
122 else
122 else
123 @user.login = params[:user][:login]
123 @user.login = params[:user][:login]
124 unless user_params[:identity_url].present? && user_params[:password].blank? && user_params[:password_confirmation].blank?
124 unless user_params[:identity_url].present? && user_params[:password].blank? && user_params[:password_confirmation].blank?
125 @user.password, @user.password_confirmation = user_params[:password], user_params[:password_confirmation]
125 @user.password, @user.password_confirmation = user_params[:password], user_params[:password_confirmation]
126 end
126 end
127
127
128 case Setting.self_registration
128 case Setting.self_registration
129 when '1'
129 when '1'
130 register_by_email_activation(@user)
130 register_by_email_activation(@user)
131 when '3'
131 when '3'
132 register_automatically(@user)
132 register_automatically(@user)
133 else
133 else
134 register_manually_by_administrator(@user)
134 register_manually_by_administrator(@user)
135 end
135 end
136 end
136 end
137 end
137 end
138 end
138 end
139
139
140 # Token based account activation
140 # Token based account activation
141 def activate
141 def activate
142 (redirect_to(home_url); return) unless Setting.self_registration? && params[:token].present?
142 (redirect_to(home_url); return) unless Setting.self_registration? && params[:token].present?
143 token = Token.find_token('register', params[:token].to_s)
143 token = Token.find_token('register', params[:token].to_s)
144 (redirect_to(home_url); return) unless token and !token.expired?
144 (redirect_to(home_url); return) unless token and !token.expired?
145 user = token.user
145 user = token.user
146 (redirect_to(home_url); return) unless user.registered?
146 (redirect_to(home_url); return) unless user.registered?
147 user.activate
147 user.activate
148 if user.save
148 if user.save
149 token.destroy
149 token.destroy
150 flash[:notice] = l(:notice_account_activated)
150 flash[:notice] = l(:notice_account_activated)
151 end
151 end
152 redirect_to signin_path
152 redirect_to signin_path
153 end
153 end
154
154
155 private
155 private
156
156
157 def authenticate_user
157 def authenticate_user
158 if Setting.openid? && using_open_id?
158 if Setting.openid? && using_open_id?
159 open_id_authenticate(params[:openid_url])
159 open_id_authenticate(params[:openid_url])
160 else
160 else
161 password_authentication
161 password_authentication
162 end
162 end
163 end
163 end
164
164
165 def password_authentication
165 def password_authentication
166 user = User.try_to_login(params[:username], params[:password])
166 user = User.try_to_login(params[:username], params[:password])
167
167
168 if user.nil?
168 if user.nil?
169 invalid_credentials
169 invalid_credentials
170 elsif user.new_record?
170 elsif user.new_record?
171 onthefly_creation_failed(user, {:login => user.login, :auth_source_id => user.auth_source_id })
171 onthefly_creation_failed(user, {:login => user.login, :auth_source_id => user.auth_source_id })
172 else
172 else
173 # Valid user
173 # Valid user
174 successful_authentication(user)
174 successful_authentication(user)
175 end
175 end
176 end
176 end
177
177
178 def open_id_authenticate(openid_url)
178 def open_id_authenticate(openid_url)
179 authenticate_with_open_id(openid_url, :required => [:nickname, :fullname, :email], :return_to => signin_url, :method => :post) do |result, identity_url, registration|
179 authenticate_with_open_id(openid_url, :required => [:nickname, :fullname, :email], :return_to => signin_url, :method => :post) do |result, identity_url, registration|
180 if result.successful?
180 if result.successful?
181 user = User.find_or_initialize_by_identity_url(identity_url)
181 user = User.find_or_initialize_by_identity_url(identity_url)
182 if user.new_record?
182 if user.new_record?
183 # Self-registration off
183 # Self-registration off
184 (redirect_to(home_url); return) unless Setting.self_registration?
184 (redirect_to(home_url); return) unless Setting.self_registration?
185
185
186 # Create on the fly
186 # Create on the fly
187 user.login = registration['nickname'] unless registration['nickname'].nil?
187 user.login = registration['nickname'] unless registration['nickname'].nil?
188 user.mail = registration['email'] unless registration['email'].nil?
188 user.mail = registration['email'] unless registration['email'].nil?
189 user.firstname, user.lastname = registration['fullname'].split(' ') unless registration['fullname'].nil?
189 user.firstname, user.lastname = registration['fullname'].split(' ') unless registration['fullname'].nil?
190 user.random_password
190 user.random_password
191 user.register
191 user.register
192
192
193 case Setting.self_registration
193 case Setting.self_registration
194 when '1'
194 when '1'
195 register_by_email_activation(user) do
195 register_by_email_activation(user) do
196 onthefly_creation_failed(user)
196 onthefly_creation_failed(user)
197 end
197 end
198 when '3'
198 when '3'
199 register_automatically(user) do
199 register_automatically(user) do
200 onthefly_creation_failed(user)
200 onthefly_creation_failed(user)
201 end
201 end
202 else
202 else
203 register_manually_by_administrator(user) do
203 register_manually_by_administrator(user) do
204 onthefly_creation_failed(user)
204 onthefly_creation_failed(user)
205 end
205 end
206 end
206 end
207 else
207 else
208 # Existing record
208 # Existing record
209 if user.active?
209 if user.active?
210 successful_authentication(user)
210 successful_authentication(user)
211 else
211 else
212 account_pending
212 account_pending
213 end
213 end
214 end
214 end
215 end
215 end
216 end
216 end
217 end
217 end
218
218
219 def successful_authentication(user)
219 def successful_authentication(user)
220 logger.info "Successful authentication for '#{user.login}' from #{request.remote_ip} at #{Time.now.utc}"
220 logger.info "Successful authentication for '#{user.login}' from #{request.remote_ip} at #{Time.now.utc}"
221 # Valid user
221 # Valid user
222 self.logged_user = user
222 self.logged_user = user
223 # generate a key and set cookie if autologin
223 # generate a key and set cookie if autologin
224 if params[:autologin] && Setting.autologin?
224 if params[:autologin] && Setting.autologin?
225 set_autologin_cookie(user)
225 set_autologin_cookie(user)
226 end
226 end
227 call_hook(:controller_account_success_authentication_after, {:user => user })
227 call_hook(:controller_account_success_authentication_after, {:user => user })
228 redirect_back_or_default my_page_path
228 redirect_back_or_default my_page_path
229 end
229 end
230
230
231 def set_autologin_cookie(user)
231 def set_autologin_cookie(user)
232 token = Token.create(:user => user, :action => 'autologin')
232 token = Token.create(:user => user, :action => 'autologin')
233 cookie_name = Redmine::Configuration['autologin_cookie_name'] || 'autologin'
234 cookie_options = {
233 cookie_options = {
235 :value => token.value,
234 :value => token.value,
236 :expires => 1.year.from_now,
235 :expires => 1.year.from_now,
237 :path => (Redmine::Configuration['autologin_cookie_path'] || '/'),
236 :path => (Redmine::Configuration['autologin_cookie_path'] || '/'),
238 :secure => (Redmine::Configuration['autologin_cookie_secure'] ? true : false),
237 :secure => (Redmine::Configuration['autologin_cookie_secure'] ? true : false),
239 :httponly => true
238 :httponly => true
240 }
239 }
241 cookies[cookie_name] = cookie_options
240 cookies[autologin_cookie_name] = cookie_options
242 end
241 end
243
242
244 # Onthefly creation failed, display the registration form to fill/fix attributes
243 # Onthefly creation failed, display the registration form to fill/fix attributes
245 def onthefly_creation_failed(user, auth_source_options = { })
244 def onthefly_creation_failed(user, auth_source_options = { })
246 @user = user
245 @user = user
247 session[:auth_source_registration] = auth_source_options unless auth_source_options.empty?
246 session[:auth_source_registration] = auth_source_options unless auth_source_options.empty?
248 render :action => 'register'
247 render :action => 'register'
249 end
248 end
250
249
251 def invalid_credentials
250 def invalid_credentials
252 logger.warn "Failed login for '#{params[:username]}' from #{request.remote_ip} at #{Time.now.utc}"
251 logger.warn "Failed login for '#{params[:username]}' from #{request.remote_ip} at #{Time.now.utc}"
253 flash.now[:error] = l(:notice_account_invalid_creditentials)
252 flash.now[:error] = l(:notice_account_invalid_creditentials)
254 end
253 end
255
254
256 # Register a user for email activation.
255 # Register a user for email activation.
257 #
256 #
258 # Pass a block for behavior when a user fails to save
257 # Pass a block for behavior when a user fails to save
259 def register_by_email_activation(user, &block)
258 def register_by_email_activation(user, &block)
260 token = Token.new(:user => user, :action => "register")
259 token = Token.new(:user => user, :action => "register")
261 if user.save and token.save
260 if user.save and token.save
262 Mailer.register(token).deliver
261 Mailer.register(token).deliver
263 flash[:notice] = l(:notice_account_register_done)
262 flash[:notice] = l(:notice_account_register_done)
264 redirect_to signin_path
263 redirect_to signin_path
265 else
264 else
266 yield if block_given?
265 yield if block_given?
267 end
266 end
268 end
267 end
269
268
270 # Automatically register a user
269 # Automatically register a user
271 #
270 #
272 # Pass a block for behavior when a user fails to save
271 # Pass a block for behavior when a user fails to save
273 def register_automatically(user, &block)
272 def register_automatically(user, &block)
274 # Automatic activation
273 # Automatic activation
275 user.activate
274 user.activate
276 user.last_login_on = Time.now
275 user.last_login_on = Time.now
277 if user.save
276 if user.save
278 self.logged_user = user
277 self.logged_user = user
279 flash[:notice] = l(:notice_account_activated)
278 flash[:notice] = l(:notice_account_activated)
280 redirect_to my_account_path
279 redirect_to my_account_path
281 else
280 else
282 yield if block_given?
281 yield if block_given?
283 end
282 end
284 end
283 end
285
284
286 # Manual activation by the administrator
285 # Manual activation by the administrator
287 #
286 #
288 # Pass a block for behavior when a user fails to save
287 # Pass a block for behavior when a user fails to save
289 def register_manually_by_administrator(user, &block)
288 def register_manually_by_administrator(user, &block)
290 if user.save
289 if user.save
291 # Sends an email to the administrators
290 # Sends an email to the administrators
292 Mailer.account_activation_request(user).deliver
291 Mailer.account_activation_request(user).deliver
293 account_pending
292 account_pending
294 else
293 else
295 yield if block_given?
294 yield if block_given?
296 end
295 end
297 end
296 end
298
297
299 def account_pending
298 def account_pending
300 flash[:notice] = l(:notice_account_pending)
299 flash[:notice] = l(:notice_account_pending)
301 redirect_to signin_path
300 redirect_to signin_path
302 end
301 end
303 end
302 end
@@ -1,603 +1,607
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2013 Jean-Philippe Lang
2 # Copyright (C) 2006-2013 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 def handle_unverified_request
36 def handle_unverified_request
37 super
37 super
38 cookies.delete(:autologin)
38 cookies.delete(autologin_cookie_name)
39 end
39 end
40
40
41 before_filter :session_expiration, :user_setup, :check_if_login_required, :set_localization
41 before_filter :session_expiration, :user_setup, :check_if_login_required, :set_localization
42
42
43 rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token
43 rescue_from ActionController::InvalidAuthenticityToken, :with => :invalid_authenticity_token
44 rescue_from ::Unauthorized, :with => :deny_access
44 rescue_from ::Unauthorized, :with => :deny_access
45 rescue_from ::ActionView::MissingTemplate, :with => :missing_template
45 rescue_from ::ActionView::MissingTemplate, :with => :missing_template
46
46
47 include Redmine::Search::Controller
47 include Redmine::Search::Controller
48 include Redmine::MenuManager::MenuController
48 include Redmine::MenuManager::MenuController
49 helper Redmine::MenuManager::MenuHelper
49 helper Redmine::MenuManager::MenuHelper
50
50
51 def session_expiration
51 def session_expiration
52 if session[:user_id]
52 if session[:user_id]
53 if session_expired? && !try_to_autologin
53 if session_expired? && !try_to_autologin
54 reset_session
54 reset_session
55 flash[:error] = l(:error_session_expired)
55 flash[:error] = l(:error_session_expired)
56 redirect_to signin_url
56 redirect_to signin_url
57 else
57 else
58 session[:atime] = Time.now.utc.to_i
58 session[:atime] = Time.now.utc.to_i
59 end
59 end
60 end
60 end
61 end
61 end
62
62
63 def session_expired?
63 def session_expired?
64 if Setting.session_lifetime?
64 if Setting.session_lifetime?
65 unless session[:ctime] && (Time.now.utc.to_i - session[:ctime].to_i <= Setting.session_lifetime.to_i * 60)
65 unless session[:ctime] && (Time.now.utc.to_i - session[:ctime].to_i <= Setting.session_lifetime.to_i * 60)
66 return true
66 return true
67 end
67 end
68 end
68 end
69 if Setting.session_timeout?
69 if Setting.session_timeout?
70 unless session[:atime] && (Time.now.utc.to_i - session[:atime].to_i <= Setting.session_timeout.to_i * 60)
70 unless session[:atime] && (Time.now.utc.to_i - session[:atime].to_i <= Setting.session_timeout.to_i * 60)
71 return true
71 return true
72 end
72 end
73 end
73 end
74 false
74 false
75 end
75 end
76
76
77 def start_user_session(user)
77 def start_user_session(user)
78 session[:user_id] = user.id
78 session[:user_id] = user.id
79 session[:ctime] = Time.now.utc.to_i
79 session[:ctime] = Time.now.utc.to_i
80 session[:atime] = Time.now.utc.to_i
80 session[:atime] = Time.now.utc.to_i
81 end
81 end
82
82
83 def user_setup
83 def user_setup
84 # Check the settings cache for each request
84 # Check the settings cache for each request
85 Setting.check_cache
85 Setting.check_cache
86 # Find the current user
86 # Find the current user
87 User.current = find_current_user
87 User.current = find_current_user
88 logger.info(" Current user: " + (User.current.logged? ? "#{User.current.login} (id=#{User.current.id})" : "anonymous")) if logger
88 logger.info(" Current user: " + (User.current.logged? ? "#{User.current.login} (id=#{User.current.id})" : "anonymous")) if logger
89 end
89 end
90
90
91 # Returns the current user or nil if no user is logged in
91 # Returns the current user or nil if no user is logged in
92 # and starts a session if needed
92 # and starts a session if needed
93 def find_current_user
93 def find_current_user
94 user = nil
94 user = nil
95 unless api_request?
95 unless api_request?
96 if session[:user_id]
96 if session[:user_id]
97 # existing session
97 # existing session
98 user = (User.active.find(session[:user_id]) rescue nil)
98 user = (User.active.find(session[:user_id]) rescue nil)
99 elsif autologin_user = try_to_autologin
99 elsif autologin_user = try_to_autologin
100 user = autologin_user
100 user = autologin_user
101 elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
101 elsif params[:format] == 'atom' && params[:key] && request.get? && accept_rss_auth?
102 # RSS key authentication does not start a session
102 # RSS key authentication does not start a session
103 user = User.find_by_rss_key(params[:key])
103 user = User.find_by_rss_key(params[:key])
104 end
104 end
105 end
105 end
106 if user.nil? && Setting.rest_api_enabled? && accept_api_auth?
106 if user.nil? && Setting.rest_api_enabled? && accept_api_auth?
107 if (key = api_key_from_request)
107 if (key = api_key_from_request)
108 # Use API key
108 # Use API key
109 user = User.find_by_api_key(key)
109 user = User.find_by_api_key(key)
110 else
110 else
111 # HTTP Basic, either username/password or API key/random
111 # HTTP Basic, either username/password or API key/random
112 authenticate_with_http_basic do |username, password|
112 authenticate_with_http_basic do |username, password|
113 user = User.try_to_login(username, password) || User.find_by_api_key(username)
113 user = User.try_to_login(username, password) || User.find_by_api_key(username)
114 end
114 end
115 end
115 end
116 # Switch user if requested by an admin user
116 # Switch user if requested by an admin user
117 if user && user.admin? && (username = api_switch_user_from_request)
117 if user && user.admin? && (username = api_switch_user_from_request)
118 su = User.find_by_login(username)
118 su = User.find_by_login(username)
119 if su && su.active?
119 if su && su.active?
120 logger.info(" User switched by: #{user.login} (id=#{user.id})") if logger
120 logger.info(" User switched by: #{user.login} (id=#{user.id})") if logger
121 user = su
121 user = su
122 else
122 else
123 render_error :message => 'Invalid X-Redmine-Switch-User header', :status => 412
123 render_error :message => 'Invalid X-Redmine-Switch-User header', :status => 412
124 end
124 end
125 end
125 end
126 end
126 end
127 user
127 user
128 end
128 end
129
129
130 def autologin_cookie_name
131 Redmine::Configuration['autologin_cookie_name'].presence || 'autologin'
132 end
133
130 def try_to_autologin
134 def try_to_autologin
131 if cookies[:autologin] && Setting.autologin?
135 if cookies[autologin_cookie_name] && Setting.autologin?
132 # auto-login feature starts a new session
136 # auto-login feature starts a new session
133 user = User.try_to_autologin(cookies[:autologin])
137 user = User.try_to_autologin(cookies[autologin_cookie_name])
134 if user
138 if user
135 reset_session
139 reset_session
136 start_user_session(user)
140 start_user_session(user)
137 end
141 end
138 user
142 user
139 end
143 end
140 end
144 end
141
145
142 # Sets the logged in user
146 # Sets the logged in user
143 def logged_user=(user)
147 def logged_user=(user)
144 reset_session
148 reset_session
145 if user && user.is_a?(User)
149 if user && user.is_a?(User)
146 User.current = user
150 User.current = user
147 start_user_session(user)
151 start_user_session(user)
148 else
152 else
149 User.current = User.anonymous
153 User.current = User.anonymous
150 end
154 end
151 end
155 end
152
156
153 # Logs out current user
157 # Logs out current user
154 def logout_user
158 def logout_user
155 if User.current.logged?
159 if User.current.logged?
156 cookies.delete :autologin
160 cookies.delete :autologin
157 Token.delete_all(["user_id = ? AND action = ?", User.current.id, 'autologin'])
161 Token.delete_all(["user_id = ? AND action = ?", User.current.id, 'autologin'])
158 self.logged_user = nil
162 self.logged_user = nil
159 end
163 end
160 end
164 end
161
165
162 # check if login is globally required to access the application
166 # check if login is globally required to access the application
163 def check_if_login_required
167 def check_if_login_required
164 # no check needed if user is already logged in
168 # no check needed if user is already logged in
165 return true if User.current.logged?
169 return true if User.current.logged?
166 require_login if Setting.login_required?
170 require_login if Setting.login_required?
167 end
171 end
168
172
169 def set_localization
173 def set_localization
170 lang = nil
174 lang = nil
171 if User.current.logged?
175 if User.current.logged?
172 lang = find_language(User.current.language)
176 lang = find_language(User.current.language)
173 end
177 end
174 if lang.nil? && request.env['HTTP_ACCEPT_LANGUAGE']
178 if lang.nil? && request.env['HTTP_ACCEPT_LANGUAGE']
175 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
179 accept_lang = parse_qvalues(request.env['HTTP_ACCEPT_LANGUAGE']).first
176 if !accept_lang.blank?
180 if !accept_lang.blank?
177 accept_lang = accept_lang.downcase
181 accept_lang = accept_lang.downcase
178 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
182 lang = find_language(accept_lang) || find_language(accept_lang.split('-').first)
179 end
183 end
180 end
184 end
181 lang ||= Setting.default_language
185 lang ||= Setting.default_language
182 set_language_if_valid(lang)
186 set_language_if_valid(lang)
183 end
187 end
184
188
185 def require_login
189 def require_login
186 if !User.current.logged?
190 if !User.current.logged?
187 # Extract only the basic url parameters on non-GET requests
191 # Extract only the basic url parameters on non-GET requests
188 if request.get?
192 if request.get?
189 url = url_for(params)
193 url = url_for(params)
190 else
194 else
191 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
195 url = url_for(:controller => params[:controller], :action => params[:action], :id => params[:id], :project_id => params[:project_id])
192 end
196 end
193 respond_to do |format|
197 respond_to do |format|
194 format.html { redirect_to :controller => "account", :action => "login", :back_url => url }
198 format.html { redirect_to :controller => "account", :action => "login", :back_url => url }
195 format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
199 format.atom { redirect_to :controller => "account", :action => "login", :back_url => url }
196 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
200 format.xml { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
197 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
201 format.js { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
198 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
202 format.json { head :unauthorized, 'WWW-Authenticate' => 'Basic realm="Redmine API"' }
199 end
203 end
200 return false
204 return false
201 end
205 end
202 true
206 true
203 end
207 end
204
208
205 def require_admin
209 def require_admin
206 return unless require_login
210 return unless require_login
207 if !User.current.admin?
211 if !User.current.admin?
208 render_403
212 render_403
209 return false
213 return false
210 end
214 end
211 true
215 true
212 end
216 end
213
217
214 def deny_access
218 def deny_access
215 User.current.logged? ? render_403 : require_login
219 User.current.logged? ? render_403 : require_login
216 end
220 end
217
221
218 # Authorize the user for the requested action
222 # Authorize the user for the requested action
219 def authorize(ctrl = params[:controller], action = params[:action], global = false)
223 def authorize(ctrl = params[:controller], action = params[:action], global = false)
220 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
224 allowed = User.current.allowed_to?({:controller => ctrl, :action => action}, @project || @projects, :global => global)
221 if allowed
225 if allowed
222 true
226 true
223 else
227 else
224 if @project && @project.archived?
228 if @project && @project.archived?
225 render_403 :message => :notice_not_authorized_archived_project
229 render_403 :message => :notice_not_authorized_archived_project
226 else
230 else
227 deny_access
231 deny_access
228 end
232 end
229 end
233 end
230 end
234 end
231
235
232 # Authorize the user for the requested action outside a project
236 # Authorize the user for the requested action outside a project
233 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
237 def authorize_global(ctrl = params[:controller], action = params[:action], global = true)
234 authorize(ctrl, action, global)
238 authorize(ctrl, action, global)
235 end
239 end
236
240
237 # Find project of id params[:id]
241 # Find project of id params[:id]
238 def find_project
242 def find_project
239 @project = Project.find(params[:id])
243 @project = Project.find(params[:id])
240 rescue ActiveRecord::RecordNotFound
244 rescue ActiveRecord::RecordNotFound
241 render_404
245 render_404
242 end
246 end
243
247
244 # Find project of id params[:project_id]
248 # Find project of id params[:project_id]
245 def find_project_by_project_id
249 def find_project_by_project_id
246 @project = Project.find(params[:project_id])
250 @project = Project.find(params[:project_id])
247 rescue ActiveRecord::RecordNotFound
251 rescue ActiveRecord::RecordNotFound
248 render_404
252 render_404
249 end
253 end
250
254
251 # Find a project based on params[:project_id]
255 # Find a project based on params[:project_id]
252 # TODO: some subclasses override this, see about merging their logic
256 # TODO: some subclasses override this, see about merging their logic
253 def find_optional_project
257 def find_optional_project
254 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
258 @project = Project.find(params[:project_id]) unless params[:project_id].blank?
255 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
259 allowed = User.current.allowed_to?({:controller => params[:controller], :action => params[:action]}, @project, :global => true)
256 allowed ? true : deny_access
260 allowed ? true : deny_access
257 rescue ActiveRecord::RecordNotFound
261 rescue ActiveRecord::RecordNotFound
258 render_404
262 render_404
259 end
263 end
260
264
261 # Finds and sets @project based on @object.project
265 # Finds and sets @project based on @object.project
262 def find_project_from_association
266 def find_project_from_association
263 render_404 unless @object.present?
267 render_404 unless @object.present?
264
268
265 @project = @object.project
269 @project = @object.project
266 end
270 end
267
271
268 def find_model_object
272 def find_model_object
269 model = self.class.model_object
273 model = self.class.model_object
270 if model
274 if model
271 @object = model.find(params[:id])
275 @object = model.find(params[:id])
272 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
276 self.instance_variable_set('@' + controller_name.singularize, @object) if @object
273 end
277 end
274 rescue ActiveRecord::RecordNotFound
278 rescue ActiveRecord::RecordNotFound
275 render_404
279 render_404
276 end
280 end
277
281
278 def self.model_object(model)
282 def self.model_object(model)
279 self.model_object = model
283 self.model_object = model
280 end
284 end
281
285
282 # Find the issue whose id is the :id parameter
286 # Find the issue whose id is the :id parameter
283 # Raises a Unauthorized exception if the issue is not visible
287 # Raises a Unauthorized exception if the issue is not visible
284 def find_issue
288 def find_issue
285 # Issue.visible.find(...) can not be used to redirect user to the login form
289 # Issue.visible.find(...) can not be used to redirect user to the login form
286 # if the issue actually exists but requires authentication
290 # if the issue actually exists but requires authentication
287 @issue = Issue.find(params[:id])
291 @issue = Issue.find(params[:id])
288 raise Unauthorized unless @issue.visible?
292 raise Unauthorized unless @issue.visible?
289 @project = @issue.project
293 @project = @issue.project
290 rescue ActiveRecord::RecordNotFound
294 rescue ActiveRecord::RecordNotFound
291 render_404
295 render_404
292 end
296 end
293
297
294 # Find issues with a single :id param or :ids array param
298 # Find issues with a single :id param or :ids array param
295 # Raises a Unauthorized exception if one of the issues is not visible
299 # Raises a Unauthorized exception if one of the issues is not visible
296 def find_issues
300 def find_issues
297 @issues = Issue.find_all_by_id(params[:id] || params[:ids])
301 @issues = Issue.find_all_by_id(params[:id] || params[:ids])
298 raise ActiveRecord::RecordNotFound if @issues.empty?
302 raise ActiveRecord::RecordNotFound if @issues.empty?
299 raise Unauthorized unless @issues.all?(&:visible?)
303 raise Unauthorized unless @issues.all?(&:visible?)
300 @projects = @issues.collect(&:project).compact.uniq
304 @projects = @issues.collect(&:project).compact.uniq
301 @project = @projects.first if @projects.size == 1
305 @project = @projects.first if @projects.size == 1
302 rescue ActiveRecord::RecordNotFound
306 rescue ActiveRecord::RecordNotFound
303 render_404
307 render_404
304 end
308 end
305
309
306 def find_attachments
310 def find_attachments
307 if (attachments = params[:attachments]).present?
311 if (attachments = params[:attachments]).present?
308 att = attachments.values.collect do |attachment|
312 att = attachments.values.collect do |attachment|
309 Attachment.find_by_token( attachment[:token] ) if attachment[:token].present?
313 Attachment.find_by_token( attachment[:token] ) if attachment[:token].present?
310 end
314 end
311 att.compact!
315 att.compact!
312 end
316 end
313 @attachments = att || []
317 @attachments = att || []
314 end
318 end
315
319
316 # make sure that the user is a member of the project (or admin) if project is private
320 # make sure that the user is a member of the project (or admin) if project is private
317 # used as a before_filter for actions that do not require any particular permission on the project
321 # used as a before_filter for actions that do not require any particular permission on the project
318 def check_project_privacy
322 def check_project_privacy
319 if @project && !@project.archived?
323 if @project && !@project.archived?
320 if @project.visible?
324 if @project.visible?
321 true
325 true
322 else
326 else
323 deny_access
327 deny_access
324 end
328 end
325 else
329 else
326 @project = nil
330 @project = nil
327 render_404
331 render_404
328 false
332 false
329 end
333 end
330 end
334 end
331
335
332 def back_url
336 def back_url
333 url = params[:back_url]
337 url = params[:back_url]
334 if url.nil? && referer = request.env['HTTP_REFERER']
338 if url.nil? && referer = request.env['HTTP_REFERER']
335 url = CGI.unescape(referer.to_s)
339 url = CGI.unescape(referer.to_s)
336 end
340 end
337 url
341 url
338 end
342 end
339
343
340 def redirect_back_or_default(default)
344 def redirect_back_or_default(default)
341 back_url = params[:back_url].to_s
345 back_url = params[:back_url].to_s
342 if back_url.present?
346 if back_url.present?
343 begin
347 begin
344 uri = URI.parse(back_url)
348 uri = URI.parse(back_url)
345 # do not redirect user to another host or to the login or register page
349 # do not redirect user to another host or to the login or register page
346 if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})
350 if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})
347 redirect_to(back_url)
351 redirect_to(back_url)
348 return
352 return
349 end
353 end
350 rescue URI::InvalidURIError
354 rescue URI::InvalidURIError
351 logger.warn("Could not redirect to invalid URL #{back_url}")
355 logger.warn("Could not redirect to invalid URL #{back_url}")
352 # redirect to default
356 # redirect to default
353 end
357 end
354 end
358 end
355 redirect_to default
359 redirect_to default
356 false
360 false
357 end
361 end
358
362
359 # Redirects to the request referer if present, redirects to args or call block otherwise.
363 # Redirects to the request referer if present, redirects to args or call block otherwise.
360 def redirect_to_referer_or(*args, &block)
364 def redirect_to_referer_or(*args, &block)
361 redirect_to :back
365 redirect_to :back
362 rescue ::ActionController::RedirectBackError
366 rescue ::ActionController::RedirectBackError
363 if args.any?
367 if args.any?
364 redirect_to *args
368 redirect_to *args
365 elsif block_given?
369 elsif block_given?
366 block.call
370 block.call
367 else
371 else
368 raise "#redirect_to_referer_or takes arguments or a block"
372 raise "#redirect_to_referer_or takes arguments or a block"
369 end
373 end
370 end
374 end
371
375
372 def render_403(options={})
376 def render_403(options={})
373 @project = nil
377 @project = nil
374 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
378 render_error({:message => :notice_not_authorized, :status => 403}.merge(options))
375 return false
379 return false
376 end
380 end
377
381
378 def render_404(options={})
382 def render_404(options={})
379 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
383 render_error({:message => :notice_file_not_found, :status => 404}.merge(options))
380 return false
384 return false
381 end
385 end
382
386
383 # Renders an error response
387 # Renders an error response
384 def render_error(arg)
388 def render_error(arg)
385 arg = {:message => arg} unless arg.is_a?(Hash)
389 arg = {:message => arg} unless arg.is_a?(Hash)
386
390
387 @message = arg[:message]
391 @message = arg[:message]
388 @message = l(@message) if @message.is_a?(Symbol)
392 @message = l(@message) if @message.is_a?(Symbol)
389 @status = arg[:status] || 500
393 @status = arg[:status] || 500
390
394
391 respond_to do |format|
395 respond_to do |format|
392 format.html {
396 format.html {
393 render :template => 'common/error', :layout => use_layout, :status => @status
397 render :template => 'common/error', :layout => use_layout, :status => @status
394 }
398 }
395 format.any { head @status }
399 format.any { head @status }
396 end
400 end
397 end
401 end
398
402
399 # Handler for ActionView::MissingTemplate exception
403 # Handler for ActionView::MissingTemplate exception
400 def missing_template
404 def missing_template
401 logger.warn "Missing template, responding with 404"
405 logger.warn "Missing template, responding with 404"
402 @project = nil
406 @project = nil
403 render_404
407 render_404
404 end
408 end
405
409
406 # Filter for actions that provide an API response
410 # Filter for actions that provide an API response
407 # but have no HTML representation for non admin users
411 # but have no HTML representation for non admin users
408 def require_admin_or_api_request
412 def require_admin_or_api_request
409 return true if api_request?
413 return true if api_request?
410 if User.current.admin?
414 if User.current.admin?
411 true
415 true
412 elsif User.current.logged?
416 elsif User.current.logged?
413 render_error(:status => 406)
417 render_error(:status => 406)
414 else
418 else
415 deny_access
419 deny_access
416 end
420 end
417 end
421 end
418
422
419 # Picks which layout to use based on the request
423 # Picks which layout to use based on the request
420 #
424 #
421 # @return [boolean, string] name of the layout to use or false for no layout
425 # @return [boolean, string] name of the layout to use or false for no layout
422 def use_layout
426 def use_layout
423 request.xhr? ? false : 'base'
427 request.xhr? ? false : 'base'
424 end
428 end
425
429
426 def invalid_authenticity_token
430 def invalid_authenticity_token
427 if api_request?
431 if api_request?
428 logger.error "Form authenticity token is missing or is invalid. API calls must include a proper Content-type header (text/xml or text/json)."
432 logger.error "Form authenticity token is missing or is invalid. API calls must include a proper Content-type header (text/xml or text/json)."
429 end
433 end
430 render_error "Invalid form authenticity token."
434 render_error "Invalid form authenticity token."
431 end
435 end
432
436
433 def render_feed(items, options={})
437 def render_feed(items, options={})
434 @items = items || []
438 @items = items || []
435 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
439 @items.sort! {|x,y| y.event_datetime <=> x.event_datetime }
436 @items = @items.slice(0, Setting.feeds_limit.to_i)
440 @items = @items.slice(0, Setting.feeds_limit.to_i)
437 @title = options[:title] || Setting.app_title
441 @title = options[:title] || Setting.app_title
438 render :template => "common/feed", :formats => [:atom], :layout => false,
442 render :template => "common/feed", :formats => [:atom], :layout => false,
439 :content_type => 'application/atom+xml'
443 :content_type => 'application/atom+xml'
440 end
444 end
441
445
442 def self.accept_rss_auth(*actions)
446 def self.accept_rss_auth(*actions)
443 if actions.any?
447 if actions.any?
444 self.accept_rss_auth_actions = actions
448 self.accept_rss_auth_actions = actions
445 else
449 else
446 self.accept_rss_auth_actions || []
450 self.accept_rss_auth_actions || []
447 end
451 end
448 end
452 end
449
453
450 def accept_rss_auth?(action=action_name)
454 def accept_rss_auth?(action=action_name)
451 self.class.accept_rss_auth.include?(action.to_sym)
455 self.class.accept_rss_auth.include?(action.to_sym)
452 end
456 end
453
457
454 def self.accept_api_auth(*actions)
458 def self.accept_api_auth(*actions)
455 if actions.any?
459 if actions.any?
456 self.accept_api_auth_actions = actions
460 self.accept_api_auth_actions = actions
457 else
461 else
458 self.accept_api_auth_actions || []
462 self.accept_api_auth_actions || []
459 end
463 end
460 end
464 end
461
465
462 def accept_api_auth?(action=action_name)
466 def accept_api_auth?(action=action_name)
463 self.class.accept_api_auth.include?(action.to_sym)
467 self.class.accept_api_auth.include?(action.to_sym)
464 end
468 end
465
469
466 # Returns the number of objects that should be displayed
470 # Returns the number of objects that should be displayed
467 # on the paginated list
471 # on the paginated list
468 def per_page_option
472 def per_page_option
469 per_page = nil
473 per_page = nil
470 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
474 if params[:per_page] && Setting.per_page_options_array.include?(params[:per_page].to_s.to_i)
471 per_page = params[:per_page].to_s.to_i
475 per_page = params[:per_page].to_s.to_i
472 session[:per_page] = per_page
476 session[:per_page] = per_page
473 elsif session[:per_page]
477 elsif session[:per_page]
474 per_page = session[:per_page]
478 per_page = session[:per_page]
475 else
479 else
476 per_page = Setting.per_page_options_array.first || 25
480 per_page = Setting.per_page_options_array.first || 25
477 end
481 end
478 per_page
482 per_page
479 end
483 end
480
484
481 # Returns offset and limit used to retrieve objects
485 # Returns offset and limit used to retrieve objects
482 # for an API response based on offset, limit and page parameters
486 # for an API response based on offset, limit and page parameters
483 def api_offset_and_limit(options=params)
487 def api_offset_and_limit(options=params)
484 if options[:offset].present?
488 if options[:offset].present?
485 offset = options[:offset].to_i
489 offset = options[:offset].to_i
486 if offset < 0
490 if offset < 0
487 offset = 0
491 offset = 0
488 end
492 end
489 end
493 end
490 limit = options[:limit].to_i
494 limit = options[:limit].to_i
491 if limit < 1
495 if limit < 1
492 limit = 25
496 limit = 25
493 elsif limit > 100
497 elsif limit > 100
494 limit = 100
498 limit = 100
495 end
499 end
496 if offset.nil? && options[:page].present?
500 if offset.nil? && options[:page].present?
497 offset = (options[:page].to_i - 1) * limit
501 offset = (options[:page].to_i - 1) * limit
498 offset = 0 if offset < 0
502 offset = 0 if offset < 0
499 end
503 end
500 offset ||= 0
504 offset ||= 0
501
505
502 [offset, limit]
506 [offset, limit]
503 end
507 end
504
508
505 # qvalues http header parser
509 # qvalues http header parser
506 # code taken from webrick
510 # code taken from webrick
507 def parse_qvalues(value)
511 def parse_qvalues(value)
508 tmp = []
512 tmp = []
509 if value
513 if value
510 parts = value.split(/,\s*/)
514 parts = value.split(/,\s*/)
511 parts.each {|part|
515 parts.each {|part|
512 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
516 if m = %r{^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$}.match(part)
513 val = m[1]
517 val = m[1]
514 q = (m[2] or 1).to_f
518 q = (m[2] or 1).to_f
515 tmp.push([val, q])
519 tmp.push([val, q])
516 end
520 end
517 }
521 }
518 tmp = tmp.sort_by{|val, q| -q}
522 tmp = tmp.sort_by{|val, q| -q}
519 tmp.collect!{|val, q| val}
523 tmp.collect!{|val, q| val}
520 end
524 end
521 return tmp
525 return tmp
522 rescue
526 rescue
523 nil
527 nil
524 end
528 end
525
529
526 # Returns a string that can be used as filename value in Content-Disposition header
530 # Returns a string that can be used as filename value in Content-Disposition header
527 def filename_for_content_disposition(name)
531 def filename_for_content_disposition(name)
528 request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name
532 request.env['HTTP_USER_AGENT'] =~ %r{MSIE} ? ERB::Util.url_encode(name) : name
529 end
533 end
530
534
531 def api_request?
535 def api_request?
532 %w(xml json).include? params[:format]
536 %w(xml json).include? params[:format]
533 end
537 end
534
538
535 # Returns the API key present in the request
539 # Returns the API key present in the request
536 def api_key_from_request
540 def api_key_from_request
537 if params[:key].present?
541 if params[:key].present?
538 params[:key].to_s
542 params[:key].to_s
539 elsif request.headers["X-Redmine-API-Key"].present?
543 elsif request.headers["X-Redmine-API-Key"].present?
540 request.headers["X-Redmine-API-Key"].to_s
544 request.headers["X-Redmine-API-Key"].to_s
541 end
545 end
542 end
546 end
543
547
544 # Returns the API 'switch user' value if present
548 # Returns the API 'switch user' value if present
545 def api_switch_user_from_request
549 def api_switch_user_from_request
546 request.headers["X-Redmine-Switch-User"].to_s.presence
550 request.headers["X-Redmine-Switch-User"].to_s.presence
547 end
551 end
548
552
549 # Renders a warning flash if obj has unsaved attachments
553 # Renders a warning flash if obj has unsaved attachments
550 def render_attachment_warning_if_needed(obj)
554 def render_attachment_warning_if_needed(obj)
551 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
555 flash[:warning] = l(:warning_attachments_not_saved, obj.unsaved_attachments.size) if obj.unsaved_attachments.present?
552 end
556 end
553
557
554 # Sets the `flash` notice or error based the number of issues that did not save
558 # Sets the `flash` notice or error based the number of issues that did not save
555 #
559 #
556 # @param [Array, Issue] issues all of the saved and unsaved Issues
560 # @param [Array, Issue] issues all of the saved and unsaved Issues
557 # @param [Array, Integer] unsaved_issue_ids the issue ids that were not saved
561 # @param [Array, Integer] unsaved_issue_ids the issue ids that were not saved
558 def set_flash_from_bulk_issue_save(issues, unsaved_issue_ids)
562 def set_flash_from_bulk_issue_save(issues, unsaved_issue_ids)
559 if unsaved_issue_ids.empty?
563 if unsaved_issue_ids.empty?
560 flash[:notice] = l(:notice_successful_update) unless issues.empty?
564 flash[:notice] = l(:notice_successful_update) unless issues.empty?
561 else
565 else
562 flash[:error] = l(:notice_failed_to_save_issues,
566 flash[:error] = l(:notice_failed_to_save_issues,
563 :count => unsaved_issue_ids.size,
567 :count => unsaved_issue_ids.size,
564 :total => issues.size,
568 :total => issues.size,
565 :ids => '#' + unsaved_issue_ids.join(', #'))
569 :ids => '#' + unsaved_issue_ids.join(', #'))
566 end
570 end
567 end
571 end
568
572
569 # Rescues an invalid query statement. Just in case...
573 # Rescues an invalid query statement. Just in case...
570 def query_statement_invalid(exception)
574 def query_statement_invalid(exception)
571 logger.error "Query::StatementInvalid: #{exception.message}" if logger
575 logger.error "Query::StatementInvalid: #{exception.message}" if logger
572 session.delete(:query)
576 session.delete(:query)
573 sort_clear if respond_to?(:sort_clear)
577 sort_clear if respond_to?(:sort_clear)
574 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
578 render_error "An error occurred while executing the query and has been logged. Please report this error to your Redmine administrator."
575 end
579 end
576
580
577 # Renders a 200 response for successfull updates or deletions via the API
581 # Renders a 200 response for successfull updates or deletions via the API
578 def render_api_ok
582 def render_api_ok
579 render_api_head :ok
583 render_api_head :ok
580 end
584 end
581
585
582 # Renders a head API response
586 # Renders a head API response
583 def render_api_head(status)
587 def render_api_head(status)
584 # #head would return a response body with one space
588 # #head would return a response body with one space
585 render :text => '', :status => status, :layout => nil
589 render :text => '', :status => status, :layout => nil
586 end
590 end
587
591
588 # Renders API response on validation failure
592 # Renders API response on validation failure
589 def render_validation_errors(objects)
593 def render_validation_errors(objects)
590 if objects.is_a?(Array)
594 if objects.is_a?(Array)
591 @error_messages = objects.map {|object| object.errors.full_messages}.flatten
595 @error_messages = objects.map {|object| object.errors.full_messages}.flatten
592 else
596 else
593 @error_messages = objects.errors.full_messages
597 @error_messages = objects.errors.full_messages
594 end
598 end
595 render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
599 render :template => 'common/error_messages.api', :status => :unprocessable_entity, :layout => nil
596 end
600 end
597
601
598 # Overrides #_include_layout? so that #render with no arguments
602 # Overrides #_include_layout? so that #render with no arguments
599 # doesn't use the layout for api requests
603 # doesn't use the layout for api requests
600 def _include_layout?(*args)
604 def _include_layout?(*args)
601 api_request? ? false : super
605 api_request? ? false : super
602 end
606 end
603 end
607 end
@@ -1,185 +1,207
1 # Redmine - project management software
1 # Redmine - project management software
2 # Copyright (C) 2006-2013 Jean-Philippe Lang
2 # Copyright (C) 2006-2013 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 File.expand_path('../../test_helper', __FILE__)
18 require File.expand_path('../../test_helper', __FILE__)
19
19
20 begin
20 begin
21 require 'mocha'
21 require 'mocha'
22 rescue
22 rescue
23 # Won't run some tests
23 # Won't run some tests
24 end
24 end
25
25
26 class AccountTest < ActionController::IntegrationTest
26 class AccountTest < ActionController::IntegrationTest
27 fixtures :users, :roles
27 fixtures :users, :roles
28
28
29 # Replace this with your real tests.
29 # Replace this with your real tests.
30 def test_login
30 def test_login
31 get "my/page"
31 get "my/page"
32 assert_redirected_to "/login?back_url=http%3A%2F%2Fwww.example.com%2Fmy%2Fpage"
32 assert_redirected_to "/login?back_url=http%3A%2F%2Fwww.example.com%2Fmy%2Fpage"
33 log_user('jsmith', 'jsmith')
33 log_user('jsmith', 'jsmith')
34
34
35 get "my/account"
35 get "my/account"
36 assert_response :success
36 assert_response :success
37 assert_template "my/account"
37 assert_template "my/account"
38 end
38 end
39
39
40 def test_autologin
40 def test_autologin
41 user = User.find(1)
41 user = User.find(1)
42 Setting.autologin = "7"
42 Setting.autologin = "7"
43 Token.delete_all
43 Token.delete_all
44
44
45 # User logs in with 'autologin' checked
45 # User logs in with 'autologin' checked
46 post '/login', :username => user.login, :password => 'admin', :autologin => 1
46 post '/login', :username => user.login, :password => 'admin', :autologin => 1
47 assert_redirected_to '/my/page'
47 assert_redirected_to '/my/page'
48 token = Token.first
48 token = Token.first
49 assert_not_nil token
49 assert_not_nil token
50 assert_equal user, token.user
50 assert_equal user, token.user
51 assert_equal 'autologin', token.action
51 assert_equal 'autologin', token.action
52 assert_equal user.id, session[:user_id]
52 assert_equal user.id, session[:user_id]
53 assert_equal token.value, cookies['autologin']
53 assert_equal token.value, cookies['autologin']
54
54
55 # Session is cleared
55 # Session is cleared
56 reset!
56 reset!
57 User.current = nil
57 User.current = nil
58 # Clears user's last login timestamp
58 # Clears user's last login timestamp
59 user.update_attribute :last_login_on, nil
59 user.update_attribute :last_login_on, nil
60 assert_nil user.reload.last_login_on
60 assert_nil user.reload.last_login_on
61
61
62 # User comes back with his autologin cookie
62 # User comes back with his autologin cookie
63 cookies[:autologin] = token.value
63 cookies[:autologin] = token.value
64 get '/my/page'
64 get '/my/page'
65 assert_response :success
65 assert_response :success
66 assert_template 'my/page'
66 assert_template 'my/page'
67 assert_equal user.id, session[:user_id]
67 assert_equal user.id, session[:user_id]
68 assert_not_nil user.reload.last_login_on
68 assert_not_nil user.reload.last_login_on
69 end
69 end
70
70
71 def test_autologin_should_use_autologin_cookie_name
72 Token.delete_all
73 Redmine::Configuration.stubs(:[]).with('autologin_cookie_name').returns('custom_autologin')
74 Redmine::Configuration.stubs(:[]).with('autologin_cookie_path').returns('/')
75 Redmine::Configuration.stubs(:[]).with('autologin_cookie_secure').returns(false)
76
77 with_settings :autologin => '7' do
78 assert_difference 'Token.count' do
79 post '/login', :username => 'admin', :password => 'admin', :autologin => 1
80 end
81 assert_response 302
82 assert cookies['custom_autologin'].present?
83 token = cookies['custom_autologin']
84
85 # Session is cleared
86 reset!
87 cookies['custom_autologin'] = token
88 get '/my/page'
89 assert_response :success
90 end
91 end
92
71 def test_lost_password
93 def test_lost_password
72 Token.delete_all
94 Token.delete_all
73
95
74 get "account/lost_password"
96 get "account/lost_password"
75 assert_response :success
97 assert_response :success
76 assert_template "account/lost_password"
98 assert_template "account/lost_password"
77 assert_select 'input[name=mail]'
99 assert_select 'input[name=mail]'
78
100
79 post "account/lost_password", :mail => 'jSmith@somenet.foo'
101 post "account/lost_password", :mail => 'jSmith@somenet.foo'
80 assert_redirected_to "/login"
102 assert_redirected_to "/login"
81
103
82 token = Token.first
104 token = Token.first
83 assert_equal 'recovery', token.action
105 assert_equal 'recovery', token.action
84 assert_equal 'jsmith@somenet.foo', token.user.mail
106 assert_equal 'jsmith@somenet.foo', token.user.mail
85 assert !token.expired?
107 assert !token.expired?
86
108
87 get "account/lost_password", :token => token.value
109 get "account/lost_password", :token => token.value
88 assert_response :success
110 assert_response :success
89 assert_template "account/password_recovery"
111 assert_template "account/password_recovery"
90 assert_select 'input[type=hidden][name=token][value=?]', token.value
112 assert_select 'input[type=hidden][name=token][value=?]', token.value
91 assert_select 'input[name=new_password]'
113 assert_select 'input[name=new_password]'
92 assert_select 'input[name=new_password_confirmation]'
114 assert_select 'input[name=new_password_confirmation]'
93
115
94 post "account/lost_password", :token => token.value, :new_password => 'newpass123', :new_password_confirmation => 'newpass123'
116 post "account/lost_password", :token => token.value, :new_password => 'newpass123', :new_password_confirmation => 'newpass123'
95 assert_redirected_to "/login"
117 assert_redirected_to "/login"
96 assert_equal 'Password was successfully updated.', flash[:notice]
118 assert_equal 'Password was successfully updated.', flash[:notice]
97
119
98 log_user('jsmith', 'newpass123')
120 log_user('jsmith', 'newpass123')
99 assert_equal 0, Token.count
121 assert_equal 0, Token.count
100 end
122 end
101
123
102 def test_register_with_automatic_activation
124 def test_register_with_automatic_activation
103 Setting.self_registration = '3'
125 Setting.self_registration = '3'
104
126
105 get 'account/register'
127 get 'account/register'
106 assert_response :success
128 assert_response :success
107 assert_template 'account/register'
129 assert_template 'account/register'
108
130
109 post 'account/register', :user => {:login => "newuser", :language => "en", :firstname => "New", :lastname => "User", :mail => "newuser@foo.bar",
131 post 'account/register', :user => {:login => "newuser", :language => "en", :firstname => "New", :lastname => "User", :mail => "newuser@foo.bar",
110 :password => "newpass123", :password_confirmation => "newpass123"}
132 :password => "newpass123", :password_confirmation => "newpass123"}
111 assert_redirected_to '/my/account'
133 assert_redirected_to '/my/account'
112 follow_redirect!
134 follow_redirect!
113 assert_response :success
135 assert_response :success
114 assert_template 'my/account'
136 assert_template 'my/account'
115
137
116 user = User.find_by_login('newuser')
138 user = User.find_by_login('newuser')
117 assert_not_nil user
139 assert_not_nil user
118 assert user.active?
140 assert user.active?
119 assert_not_nil user.last_login_on
141 assert_not_nil user.last_login_on
120 end
142 end
121
143
122 def test_register_with_manual_activation
144 def test_register_with_manual_activation
123 Setting.self_registration = '2'
145 Setting.self_registration = '2'
124
146
125 post 'account/register', :user => {:login => "newuser", :language => "en", :firstname => "New", :lastname => "User", :mail => "newuser@foo.bar",
147 post 'account/register', :user => {:login => "newuser", :language => "en", :firstname => "New", :lastname => "User", :mail => "newuser@foo.bar",
126 :password => "newpass123", :password_confirmation => "newpass123"}
148 :password => "newpass123", :password_confirmation => "newpass123"}
127 assert_redirected_to '/login'
149 assert_redirected_to '/login'
128 assert !User.find_by_login('newuser').active?
150 assert !User.find_by_login('newuser').active?
129 end
151 end
130
152
131 def test_register_with_email_activation
153 def test_register_with_email_activation
132 Setting.self_registration = '1'
154 Setting.self_registration = '1'
133 Token.delete_all
155 Token.delete_all
134
156
135 post 'account/register', :user => {:login => "newuser", :language => "en", :firstname => "New", :lastname => "User", :mail => "newuser@foo.bar",
157 post 'account/register', :user => {:login => "newuser", :language => "en", :firstname => "New", :lastname => "User", :mail => "newuser@foo.bar",
136 :password => "newpass123", :password_confirmation => "newpass123"}
158 :password => "newpass123", :password_confirmation => "newpass123"}
137 assert_redirected_to '/login'
159 assert_redirected_to '/login'
138 assert !User.find_by_login('newuser').active?
160 assert !User.find_by_login('newuser').active?
139
161
140 token = Token.first
162 token = Token.first
141 assert_equal 'register', token.action
163 assert_equal 'register', token.action
142 assert_equal 'newuser@foo.bar', token.user.mail
164 assert_equal 'newuser@foo.bar', token.user.mail
143 assert !token.expired?
165 assert !token.expired?
144
166
145 get 'account/activate', :token => token.value
167 get 'account/activate', :token => token.value
146 assert_redirected_to '/login'
168 assert_redirected_to '/login'
147 log_user('newuser', 'newpass123')
169 log_user('newuser', 'newpass123')
148 end
170 end
149
171
150 def test_onthefly_registration
172 def test_onthefly_registration
151 # disable registration
173 # disable registration
152 Setting.self_registration = '0'
174 Setting.self_registration = '0'
153 AuthSource.expects(:authenticate).returns({:login => 'foo', :firstname => 'Foo', :lastname => 'Smith', :mail => 'foo@bar.com', :auth_source_id => 66})
175 AuthSource.expects(:authenticate).returns({:login => 'foo', :firstname => 'Foo', :lastname => 'Smith', :mail => 'foo@bar.com', :auth_source_id => 66})
154
176
155 post '/login', :username => 'foo', :password => 'bar'
177 post '/login', :username => 'foo', :password => 'bar'
156 assert_redirected_to '/my/page'
178 assert_redirected_to '/my/page'
157
179
158 user = User.find_by_login('foo')
180 user = User.find_by_login('foo')
159 assert user.is_a?(User)
181 assert user.is_a?(User)
160 assert_equal 66, user.auth_source_id
182 assert_equal 66, user.auth_source_id
161 assert user.hashed_password.blank?
183 assert user.hashed_password.blank?
162 end
184 end
163
185
164 def test_onthefly_registration_with_invalid_attributes
186 def test_onthefly_registration_with_invalid_attributes
165 # disable registration
187 # disable registration
166 Setting.self_registration = '0'
188 Setting.self_registration = '0'
167 AuthSource.expects(:authenticate).returns({:login => 'foo', :lastname => 'Smith', :auth_source_id => 66})
189 AuthSource.expects(:authenticate).returns({:login => 'foo', :lastname => 'Smith', :auth_source_id => 66})
168
190
169 post '/login', :username => 'foo', :password => 'bar'
191 post '/login', :username => 'foo', :password => 'bar'
170 assert_response :success
192 assert_response :success
171 assert_template 'account/register'
193 assert_template 'account/register'
172 assert_tag :input, :attributes => { :name => 'user[firstname]', :value => '' }
194 assert_tag :input, :attributes => { :name => 'user[firstname]', :value => '' }
173 assert_tag :input, :attributes => { :name => 'user[lastname]', :value => 'Smith' }
195 assert_tag :input, :attributes => { :name => 'user[lastname]', :value => 'Smith' }
174 assert_no_tag :input, :attributes => { :name => 'user[login]' }
196 assert_no_tag :input, :attributes => { :name => 'user[login]' }
175 assert_no_tag :input, :attributes => { :name => 'user[password]' }
197 assert_no_tag :input, :attributes => { :name => 'user[password]' }
176
198
177 post 'account/register', :user => {:firstname => 'Foo', :lastname => 'Smith', :mail => 'foo@bar.com'}
199 post 'account/register', :user => {:firstname => 'Foo', :lastname => 'Smith', :mail => 'foo@bar.com'}
178 assert_redirected_to '/my/account'
200 assert_redirected_to '/my/account'
179
201
180 user = User.find_by_login('foo')
202 user = User.find_by_login('foo')
181 assert user.is_a?(User)
203 assert user.is_a?(User)
182 assert_equal 66, user.auth_source_id
204 assert_equal 66, user.auth_source_id
183 assert user.hashed_password.blank?
205 assert user.hashed_password.blank?
184 end
206 end
185 end
207 end
General Comments 0
You need to be logged in to leave comments. Login now