two_factor_authentication 1.1.3 → 2.2.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +4 -4
- data/.codeclimate.yml +21 -0
- data/.gitignore +2 -0
- data/.rubocop.yml +295 -0
- data/.travis.yml +14 -7
- data/CHANGELOG.md +119 -0
- data/Gemfile +12 -3
- data/README.md +320 -58
- data/app/controllers/devise/two_factor_authentication_controller.rb +65 -25
- data/app/views/devise/two_factor_authentication/show.html.erb +11 -2
- data/config/locales/en.yml +1 -0
- data/config/locales/es.yml +8 -0
- data/config/locales/fr.yml +8 -0
- data/config/locales/ru.yml +1 -0
- data/lib/generators/active_record/templates/migration.rb +9 -11
- data/lib/two_factor_authentication/controllers/helpers.rb +3 -3
- data/lib/two_factor_authentication/hooks/two_factor_authenticatable.rb +12 -2
- data/lib/two_factor_authentication/models/two_factor_authenticatable.rb +158 -29
- data/lib/two_factor_authentication/orm/active_record.rb +2 -0
- data/lib/two_factor_authentication/routes.rb +3 -1
- data/lib/two_factor_authentication/schema.rb +24 -4
- data/lib/two_factor_authentication/version.rb +1 -1
- data/lib/two_factor_authentication.rb +20 -3
- data/spec/controllers/two_factor_authentication_controller_spec.rb +41 -0
- data/spec/features/two_factor_authenticatable_spec.rb +179 -30
- data/spec/generators/active_record/two_factor_authentication_generator_spec.rb +36 -0
- data/spec/lib/two_factor_authentication/models/two_factor_authenticatable_spec.rb +272 -114
- data/spec/rails_app/app/controllers/home_controller.rb +1 -1
- data/spec/rails_app/app/models/admin.rb +6 -0
- data/spec/rails_app/app/models/encrypted_user.rb +15 -0
- data/spec/rails_app/app/models/guest_user.rb +8 -1
- data/spec/rails_app/app/models/user.rb +3 -4
- data/spec/rails_app/config/environments/test.rb +10 -1
- data/spec/rails_app/config/initializers/devise.rb +5 -3
- data/spec/rails_app/config/routes.rb +1 -0
- data/spec/rails_app/db/migrate/20140403184646_devise_create_users.rb +2 -2
- data/spec/rails_app/db/migrate/20140407172619_two_factor_authentication_add_to_users.rb +1 -1
- data/spec/rails_app/db/migrate/20140407215513_add_nickanme_to_users.rb +1 -1
- data/spec/rails_app/db/migrate/20151224171231_add_encrypted_columns_to_user.rb +9 -0
- data/spec/rails_app/db/migrate/20151224180310_populate_otp_column.rb +19 -0
- data/spec/rails_app/db/migrate/20151228230340_remove_otp_secret_key_from_user.rb +5 -0
- data/spec/rails_app/db/migrate/20160209032439_devise_create_admins.rb +42 -0
- data/spec/rails_app/db/schema.rb +35 -18
- data/spec/spec_helper.rb +4 -0
- data/spec/support/authenticated_model_helper.rb +33 -2
- data/spec/support/controller_helper.rb +16 -0
- data/spec/support/features_spec_helper.rb +24 -1
- data/spec/support/totp_helper.rb +11 -0
- data/two_factor_authentication.gemspec +4 -2
- metadata +133 -30
- data/spec/controllers/two_factor_auth_spec.rb +0 -18
data/README.md
CHANGED
@@ -1,14 +1,20 @@
|
|
1
1
|
# Two factor authentication for Devise
|
2
2
|
|
3
|
+
[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Houdini/two_factor_authentication?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
4
|
+
|
3
5
|
[![Build Status](https://travis-ci.org/Houdini/two_factor_authentication.svg?branch=master)](https://travis-ci.org/Houdini/two_factor_authentication)
|
4
|
-
[![Code Climate](https://codeclimate.com/github/Houdini/two_factor_authentication.
|
6
|
+
[![Code Climate](https://codeclimate.com/github/Houdini/two_factor_authentication.svg)](https://codeclimate.com/github/Houdini/two_factor_authentication)
|
5
7
|
|
6
8
|
## Features
|
7
9
|
|
8
|
-
*
|
9
|
-
|
10
|
-
|
11
|
-
*
|
10
|
+
* Support for 2 types of OTP codes
|
11
|
+
1. Codes delivered directly to the user
|
12
|
+
2. TOTP (Google Authenticator) codes based on a shared secret (HMAC)
|
13
|
+
* Configurable OTP code digit length
|
14
|
+
* Configurable max login attempts
|
15
|
+
* Customizable logic to determine if a user needs two factor authentication
|
16
|
+
* Configurable period where users won't be asked for 2FA again
|
17
|
+
* Option to encrypt the TOTP secret in the database, with iv and salt
|
12
18
|
|
13
19
|
## Configuration
|
14
20
|
|
@@ -22,71 +28,95 @@ Once that's done, run:
|
|
22
28
|
|
23
29
|
bundle install
|
24
30
|
|
25
|
-
|
31
|
+
Note that Ruby 2.1 or greater is required.
|
26
32
|
|
27
|
-
|
33
|
+
### Installation
|
28
34
|
|
29
|
-
|
35
|
+
#### Automatic initial setup
|
30
36
|
|
31
|
-
|
32
|
-
|
33
|
-
Finally, run the migration with:
|
37
|
+
To set up the model and database migration file automatically, run the
|
38
|
+
following command:
|
34
39
|
|
35
|
-
bundle exec
|
40
|
+
bundle exec rails g two_factor_authentication MODEL
|
36
41
|
|
37
|
-
|
42
|
+
Where MODEL is your model name (e.g. User or Admin). This generator will add
|
43
|
+
`:two_factor_authenticatable` to your model's Devise options and create a
|
44
|
+
migration in `db/migrate/`, which will add the following columns to your table:
|
45
|
+
|
46
|
+
- `:second_factor_attempts_count`
|
47
|
+
- `:encrypted_otp_secret_key`
|
48
|
+
- `:encrypted_otp_secret_key_iv`
|
49
|
+
- `:encrypted_otp_secret_key_salt`
|
50
|
+
- `:direct_otp`
|
51
|
+
- `:direct_otp_sent_at`
|
52
|
+
- `:totp_timestamp`
|
38
53
|
|
39
|
-
|
54
|
+
#### Manual initial setup
|
40
55
|
|
41
|
-
|
56
|
+
If you prefer to set up the model and migration manually, add the
|
57
|
+
`:two_factor_authenticatable` option to your existing devise options, such as:
|
42
58
|
|
43
59
|
```ruby
|
44
|
-
|
45
|
-
|
46
|
-
config.otp_length = 6
|
60
|
+
devise :database_authenticatable, :registerable, :recoverable, :rememberable,
|
61
|
+
:trackable, :validatable, :two_factor_authenticatable
|
47
62
|
```
|
48
63
|
|
49
|
-
|
64
|
+
Then create your migration file using the Rails generator, such as:
|
50
65
|
|
51
|
-
```
|
52
|
-
|
53
|
-
# use Model#otp_code and send via SMS, etc.
|
54
|
-
end
|
66
|
+
```
|
67
|
+
rails g migration AddTwoFactorFieldsToUsers second_factor_attempts_count:integer encrypted_otp_secret_key:string:index encrypted_otp_secret_key_iv:string encrypted_otp_secret_key_salt:string direct_otp:string direct_otp_sent_at:datetime totp_timestamp:timestamp
|
55
68
|
```
|
56
69
|
|
57
|
-
|
58
|
-
|
59
|
-
|
70
|
+
Open your migration file (it will be in the `db/migrate` directory and will be
|
71
|
+
named something like `20151230163930_add_two_factor_fields_to_users.rb`), and
|
72
|
+
add `unique: true` to the `add_index` line so that it looks like this:
|
60
73
|
|
61
74
|
```ruby
|
62
|
-
|
63
|
-
:recoverable, :rememberable, :trackable, :validatable, :two_factor_authenticatable
|
75
|
+
add_index :users, :encrypted_otp_secret_key, unique: true
|
64
76
|
```
|
77
|
+
Save the file.
|
78
|
+
|
79
|
+
#### Complete the setup
|
80
|
+
|
81
|
+
Run the migration with:
|
82
|
+
|
83
|
+
bundle exec rake db:migrate
|
65
84
|
|
66
85
|
Add the following line to your model to fully enable two-factor auth:
|
67
86
|
|
68
|
-
has_one_time_password
|
87
|
+
has_one_time_password(encrypted: true)
|
69
88
|
|
70
|
-
Set config values
|
89
|
+
Set config values in `config/initializers/devise.rb`:
|
71
90
|
|
72
91
|
```ruby
|
73
|
-
config.max_login_attempts = 3
|
74
|
-
config.allowed_otp_drift_seconds = 30
|
75
|
-
config.otp_length = 6
|
92
|
+
config.max_login_attempts = 3 # Maximum second factor attempts count.
|
93
|
+
config.allowed_otp_drift_seconds = 30 # Allowed TOTP time drift between client and server.
|
94
|
+
config.otp_length = 6 # TOTP code length
|
95
|
+
config.direct_otp_valid_for = 5.minutes # Time before direct OTP becomes invalid
|
96
|
+
config.direct_otp_length = 6 # Direct OTP code length
|
97
|
+
config.remember_otp_session_for_seconds = 30.days # Time before browser has to perform 2fA again. Default is 0.
|
98
|
+
config.otp_secret_encryption_key = ENV['OTP_SECRET_ENCRYPTION_KEY']
|
99
|
+
config.second_factor_resource_id = 'id' # Field or method name used to set value for 2fA remember cookie
|
100
|
+
config.delete_cookie_on_logout = false # Delete cookie when user signs out, to force 2fA again on login
|
76
101
|
```
|
102
|
+
The `otp_secret_encryption_key` must be a random key that is not stored in the
|
103
|
+
DB, and is not checked in to your repo. It is recommended to store it in an
|
104
|
+
environment variable, and you can generate it with `bundle exec rake secret`.
|
77
105
|
|
78
|
-
Override the method
|
106
|
+
Override the method in your model in order to send direct OTP codes. This is
|
107
|
+
automatically called when a user logs in unless they have TOTP enabled (see
|
108
|
+
below):
|
79
109
|
|
80
110
|
```ruby
|
81
|
-
def send_two_factor_authentication_code
|
82
|
-
#
|
111
|
+
def send_two_factor_authentication_code(code)
|
112
|
+
# Send code via SMS, etc.
|
83
113
|
end
|
84
114
|
```
|
85
115
|
|
86
|
-
|
87
116
|
### Customisation and Usage
|
88
117
|
|
89
|
-
By default second factor authentication
|
118
|
+
By default, second factor authentication is required for each user. You can
|
119
|
+
change that by overriding the following method in your model:
|
90
120
|
|
91
121
|
```ruby
|
92
122
|
def need_two_factor_authentication?(request)
|
@@ -94,19 +124,34 @@ def need_two_factor_authentication?(request)
|
|
94
124
|
end
|
95
125
|
```
|
96
126
|
|
97
|
-
|
127
|
+
In the example above, two factor authentication will not be required for local
|
128
|
+
users.
|
98
129
|
|
99
|
-
This gem is compatible with Google Authenticator
|
130
|
+
This gem is compatible with [Google Authenticator](https://support.google.com/accounts/answer/1066447?hl=en).
|
131
|
+
To enable this a shared secret must be generated by invoking the following
|
132
|
+
method on your model:
|
100
133
|
|
101
|
-
|
134
|
+
```ruby
|
135
|
+
user.generate_totp_secret
|
136
|
+
```
|
102
137
|
|
103
|
-
This
|
138
|
+
This must then be shared via a provisioning uri:
|
139
|
+
|
140
|
+
```ruby
|
141
|
+
user.provisioning_uri # This assumes a user model with an email attribute
|
142
|
+
```
|
143
|
+
|
144
|
+
This provisioning uri can then be turned in to a QR code if desired so that
|
145
|
+
users may add the app to Google Authenticator easily. Once this is done, they
|
146
|
+
may retrieve a one-time password directly from the Google Authenticator app.
|
104
147
|
|
105
148
|
#### Overriding the view
|
106
149
|
|
107
|
-
The default view that shows the form can be overridden by
|
150
|
+
The default view that shows the form can be overridden by adding a
|
151
|
+
file named `show.html.erb` (or `show.html.haml` if you prefer HAML)
|
152
|
+
inside `app/views/devise/two_factor_authentication/` and customizing it.
|
153
|
+
Below is an example using ERB:
|
108
154
|
|
109
|
-
The full path should be "app/views/devise/two_factor_authentication/show.html.erb"
|
110
155
|
|
111
156
|
```html
|
112
157
|
<h2>Hi, you received a code by email, please enter it below, thanks!</h2>
|
@@ -117,27 +162,244 @@ The full path should be "app/views/devise/two_factor_authentication/show.html.er
|
|
117
162
|
<% end %>
|
118
163
|
|
119
164
|
<%= link_to "Sign out", destroy_user_session_path, :method => :delete %>
|
120
|
-
|
121
165
|
```
|
122
166
|
|
123
|
-
####
|
167
|
+
#### Upgrading from version 1.X to 2.X
|
168
|
+
|
169
|
+
The following database fields are new in version 2.
|
124
170
|
|
125
|
-
|
171
|
+
- `direct_otp`
|
172
|
+
- `direct_otp_sent_at`
|
173
|
+
- `totp_timestamp`
|
174
|
+
|
175
|
+
To add them, generate a migration such as:
|
176
|
+
|
177
|
+
$ rails g migration AddTwoFactorFieldsToUsers direct_otp:string direct_otp_sent_at:datetime totp_timestamp:timestamp
|
178
|
+
|
179
|
+
The `otp_secret_key` is only required for users who use TOTP (Google Authenticator) codes,
|
180
|
+
so unless it has been shared with the user it should be set to `nil`. The
|
181
|
+
following pseudo-code is an example of how this might be done:
|
126
182
|
|
127
183
|
```ruby
|
128
|
-
|
129
|
-
|
130
|
-
|
131
|
-
|
132
|
-
|
133
|
-
key = ROTP::Base32.random_base32
|
134
|
-
user.update_attributes(:otp_secret_key => key)
|
135
|
-
user.save
|
136
|
-
puts "Rake[:update_users_with_otp_secret_key] => User '#{user.email}' OTP secret key set to '#{key}'"
|
137
|
-
end
|
184
|
+
User.find_each do |user| do
|
185
|
+
if !uses_authenticator_app(user)
|
186
|
+
user.otp_secret_key = nil
|
187
|
+
user.save!
|
188
|
+
end
|
138
189
|
end
|
139
190
|
```
|
140
191
|
|
141
|
-
|
192
|
+
#### Adding the TOTP encryption option to an existing app
|
193
|
+
|
194
|
+
If you've already been using this gem, and want to start encrypting the OTP
|
195
|
+
secret key in the database (recommended), you'll need to perform the following
|
196
|
+
steps:
|
197
|
+
|
198
|
+
1. Generate a migration to add the necessary columns to your model's table:
|
199
|
+
|
200
|
+
```
|
201
|
+
rails g migration AddEncryptionFieldsToUsers encrypted_otp_secret_key:string:index encrypted_otp_secret_key_iv:string encrypted_otp_secret_key_salt:string
|
202
|
+
```
|
203
|
+
|
204
|
+
Open your migration file (it will be in the `db/migrate` directory and will be
|
205
|
+
named something like `20151230163930_add_encryption_fields_to_users.rb`), and
|
206
|
+
add `unique: true` to the `add_index` line so that it looks like this:
|
207
|
+
|
208
|
+
```ruby
|
209
|
+
add_index :users, :encrypted_otp_secret_key, unique: true
|
210
|
+
```
|
211
|
+
Save the file.
|
212
|
+
|
213
|
+
2. Run the migration: `bundle exec rake db:migrate`
|
214
|
+
|
215
|
+
2. Update the gem: `bundle update two_factor_authentication`
|
216
|
+
|
217
|
+
3. Add `encrypted: true` to `has_one_time_password` in your model.
|
218
|
+
For example: `has_one_time_password(encrypted: true)`
|
219
|
+
|
220
|
+
4. Generate a migration to populate the new encryption fields:
|
221
|
+
```
|
222
|
+
rails g migration PopulateEncryptedOtpFields
|
223
|
+
```
|
224
|
+
|
225
|
+
Open the generated file, and replace its contents with the following:
|
226
|
+
```ruby
|
227
|
+
class PopulateEncryptedOtpFields < ActiveRecord::Migration
|
228
|
+
def up
|
229
|
+
User.reset_column_information
|
230
|
+
|
231
|
+
User.find_each do |user|
|
232
|
+
user.otp_secret_key = user.read_attribute('otp_secret_key')
|
233
|
+
user.save!
|
234
|
+
end
|
235
|
+
end
|
236
|
+
|
237
|
+
def down
|
238
|
+
User.reset_column_information
|
239
|
+
|
240
|
+
User.find_each do |user|
|
241
|
+
user.otp_secret_key = ROTP::Base32.random_base32
|
242
|
+
user.save!
|
243
|
+
end
|
244
|
+
end
|
245
|
+
end
|
246
|
+
```
|
247
|
+
|
248
|
+
5. Generate a migration to remove the `:otp_secret_key` column:
|
249
|
+
```
|
250
|
+
rails g migration RemoveOtpSecretKeyFromUsers otp_secret_key:string
|
251
|
+
```
|
252
|
+
|
253
|
+
6. Run the migrations: `bundle exec rake db:migrate`
|
254
|
+
|
255
|
+
If, for some reason, you want to switch back to the old non-encrypted version,
|
256
|
+
use these steps:
|
257
|
+
|
258
|
+
1. Remove `(encrypted: true)` from `has_one_time_password`
|
259
|
+
|
260
|
+
2. Roll back the last 3 migrations (assuming you haven't added any new ones
|
261
|
+
after them):
|
262
|
+
```
|
263
|
+
bundle exec rake db:rollback STEP=3
|
264
|
+
```
|
265
|
+
|
266
|
+
#### Critical Security Note! Add before_action to your user registration controllers
|
267
|
+
|
268
|
+
You should have a file registrations_controller.rb in your controllers folder
|
269
|
+
to overwrite/customize user registrations. It should include the lines below, for 2FA protection of user model updates, meaning that users can only access the users/edit page after confirming 2FA fully, not simply by logging in. Otherwise the entire 2FA system can be bypassed!
|
270
|
+
|
271
|
+
```ruby
|
272
|
+
class RegistrationsController < Devise::RegistrationsController
|
273
|
+
before_action :confirm_two_factor_authenticated, except: [:new, :create, :cancel]
|
274
|
+
|
275
|
+
protected
|
276
|
+
|
277
|
+
def confirm_two_factor_authenticated
|
278
|
+
return if is_fully_authenticated?
|
279
|
+
|
280
|
+
flash[:error] = t('devise.errors.messages.user_not_authenticated')
|
281
|
+
redirect_to user_two_factor_authentication_url
|
282
|
+
end
|
283
|
+
end
|
284
|
+
```
|
285
|
+
|
286
|
+
#### Critical Security Note! Add 2FA validation to your custom user actions
|
287
|
+
|
288
|
+
Make sure you are passing the 2FA secret codes securely and checking for them upon critical user actions, such as API key updates, user email or pgp pubkey updates, or any other changess to private/secure account-related details. Validate the secret during the initial 2FA key/secret verification by the user also, of course.
|
289
|
+
|
290
|
+
For example, a simple account_controller.rb may look something like this:
|
291
|
+
|
292
|
+
```
|
293
|
+
require 'json'
|
294
|
+
|
295
|
+
class AccountController < ApplicationController
|
296
|
+
before_action :require_signed_in!
|
297
|
+
before_action :authenticate_user!
|
298
|
+
respond_to :html, :json
|
299
|
+
|
300
|
+
def account_API
|
301
|
+
resp = {}
|
302
|
+
begin
|
303
|
+
if(account_params["twoFAKey"] && account_params["twoFASecret"])
|
304
|
+
current_user.otp_secret_key = account_params["twoFAKey"]
|
305
|
+
if(current_user.authenticate_totp(account_params["twoFASecret"]))
|
306
|
+
# user has validated their temporary 2FA code, save it to their account, enable 2FA on this account
|
307
|
+
current_user.save!
|
308
|
+
resp['success'] = "passed 2FA validation!"
|
309
|
+
else
|
310
|
+
resp['error'] = "failed 2FA validation!"
|
311
|
+
end
|
312
|
+
elsif(param[:userAccountStuff] && param[:userAccountWidget])
|
313
|
+
#before updating important user account stuff and widgets,
|
314
|
+
#check to see that the 2FA secret has also been passed in, and verify it...
|
315
|
+
if(account_params["twoFASecret"] && current_user.totp_enabled? && current_user.authenticate_totp(account_params["twoFASecret"]))
|
316
|
+
# user has passed 2FA checks, do cool user account stuff here
|
317
|
+
...
|
318
|
+
else
|
319
|
+
# user failed 2FA check! No cool user stuff happens!
|
320
|
+
resp[error] = 'You failed 2FA validation!'
|
321
|
+
end
|
322
|
+
|
323
|
+
...
|
324
|
+
end
|
325
|
+
else
|
326
|
+
resp['error'] = 'unknown format error, not saved!'
|
327
|
+
end
|
328
|
+
rescue Exception => e
|
329
|
+
puts "WARNING: account api threw error : '#{e}' for user #{current_user.username}"
|
330
|
+
#print "error trace: #{e.backtrace}\n"
|
331
|
+
resp['error'] = "unanticipated server response"
|
332
|
+
end
|
333
|
+
render json: resp.to_json
|
334
|
+
end
|
335
|
+
|
336
|
+
def account_params
|
337
|
+
params.require(:twoFA).permit(:userAccountStuff, :userAcountWidget, :twoFAKey, :twoFASecret)
|
338
|
+
end
|
339
|
+
end
|
340
|
+
```
|
341
|
+
|
342
|
+
|
343
|
+
### Example App
|
142
344
|
|
143
345
|
[TwoFactorAuthenticationExample](https://github.com/Houdini/TwoFactorAuthenticationExample)
|
346
|
+
|
347
|
+
|
348
|
+
### Example user actions
|
349
|
+
|
350
|
+
to use an ENV VAR for the 2FA encryption key:
|
351
|
+
|
352
|
+
config.otp_secret_encryption_key = ENV['OTP_SECRET_ENCRYPTION_KEY']
|
353
|
+
|
354
|
+
to set up TOTP for Google Authenticator for user:
|
355
|
+
|
356
|
+
```
|
357
|
+
current_user.otp_secret_key = current_user.generate_totp_secret
|
358
|
+
current_user.save!
|
359
|
+
```
|
360
|
+
|
361
|
+
( encrypted db fields are set upon user model save action,
|
362
|
+
rails c access relies on setting env var: OTP_SECRET_ENCRYPTION_KEY )
|
363
|
+
|
364
|
+
to check if user has input the correct code (from the QR display page)
|
365
|
+
before saving the user model:
|
366
|
+
|
367
|
+
```
|
368
|
+
current_user.authenticate_totp('123456')
|
369
|
+
```
|
370
|
+
|
371
|
+
additional note:
|
372
|
+
|
373
|
+
```
|
374
|
+
current_user.otp_secret_key
|
375
|
+
```
|
376
|
+
|
377
|
+
This returns the OTP secret key in plaintext for the user (if you have set the env var) in the console
|
378
|
+
the string used for generating the QR given to the user for their Google Auth is something like:
|
379
|
+
|
380
|
+
otpauth://totp/LABEL?secret=p6wwetjnkjnrcmpd (example secret used here)
|
381
|
+
|
382
|
+
where LABEL should be something like "example.com (Username)", which shows up in their GA app to remind them the code is for example.com
|
383
|
+
|
384
|
+
this returns true or false with an allowed_otp_drift_seconds 'grace period'
|
385
|
+
|
386
|
+
to set TOTP to DISABLED for a user account:
|
387
|
+
|
388
|
+
```
|
389
|
+
current_user.second_factor_attempts_count=nil
|
390
|
+
current_user.encrypted_otp_secret_key=nil
|
391
|
+
current_user.encrypted_otp_secret_key_iv=nil
|
392
|
+
current_user.encrypted_otp_secret_key_salt=nil
|
393
|
+
current_user.direct_otp=nil
|
394
|
+
current_user.direct_otp_sent_at=nil
|
395
|
+
current_user.totp_timestamp=nil
|
396
|
+
current_user.direct_otp=nil
|
397
|
+
current_user.otp_secret_key=nil
|
398
|
+
current_user.otp_confirmed=nil
|
399
|
+
current_user.save! (if in ruby code instead of console)
|
400
|
+
current_user.direct_otp? => false
|
401
|
+
current_user.totp_enabled? => false
|
402
|
+
```
|
403
|
+
|
404
|
+
|
405
|
+
|
@@ -1,6 +1,8 @@
|
|
1
|
+
require 'devise/version'
|
2
|
+
|
1
3
|
class Devise::TwoFactorAuthenticationController < DeviseController
|
2
|
-
|
3
|
-
|
4
|
+
prepend_before_action :authenticate_scope!
|
5
|
+
before_action :prepare_and_validate, :handle_two_factor_authentication
|
4
6
|
|
5
7
|
def show
|
6
8
|
end
|
@@ -9,36 +11,74 @@ class Devise::TwoFactorAuthenticationController < DeviseController
|
|
9
11
|
render :show and return if params[:code].nil?
|
10
12
|
|
11
13
|
if resource.authenticate_otp(params[:code])
|
12
|
-
|
13
|
-
sign_in resource_name, resource, :bypass => true
|
14
|
-
set_flash_message :notice, :success
|
15
|
-
redirect_to stored_location_for(resource_name) || :root
|
16
|
-
resource.update_attribute(:second_factor_attempts_count, 0)
|
14
|
+
after_two_factor_success_for(resource)
|
17
15
|
else
|
18
|
-
resource
|
19
|
-
resource.save
|
20
|
-
flash.now[:error] = find_message(:attempt_failed)
|
21
|
-
if resource.max_login_attempts?
|
22
|
-
sign_out(resource)
|
23
|
-
render :max_login_attempts_reached
|
24
|
-
else
|
25
|
-
render :show
|
26
|
-
end
|
16
|
+
after_two_factor_fail_for(resource)
|
27
17
|
end
|
28
18
|
end
|
29
19
|
|
20
|
+
def resend_code
|
21
|
+
resource.send_new_otp
|
22
|
+
redirect_to send("#{resource_name}_two_factor_authentication_path"), notice: I18n.t('devise.two_factor_authentication.code_has_been_sent')
|
23
|
+
end
|
24
|
+
|
30
25
|
private
|
31
26
|
|
32
|
-
|
33
|
-
|
27
|
+
def after_two_factor_success_for(resource)
|
28
|
+
set_remember_two_factor_cookie(resource)
|
29
|
+
|
30
|
+
warden.session(resource_name)[TwoFactorAuthentication::NEED_AUTHENTICATION] = false
|
31
|
+
# For compatability with devise versions below v4.2.0
|
32
|
+
# https://github.com/plataformatec/devise/commit/2044fffa25d781fcbaf090e7728b48b65c854ccb
|
33
|
+
if respond_to?(:bypass_sign_in)
|
34
|
+
bypass_sign_in(resource, scope: resource_name)
|
35
|
+
else
|
36
|
+
sign_in(resource_name, resource, bypass: true)
|
34
37
|
end
|
38
|
+
set_flash_message :notice, :success
|
39
|
+
resource.update_attribute(:second_factor_attempts_count, 0)
|
35
40
|
|
36
|
-
|
37
|
-
|
38
|
-
|
39
|
-
|
40
|
-
|
41
|
-
|
42
|
-
|
41
|
+
redirect_to after_two_factor_success_path_for(resource)
|
42
|
+
end
|
43
|
+
|
44
|
+
def set_remember_two_factor_cookie(resource)
|
45
|
+
expires_seconds = resource.class.remember_otp_session_for_seconds
|
46
|
+
|
47
|
+
if expires_seconds && expires_seconds > 0
|
48
|
+
cookies.signed[TwoFactorAuthentication::REMEMBER_TFA_COOKIE_NAME] = {
|
49
|
+
value: "#{resource.class}-#{resource.public_send(Devise.second_factor_resource_id)}",
|
50
|
+
expires: expires_seconds.seconds.from_now
|
51
|
+
}
|
43
52
|
end
|
53
|
+
end
|
54
|
+
|
55
|
+
def after_two_factor_success_path_for(resource)
|
56
|
+
stored_location_for(resource_name) || :root
|
57
|
+
end
|
58
|
+
|
59
|
+
def after_two_factor_fail_for(resource)
|
60
|
+
resource.second_factor_attempts_count += 1
|
61
|
+
resource.save
|
62
|
+
set_flash_message :alert, :attempt_failed, now: true
|
63
|
+
|
64
|
+
if resource.max_login_attempts?
|
65
|
+
sign_out(resource)
|
66
|
+
render :max_login_attempts_reached
|
67
|
+
else
|
68
|
+
render :show
|
69
|
+
end
|
70
|
+
end
|
71
|
+
|
72
|
+
def authenticate_scope!
|
73
|
+
self.resource = send("current_#{resource_name}")
|
74
|
+
end
|
75
|
+
|
76
|
+
def prepare_and_validate
|
77
|
+
redirect_to :root and return if resource.nil?
|
78
|
+
@limit = resource.max_login_attempts
|
79
|
+
if resource.max_login_attempts?
|
80
|
+
sign_out(resource)
|
81
|
+
render :max_login_attempts_reached and return
|
82
|
+
end
|
83
|
+
end
|
44
84
|
end
|
@@ -1,4 +1,8 @@
|
|
1
|
-
|
1
|
+
<% if resource.direct_otp %>
|
2
|
+
<h2>Enter the code that was sent to you</h2>
|
3
|
+
<% else %>
|
4
|
+
<h2>Enter the code from your authenticator app</h2>
|
5
|
+
<% end %>
|
2
6
|
|
3
7
|
<p><%= flash[:notice] %></p>
|
4
8
|
|
@@ -7,4 +11,9 @@
|
|
7
11
|
<%= submit_tag "Submit" %>
|
8
12
|
<% end %>
|
9
13
|
|
10
|
-
|
14
|
+
<% if resource.direct_otp %>
|
15
|
+
<%= link_to "Resend Code", send("resend_code_#{resource_name}_two_factor_authentication_path"), action: :get %>
|
16
|
+
<% else %>
|
17
|
+
<%= link_to "Send me a code instead", send("resend_code_#{resource_name}_two_factor_authentication_path"), action: :get %>
|
18
|
+
<% end %>
|
19
|
+
<%= link_to "Sign out", send("destroy_#{resource_name}_session_path"), :method => :delete %>
|
data/config/locales/en.yml
CHANGED
@@ -0,0 +1,8 @@
|
|
1
|
+
es:
|
2
|
+
devise:
|
3
|
+
two_factor_authentication:
|
4
|
+
success: "Autenticación multi-factor realizada exitosamente."
|
5
|
+
attempt_failed: "La autenticación ha fallado."
|
6
|
+
max_login_attempts_reached: "Has llegado al límite de intentos fallidos, acceso denegado."
|
7
|
+
contact_administrator: "Contacte a su administrador de sistema."
|
8
|
+
code_has_been_sent: "El código de autenticación ha sido enviado."
|
@@ -0,0 +1,8 @@
|
|
1
|
+
fr:
|
2
|
+
devise:
|
3
|
+
two_factor_authentication:
|
4
|
+
success: "Validation en deux étapes effectuée avec succès."
|
5
|
+
attempt_failed: "La connexion a échoué."
|
6
|
+
max_login_attempts_reached: "Limite de tentatives atteinte, accès refusé."
|
7
|
+
contact_administrator: "Merci de contacter votre administrateur système."
|
8
|
+
code_has_been_sent: "Votre code de validation envoyé."
|
data/config/locales/ru.yml
CHANGED
@@ -1,15 +1,13 @@
|
|
1
1
|
class TwoFactorAuthenticationAddTo<%= table_name.camelize %> < ActiveRecord::Migration
|
2
|
-
def
|
3
|
-
|
4
|
-
|
5
|
-
|
6
|
-
|
2
|
+
def change
|
3
|
+
add_column :<%= table_name %>, :second_factor_attempts_count, :integer, default: 0
|
4
|
+
add_column :<%= table_name %>, :encrypted_otp_secret_key, :string
|
5
|
+
add_column :<%= table_name %>, :encrypted_otp_secret_key_iv, :string
|
6
|
+
add_column :<%= table_name %>, :encrypted_otp_secret_key_salt, :string
|
7
|
+
add_column :<%= table_name %>, :direct_otp, :string
|
8
|
+
add_column :<%= table_name %>, :direct_otp_sent_at, :datetime
|
9
|
+
add_column :<%= table_name %>, :totp_timestamp, :timestamp
|
7
10
|
|
8
|
-
add_index :<%= table_name %>, :
|
9
|
-
end
|
10
|
-
|
11
|
-
def down
|
12
|
-
remove_column :<%= table_name %>, :otp_secret_key
|
13
|
-
remove_column :<%= table_name %>, :second_factor_attempts_count
|
11
|
+
add_index :<%= table_name %>, :encrypted_otp_secret_key, unique: true
|
14
12
|
end
|
15
13
|
end
|
@@ -4,7 +4,7 @@ module TwoFactorAuthentication
|
|
4
4
|
extend ActiveSupport::Concern
|
5
5
|
|
6
6
|
included do
|
7
|
-
|
7
|
+
before_action :handle_two_factor_authentication
|
8
8
|
end
|
9
9
|
|
10
10
|
private
|
@@ -21,10 +21,10 @@ module TwoFactorAuthentication
|
|
21
21
|
|
22
22
|
def handle_failed_second_factor(scope)
|
23
23
|
if request.format.present? and request.format.html?
|
24
|
-
session["#{scope}_return_to"] =
|
24
|
+
session["#{scope}_return_to"] = request.original_fullpath if request.get?
|
25
25
|
redirect_to two_factor_authentication_path_for(scope)
|
26
26
|
else
|
27
|
-
|
27
|
+
head :unauthorized
|
28
28
|
end
|
29
29
|
end
|
30
30
|
|