##// END OF EJS Templates
Adds token finder methods....
Jean-Philippe Lang -
r11144:812da860b376
parent child
Show More
@@ -1,303 +1,303
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2013 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 class AccountController < ApplicationController
19 19 helper :custom_fields
20 20 include CustomFieldsHelper
21 21
22 22 # prevents login action to be filtered by check_if_login_required application scope filter
23 23 skip_before_filter :check_if_login_required
24 24
25 25 # Login request and validation
26 26 def login
27 27 if request.get?
28 28 if User.current.logged?
29 29 redirect_to home_url
30 30 end
31 31 else
32 32 authenticate_user
33 33 end
34 34 rescue AuthSourceException => e
35 35 logger.error "An error occured when authenticating #{params[:username]}: #{e.message}"
36 36 render_error :message => e.message
37 37 end
38 38
39 39 # Log out current user and redirect to welcome page
40 40 def logout
41 41 if User.current.anonymous?
42 42 redirect_to home_url
43 43 elsif request.post?
44 44 logout_user
45 45 redirect_to home_url
46 46 end
47 47 # display the logout form
48 48 end
49 49
50 50 # Lets user choose a new password
51 51 def lost_password
52 52 (redirect_to(home_url); return) unless Setting.lost_password?
53 53 if params[:token]
54 @token = Token.find_by_action_and_value("recovery", params[:token].to_s)
54 @token = Token.find_token("recovery", params[:token].to_s)
55 55 if @token.nil? || @token.expired?
56 56 redirect_to home_url
57 57 return
58 58 end
59 59 @user = @token.user
60 60 unless @user && @user.active?
61 61 redirect_to home_url
62 62 return
63 63 end
64 64 if request.post?
65 65 @user.password, @user.password_confirmation = params[:new_password], params[:new_password_confirmation]
66 66 if @user.save
67 67 @token.destroy
68 68 flash[:notice] = l(:notice_account_password_updated)
69 69 redirect_to signin_path
70 70 return
71 71 end
72 72 end
73 73 render :template => "account/password_recovery"
74 74 return
75 75 else
76 76 if request.post?
77 77 user = User.find_by_mail(params[:mail].to_s)
78 78 # user not found or not active
79 79 unless user && user.active?
80 80 flash.now[:error] = l(:notice_account_unknown_email)
81 81 return
82 82 end
83 83 # user cannot change its password
84 84 unless user.change_password_allowed?
85 85 flash.now[:error] = l(:notice_can_t_change_password)
86 86 return
87 87 end
88 88 # create a new token for password recovery
89 89 token = Token.new(:user => user, :action => "recovery")
90 90 if token.save
91 91 Mailer.lost_password(token).deliver
92 92 flash[:notice] = l(:notice_account_lost_email_sent)
93 93 redirect_to signin_path
94 94 return
95 95 end
96 96 end
97 97 end
98 98 end
99 99
100 100 # User self-registration
101 101 def register
102 102 (redirect_to(home_url); return) unless Setting.self_registration? || session[:auth_source_registration]
103 103 if request.get?
104 104 session[:auth_source_registration] = nil
105 105 @user = User.new(:language => current_language.to_s)
106 106 else
107 107 user_params = params[:user] || {}
108 108 @user = User.new
109 109 @user.safe_attributes = user_params
110 110 @user.admin = false
111 111 @user.register
112 112 if session[:auth_source_registration]
113 113 @user.activate
114 114 @user.login = session[:auth_source_registration][:login]
115 115 @user.auth_source_id = session[:auth_source_registration][:auth_source_id]
116 116 if @user.save
117 117 session[:auth_source_registration] = nil
118 118 self.logged_user = @user
119 119 flash[:notice] = l(:notice_account_activated)
120 120 redirect_to my_account_path
121 121 end
122 122 else
123 123 @user.login = params[:user][:login]
124 124 unless user_params[:identity_url].present? && user_params[:password].blank? && user_params[:password_confirmation].blank?
125 125 @user.password, @user.password_confirmation = user_params[:password], user_params[:password_confirmation]
126 126 end
127 127
128 128 case Setting.self_registration
129 129 when '1'
130 130 register_by_email_activation(@user)
131 131 when '3'
132 132 register_automatically(@user)
133 133 else
134 134 register_manually_by_administrator(@user)
135 135 end
136 136 end
137 137 end
138 138 end
139 139
140 140 # Token based account activation
141 141 def activate
142 142 (redirect_to(home_url); return) unless Setting.self_registration? && params[:token].present?
143 token = Token.find_by_action_and_value('register', params[:token].to_s)
143 token = Token.find_token('register', params[:token].to_s)
144 144 (redirect_to(home_url); return) unless token and !token.expired?
145 145 user = token.user
146 146 (redirect_to(home_url); return) unless user.registered?
147 147 user.activate
148 148 if user.save
149 149 token.destroy
150 150 flash[:notice] = l(:notice_account_activated)
151 151 end
152 152 redirect_to signin_path
153 153 end
154 154
155 155 private
156 156
157 157 def authenticate_user
158 158 if Setting.openid? && using_open_id?
159 159 open_id_authenticate(params[:openid_url])
160 160 else
161 161 password_authentication
162 162 end
163 163 end
164 164
165 165 def password_authentication
166 166 user = User.try_to_login(params[:username], params[:password])
167 167
168 168 if user.nil?
169 169 invalid_credentials
170 170 elsif user.new_record?
171 171 onthefly_creation_failed(user, {:login => user.login, :auth_source_id => user.auth_source_id })
172 172 else
173 173 # Valid user
174 174 successful_authentication(user)
175 175 end
176 176 end
177 177
178 178 def open_id_authenticate(openid_url)
179 179 authenticate_with_open_id(openid_url, :required => [:nickname, :fullname, :email], :return_to => signin_url, :method => :post) do |result, identity_url, registration|
180 180 if result.successful?
181 181 user = User.find_or_initialize_by_identity_url(identity_url)
182 182 if user.new_record?
183 183 # Self-registration off
184 184 (redirect_to(home_url); return) unless Setting.self_registration?
185 185
186 186 # Create on the fly
187 187 user.login = registration['nickname'] unless registration['nickname'].nil?
188 188 user.mail = registration['email'] unless registration['email'].nil?
189 189 user.firstname, user.lastname = registration['fullname'].split(' ') unless registration['fullname'].nil?
190 190 user.random_password
191 191 user.register
192 192
193 193 case Setting.self_registration
194 194 when '1'
195 195 register_by_email_activation(user) do
196 196 onthefly_creation_failed(user)
197 197 end
198 198 when '3'
199 199 register_automatically(user) do
200 200 onthefly_creation_failed(user)
201 201 end
202 202 else
203 203 register_manually_by_administrator(user) do
204 204 onthefly_creation_failed(user)
205 205 end
206 206 end
207 207 else
208 208 # Existing record
209 209 if user.active?
210 210 successful_authentication(user)
211 211 else
212 212 account_pending
213 213 end
214 214 end
215 215 end
216 216 end
217 217 end
218 218
219 219 def successful_authentication(user)
220 220 logger.info "Successful authentication for '#{user.login}' from #{request.remote_ip} at #{Time.now.utc}"
221 221 # Valid user
222 222 self.logged_user = user
223 223 # generate a key and set cookie if autologin
224 224 if params[:autologin] && Setting.autologin?
225 225 set_autologin_cookie(user)
226 226 end
227 227 call_hook(:controller_account_success_authentication_after, {:user => user })
228 228 redirect_back_or_default my_page_path
229 229 end
230 230
231 231 def set_autologin_cookie(user)
232 232 token = Token.create(:user => user, :action => 'autologin')
233 233 cookie_name = Redmine::Configuration['autologin_cookie_name'] || 'autologin'
234 234 cookie_options = {
235 235 :value => token.value,
236 236 :expires => 1.year.from_now,
237 237 :path => (Redmine::Configuration['autologin_cookie_path'] || '/'),
238 238 :secure => (Redmine::Configuration['autologin_cookie_secure'] ? true : false),
239 239 :httponly => true
240 240 }
241 241 cookies[cookie_name] = cookie_options
242 242 end
243 243
244 244 # Onthefly creation failed, display the registration form to fill/fix attributes
245 245 def onthefly_creation_failed(user, auth_source_options = { })
246 246 @user = user
247 247 session[:auth_source_registration] = auth_source_options unless auth_source_options.empty?
248 248 render :action => 'register'
249 249 end
250 250
251 251 def invalid_credentials
252 252 logger.warn "Failed login for '#{params[:username]}' from #{request.remote_ip} at #{Time.now.utc}"
253 253 flash.now[:error] = l(:notice_account_invalid_creditentials)
254 254 end
255 255
256 256 # Register a user for email activation.
257 257 #
258 258 # Pass a block for behavior when a user fails to save
259 259 def register_by_email_activation(user, &block)
260 260 token = Token.new(:user => user, :action => "register")
261 261 if user.save and token.save
262 262 Mailer.register(token).deliver
263 263 flash[:notice] = l(:notice_account_register_done)
264 264 redirect_to signin_path
265 265 else
266 266 yield if block_given?
267 267 end
268 268 end
269 269
270 270 # Automatically register a user
271 271 #
272 272 # Pass a block for behavior when a user fails to save
273 273 def register_automatically(user, &block)
274 274 # Automatic activation
275 275 user.activate
276 276 user.last_login_on = Time.now
277 277 if user.save
278 278 self.logged_user = user
279 279 flash[:notice] = l(:notice_account_activated)
280 280 redirect_to my_account_path
281 281 else
282 282 yield if block_given?
283 283 end
284 284 end
285 285
286 286 # Manual activation by the administrator
287 287 #
288 288 # Pass a block for behavior when a user fails to save
289 289 def register_manually_by_administrator(user, &block)
290 290 if user.save
291 291 # Sends an email to the administrators
292 292 Mailer.account_activation_request(user).deliver
293 293 account_pending
294 294 else
295 295 yield if block_given?
296 296 end
297 297 end
298 298
299 299 def account_pending
300 300 flash[:notice] = l(:notice_account_pending)
301 301 redirect_to signin_path
302 302 end
303 303 end
@@ -1,66 +1,83
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2013 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 class Token < ActiveRecord::Base
19 19 belongs_to :user
20 20 validates_uniqueness_of :value
21 21
22 22 before_create :delete_previous_tokens, :generate_new_token
23 23
24 24 @@validity_time = 1.day
25 25
26 26 def generate_new_token
27 27 self.value = Token.generate_token_value
28 28 end
29 29
30 30 # Return true if token has expired
31 31 def expired?
32 32 return Time.now > self.created_on + @@validity_time
33 33 end
34 34
35 35 # Delete all expired tokens
36 36 def self.destroy_expired
37 37 Token.delete_all ["action NOT IN (?) AND created_on < ?", ['feeds', 'api'], Time.now - @@validity_time]
38 38 end
39 39
40 40 # Returns the active user who owns the key for the given action
41 41 def self.find_active_user(action, key, validity_days=nil)
42 user = find_user(action, key, validity_days)
43 if user && user.active?
44 user
45 end
46 end
47
48 # Returns the user who owns the key for the given action
49 def self.find_user(action, key, validity_days=nil)
50 token = find_token(action, key, validity_days)
51 if token
52 token.user
53 end
54 end
55
56 # Returns the token for action and key with an optional
57 # validity duration (in number of days)
58 def self.find_token(action, key, validity_days=nil)
42 59 action = action.to_s
43 60 key = key.to_s
44 return nil unless action.present? && key =~ /\A[a-f0-9]+\z/
61 return nil unless action.present? && key =~ /\A[a-z0-9]+\z/i
45 62
46 token = find_by_action_and_value(action, key)
47 if token && token.user && token.user.active?
63 token = Token.where(:action => action, :value => key).first
64 if token && (token.action == action) && (token.value == key) && token.user
48 65 if validity_days.nil? || (token.created_on > validity_days.days.ago)
49 token.user
66 token
50 67 end
51 68 end
52 69 end
53 70
54 71 def self.generate_token_value
55 72 Redmine::Utils.random_hex(20)
56 73 end
57 74
58 75 private
59 76
60 77 # Removes obsolete tokens (same user and action)
61 78 def delete_previous_tokens
62 79 if user
63 80 Token.delete_all(['user_id = ? AND action = ?', user.id, action])
64 81 end
65 82 end
66 83 end
@@ -1,61 +1,113
1 1 # Redmine - project management software
2 2 # Copyright (C) 2006-2013 Jean-Philippe Lang
3 3 #
4 4 # This program is free software; you can redistribute it and/or
5 5 # modify it under the terms of the GNU General Public License
6 6 # as published by the Free Software Foundation; either version 2
7 7 # of the License, or (at your option) any later version.
8 8 #
9 9 # This program is distributed in the hope that it will be useful,
10 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 12 # GNU General Public License for more details.
13 13 #
14 14 # You should have received a copy of the GNU General Public License
15 15 # along with this program; if not, write to the Free Software
16 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 17
18 18 require File.expand_path('../../test_helper', __FILE__)
19 19
20 20 class TokenTest < ActiveSupport::TestCase
21 21 fixtures :tokens
22 22
23 23 def test_create
24 24 token = Token.new
25 25 token.save
26 26 assert_equal 40, token.value.length
27 27 assert !token.expired?
28 28 end
29 29
30 30 def test_create_should_remove_existing_tokens
31 31 user = User.find(1)
32 32 t1 = Token.create(:user => user, :action => 'autologin')
33 33 t2 = Token.create(:user => user, :action => 'autologin')
34 34 assert_not_equal t1.value, t2.value
35 35 assert !Token.exists?(t1.id)
36 36 assert Token.exists?(t2.id)
37 37 end
38 38
39 39 def test_destroy_expired_should_not_destroy_feeds_and_api_tokens
40 40 Token.delete_all
41 41
42 42 Token.create!(:user_id => 1, :action => 'api', :created_on => 7.days.ago)
43 43 Token.create!(:user_id => 1, :action => 'feeds', :created_on => 7.days.ago)
44 44
45 45 assert_no_difference 'Token.count' do
46 46 assert_equal 0, Token.destroy_expired
47 47 end
48 48 end
49 49
50 50 def test_destroy_expired_should_destroy_expired_tokens
51 51 Token.delete_all
52 52
53 53 Token.create!(:user_id => 1, :action => 'autologin', :created_on => 7.days.ago)
54 54 Token.create!(:user_id => 2, :action => 'autologin', :created_on => 3.days.ago)
55 55 Token.create!(:user_id => 3, :action => 'autologin', :created_on => 1.hour.ago)
56 56
57 57 assert_difference 'Token.count', -2 do
58 58 assert_equal 2, Token.destroy_expired
59 59 end
60 60 end
61
62 def test_find_active_user_should_return_user
63 token = Token.create!(:user_id => 1, :action => 'api')
64 assert_equal User.find(1), Token.find_active_user('api', token.value)
65 end
66
67 def test_find_active_user_should_return_nil_for_locked_user
68 token = Token.create!(:user_id => 1, :action => 'api')
69 User.find(1).lock!
70 assert_nil Token.find_active_user('api', token.value)
71 end
72
73 def test_find_user_should_return_user
74 token = Token.create!(:user_id => 1, :action => 'api')
75 assert_equal User.find(1), Token.find_user('api', token.value)
76 end
77
78 def test_find_user_should_return_locked_user
79 token = Token.create!(:user_id => 1, :action => 'api')
80 User.find(1).lock!
81 assert_equal User.find(1), Token.find_user('api', token.value)
82 end
83
84 def test_find_token_should_return_the_token
85 token = Token.create!(:user_id => 1, :action => 'api')
86 assert_equal token, Token.find_token('api', token.value)
87 end
88
89 def test_find_token_should_return_the_token_with_validity
90 token = Token.create!(:user_id => 1, :action => 'api', :created_on => 1.hour.ago)
91 assert_equal token, Token.find_token('api', token.value, 1)
92 end
93
94 def test_find_token_should_return_nil_with_wrong_action
95 token = Token.create!(:user_id => 1, :action => 'feeds')
96 assert_nil Token.find_token('api', token.value)
97 end
98
99 def test_find_token_should_return_nil_with_wrong_action
100 token = Token.create!(:user_id => 1, :action => 'feeds')
101 assert_nil Token.find_token('api', Token.generate_token_value)
102 end
103
104 def test_find_token_should_return_nil_without_user
105 token = Token.create!(:user_id => 999, :action => 'api')
106 assert_nil Token.find_token('api', token.value)
107 end
108
109 def test_find_token_should_return_nil_with_validity_expired
110 token = Token.create!(:user_id => 999, :action => 'api', :created_on => 2.days.ago)
111 assert_nil Token.find_token('api', token.value, 1)
112 end
61 113 end
General Comments 0
You need to be logged in to leave comments. Login now