Compare commits

..

4 Commits

Author SHA1 Message Date
Dmitrii Golub 7e77b61311 Merge pull request #10 from ilanstern/master 12 years ago
Ilan f2280eb620 Merge pull request #1 from ilanstern/for_activeadmin 12 years ago
Ilan 865e27c125 Update show.html.erb 12 years ago
Dmitrii Golub e398f0977f hardcoded activeadmin stuff 12 years ago
  1. 42
      .github/workflows/tests.yml
  2. 3
      .gitignore
  3. 293
      .rubocop.yml
  4. 119
      CHANGELOG.md
  5. 33
      Gemfile
  6. 385
      README.md
  7. 17
      Rakefile
  8. 101
      app/controllers/devise/two_factor_authentication_controller.rb
  9. 4
      app/views/devise/two_factor_authentication/max_login_attempts_reached.html.erb
  10. 15
      app/views/devise/two_factor_authentication/show.html.erb
  11. 8
      config/locales/de.yml
  12. 4
      config/locales/en.yml
  13. 8
      config/locales/es.yml
  14. 8
      config/locales/fr.yml
  15. 8
      config/locales/ru.yml
  16. 52
      lib/devise_two_factor_authentication.rb
  17. 54
      lib/devise_two_factor_authentication/controllers/helpers.rb
  18. 17
      lib/devise_two_factor_authentication/hooks/two_factor_authenticatable.rb
  19. 206
      lib/devise_two_factor_authentication/models/two_factor_authenticatable.rb
  20. 14
      lib/devise_two_factor_authentication/orm/active_record.rb
  21. 7
      lib/devise_two_factor_authentication/rails.rb
  22. 19
      lib/devise_two_factor_authentication/routes.rb
  23. 31
      lib/devise_two_factor_authentication/schema.rb
  24. 3
      lib/devise_two_factor_authentication/version.rb
  25. 15
      lib/generators/active_record/templates/migration.rb
  26. 2
      lib/generators/active_record/two_factor_authentication_generator.rb
  27. 27
      lib/two_factor_authentication.rb
  28. 41
      lib/two_factor_authentication/controllers/helpers.rb
  29. 10
      lib/two_factor_authentication/hooks/two_factor_authenticatable.rb
  30. 28
      lib/two_factor_authentication/models/two_factor_authenticatable.rb
  31. 12
      lib/two_factor_authentication/orm/active_record.rb
  32. 7
      lib/two_factor_authentication/rails.rb
  33. 9
      lib/two_factor_authentication/routes.rb
  34. 11
      lib/two_factor_authentication/schema.rb
  35. 3
      lib/two_factor_authentication/version.rb
  36. 41
      spec/controllers/two_factor_authentication_controller_spec.rb
  37. 236
      spec/features/two_factor_authenticatable_spec.rb
  38. 36
      spec/generators/active_record/two_factor_authentication_generator_spec.rb
  39. 326
      spec/lib/two_factor_authentication/models/two_factor_authenticatable_spec.rb
  40. 3
      spec/rails_app/.gitignore
  41. 3
      spec/rails_app/README.md
  42. 9
      spec/rails_app/Rakefile
  43. 2
      spec/rails_app/app/assets/config/manifest.js
  44. 1
      spec/rails_app/app/assets/javascripts/application.js
  45. 4
      spec/rails_app/app/assets/stylesheets/application.css
  46. 3
      spec/rails_app/app/controllers/application_controller.rb
  47. 10
      spec/rails_app/app/controllers/home_controller.rb
  48. 8
      spec/rails_app/app/helpers/application_helper.rb
  49. 0
      spec/rails_app/app/mailers/.gitkeep
  50. 0
      spec/rails_app/app/models/.gitkeep
  51. 6
      spec/rails_app/app/models/admin.rb
  52. 15
      spec/rails_app/app/models/encrypted_user.rb
  53. 17
      spec/rails_app/app/models/guest_user.rb
  54. 14
      spec/rails_app/app/models/user.rb
  55. 11
      spec/rails_app/app/views/home/dashboard.html.erb
  56. 3
      spec/rails_app/app/views/home/index.html.erb
  57. 20
      spec/rails_app/app/views/layouts/application.html.erb
  58. 4
      spec/rails_app/config.ru
  59. 64
      spec/rails_app/config/application.rb
  60. 10
      spec/rails_app/config/boot.rb
  61. 19
      spec/rails_app/config/database.yml
  62. 5
      spec/rails_app/config/environment.rb
  63. 28
      spec/rails_app/config/environments/development.rb
  64. 68
      spec/rails_app/config/environments/production.rb
  65. 41
      spec/rails_app/config/environments/test.rb
  66. 7
      spec/rails_app/config/initializers/backtrace_silencers.rb
  67. 3
      spec/rails_app/config/initializers/cookies_serializer.rb
  68. 258
      spec/rails_app/config/initializers/devise.rb
  69. 15
      spec/rails_app/config/initializers/inflections.rb
  70. 5
      spec/rails_app/config/initializers/mime_types.rb
  71. 7
      spec/rails_app/config/initializers/secret_token.rb
  72. 8
      spec/rails_app/config/initializers/session_store.rb
  73. 14
      spec/rails_app/config/initializers/wrap_parameters.rb
  74. 59
      spec/rails_app/config/locales/devise.en.yml
  75. 5
      spec/rails_app/config/locales/en.yml
  76. 65
      spec/rails_app/config/routes.rb
  77. 42
      spec/rails_app/db/migrate/20140403184646_devise_create_users.rb
  78. 15
      spec/rails_app/db/migrate/20140407172619_two_factor_authentication_add_to_users.rb
  79. 7
      spec/rails_app/db/migrate/20140407215513_add_nickanme_to_users.rb
  80. 9
      spec/rails_app/db/migrate/20151224171231_add_encrypted_columns_to_user.rb
  81. 19
      spec/rails_app/db/migrate/20151224180310_populate_otp_column.rb
  82. 5
      spec/rails_app/db/migrate/20151228230340_remove_otp_secret_key_from_user.rb
  83. 42
      spec/rails_app/db/migrate/20160209032439_devise_create_admins.rb
  84. 54
      spec/rails_app/db/schema.rb
  85. 0
      spec/rails_app/lib/assets/.gitkeep
  86. 17
      spec/rails_app/lib/sms_provider.rb
  87. 26
      spec/rails_app/public/404.html
  88. 26
      spec/rails_app/public/422.html
  89. 25
      spec/rails_app/public/500.html
  90. 0
      spec/rails_app/public/favicon.ico
  91. 9
      spec/rails_app/script/rails
  92. 27
      spec/spec_helper.rb
  93. 59
      spec/support/authenticated_model_helper.rb
  94. 3
      spec/support/capybara.rb
  95. 16
      spec/support/controller_helper.rb
  96. 42
      spec/support/features_spec_helper.rb
  97. 5
      spec/support/sms_provider.rb
  98. 11
      spec/support/totp_helper.rb
  99. 24
      two_factor_authentication.gemspec

42
.github/workflows/tests.yml

@ -1,42 +0,0 @@
name: 'CI/CD Pipeline'
on:
push:
branches:
- master
pull_request:
workflow_dispatch:
defaults:
run:
shell: bash
jobs:
test:
name: Test
runs-on: ubuntu-latest
env:
RAILS_ENV: test
GEMFILE_RUBY_VERSION: 3.0.3
# Rails verifies the time zone in DB is the same as the time zone of the Rails app
TZ: "Europe/London"
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Set up Ruby
uses: ruby/setup-ruby@v1
with:
ruby-version: 3.0.3
# runs 'bundle install' and caches installed gems automatically
bundler-cache: true
- name: Run tests
run: |
bundle exec rake spec

3
.gitignore vendored

@ -18,6 +18,3 @@ patches-*
capybara-*.html capybara-*.html
dump.rdb dump.rdb
*.ids *.ids
.rbenv-version
.ruby-gemset
.ruby-version

293
.rubocop.yml

@ -1,293 +0,0 @@
AllCops:
Include:
- '**/Gemfile'
- '**/Rakefile'
UseCache: true
Layout/LineLength:
Description: Limit lines to 80 characters.
StyleGuide: https://github.com/bbatsov/ruby-style-guide#80-character-limits
Enabled: true
Max: 100
AllowURI: true
URISchemes:
- http
- https
Layout/DotPosition:
Description: Checks the position of the dot in multi-line method calls.
StyleGuide: https://github.com/bbatsov/ruby-style-guide#consistent-multi-line-chains
Enabled: true
EnforcedStyle: trailing
SupportedStyles:
- leading
- trailing
Lint/AssignmentInCondition:
Description: Don't use assignment in conditions.
StyleGuide: https://github.com/bbatsov/ruby-style-guide#safe-assignment-in-condition
Enabled: true
AllowSafeAssignment: true
Lint/EachWithObjectArgument:
Description: Check for immutable argument given to each_with_object.
Enabled: true
Lint/SuppressedException:
Description: Don't suppress exception.
StyleGuide: https://github.com/bbatsov/ruby-style-guide#dont-hide-exceptions
Enabled: true
Lint/LiteralAsCondition:
Description: Checks of literals used in conditions.
Enabled: true
Lint/LiteralInInterpolation:
Description: Checks for literals used in interpolation.
Enabled: true
Lint/ParenthesesAsGroupedExpression:
Description: Checks for method calls with a space before the opening parenthesis.
StyleGuide: https://github.com/bbatsov/ruby-style-guide#parens-no-spaces
Enabled: true
Metrics/AbcSize:
Description: A calculated magnitude based on number of assignments, branches, and
conditions.
Enabled: true
Max: 15
Exclude:
- spec/**/*
Metrics/ClassLength:
Description: Avoid classes longer than 100 lines of code.
Enabled: true
CountComments: false
Max: 100
Exclude:
- spec/**/*
Metrics/CyclomaticComplexity:
Description: A complexity metric that is strongly correlated to the number of test
cases needed to validate a method.
Enabled: true
Max: 6
Metrics/MethodLength:
Description: Avoid methods longer than 10 lines of code.
StyleGuide: https://github.com/bbatsov/ruby-style-guide#short-methods
Enabled: true
CountComments: false
Max: 10
Exclude:
- spec/**/*
Metrics/ModuleLength:
CountComments: false
Max: 100
Description: Avoid modules longer than 100 lines of code.
Enabled: true
Exclude:
- spec/**/*
Metrics/ParameterLists:
Description: Avoid parameter lists longer than three or four parameters.
StyleGuide: https://github.com/bbatsov/ruby-style-guide#too-many-params
Enabled: true
Max: 5
CountKeywordArgs: true
Metrics/PerceivedComplexity:
Description: A complexity metric geared towards measuring complexity for a human
reader.
Enabled: true
Max: 7
Naming/AccessorMethodName:
Description: Check the naming of accessor methods for get_/set_.
Enabled: false
Naming/FileName:
Description: Use snake_case for source file names.
StyleGuide: https://github.com/bbatsov/ruby-style-guide#snake-case-files
Enabled: true
Exclude: []
Naming/PredicateName:
Description: Check the names of predicate methods.
StyleGuide: https://github.com/bbatsov/ruby-style-guide#bool-methods-qmark
Enabled: true
NamePrefix:
- is_
- has_
- have_
ForbiddenPrefixes:
- is_
Exclude:
- spec/**/*
Style/AndOr:
Description: Use &&/|| instead of and/or.
StyleGuide: https://github.com/bbatsov/ruby-style-guide#no-and-or-or
Enabled: true
EnforcedStyle: conditionals
SupportedStyles:
- always
- conditionals
Style/Alias:
Description: Use alias_method instead of alias.
StyleGuide: https://github.com/bbatsov/ruby-style-guide#alias-method
Enabled: true
Style/ClassAndModuleChildren:
EnforcedStyle: nested
SupportedStyles:
- nested
- compact
Style/CollectionMethods:
Description: Preferred collection methods.
StyleGuide: https://github.com/bbatsov/ruby-style-guide#map-find-select-reduce-size
Enabled: true
PreferredMethods:
collect: map
collect!: map!
find: detect
find_all: select
reduce: inject
Style/Documentation:
Description: Document classes and non-namespace modules.
Enabled: false
Style/DoubleNegation:
Description: Checks for uses of double negation (!!).
StyleGuide: https://github.com/bbatsov/ruby-style-guide#no-bang-bang
Enabled: true
Style/EachWithObject:
Description: Prefer `each_with_object` over `inject` or `reduce`.
Enabled: true
Style/EmptyLiteral:
Description: Prefer literals to Array.new/Hash.new/String.new.
StyleGuide: https://github.com/bbatsov/ruby-style-guide#literal-array-hash
Enabled: true
Style/GuardClause:
Description: Check for conditionals that can be replaced with guard clauses
StyleGuide: https://github.com/bbatsov/ruby-style-guide#no-nested-conditionals
Enabled: true
MinBodyLength: 1
Style/IfUnlessModifier:
Description: Favor modifier if/unless usage when you have a single-line body.
StyleGuide: https://github.com/bbatsov/ruby-style-guide#if-as-a-modifier
Enabled: false
Style/InlineComment:
Description: Avoid inline comments.
Enabled: false
Style/ModuleFunction:
Description: Checks for usage of `extend self` in modules.
StyleGuide: https://github.com/bbatsov/ruby-style-guide#module-function
Enabled: false
Style/OneLineConditional:
Description: Favor the ternary operator(?:) over if/then/else/end constructs.
StyleGuide: https://github.com/bbatsov/ruby-style-guide#ternary-operator
Enabled: false
Style/OptionHash:
Description: Don't use option hashes when you can use keyword arguments.
Enabled: false
Style/PercentLiteralDelimiters:
Description: Use `%`-literal delimiters consistently
StyleGuide: https://github.com/bbatsov/ruby-style-guide#percent-literal-braces
Enabled: true
PreferredDelimiters:
"%": "()"
"%i": "()"
"%q": "()"
"%Q": "()"
"%r": "{}"
"%s": "()"
"%w": "()"
"%W": "()"
"%x": "()"
Style/PerlBackrefs:
Description: Avoid Perl-style regex back references.
StyleGuide: https://github.com/bbatsov/ruby-style-guide#no-perl-regexp-last-matchers
Enabled: false
Style/RaiseArgs:
Description: Checks the arguments passed to raise/fail.
StyleGuide: https://github.com/bbatsov/ruby-style-guide#exception-class-messages
Enabled: true
EnforcedStyle: exploded
SupportedStyles:
- compact
- exploded
Style/Send:
Description: Prefer `Object#__send__` or `Object#public_send` to `send`, as `send`
may overlap with existing methods.
StyleGuide: https://github.com/bbatsov/ruby-style-guide#prefer-public-send
Enabled: false
Style/SignalException:
Description: Checks for proper usage of fail and raise.
StyleGuide: https://github.com/bbatsov/ruby-style-guide#fail-method
Enabled: true
EnforcedStyle: semantic
SupportedStyles:
- only_raise
- only_fail
- semantic
Style/SingleLineBlockParams:
Description: Enforces the names of some block params.
StyleGuide: https://github.com/bbatsov/ruby-style-guide#reduce-blocks
Enabled: true
Methods:
- reduce:
- a
- e
- inject:
- a
- e
Style/SingleLineMethods:
Description: Avoid single-line methods.
StyleGuide: https://github.com/bbatsov/ruby-style-guide#no-single-line-methods
Enabled: true
AllowIfMethodIsEmpty: true
Style/SpecialGlobalVars:
Description: Avoid Perl-style global variables.
StyleGuide: https://github.com/bbatsov/ruby-style-guide#no-cryptic-perlisms
Enabled: false
Style/StringLiterals:
Description: Checks if uses of quotes match the configured preference.
StyleGuide: https://github.com/bbatsov/ruby-style-guide#consistent-string-literals
Enabled: true
EnforcedStyle: single_quotes
SupportedStyles:
- single_quotes
- double_quotes
Style/StringLiteralsInInterpolation:
Description: Checks if uses of quotes inside expressions in interpolated strings
match the configured preference.
Enabled: true
EnforcedStyle: single_quotes
SupportedStyles:
- single_quotes
- double_quotes
Style/TrailingCommaInArguments:
Description: 'Checks for trailing comma in argument lists.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-trailing-array-commas'
Enabled: true
EnforcedStyleForMultiline: no_comma
SupportedStyles:
- comma
- consistent_comma
- no_comma
Style/TrailingCommaInArrayLiteral:
Description: 'Checks for trailing comma in array and hash literals.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-trailing-array-commas'
Enabled: true
EnforcedStyleForMultiline: no_comma
SupportedStyles:
- comma
- consistent_comma
- no_comma
Style/TrailingCommaInHashLiteral:
Description: 'Checks for trailing comma in array and hash literals.'
StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-trailing-array-commas'
Enabled: true
EnforcedStyleForMultiline: no_comma
SupportedStyles:
- comma
- consistent_comma
- no_comma
Style/VariableInterpolation:
Description: Don't interpolate global, instance and class variables directly in
strings.
StyleGuide: https://github.com/bbatsov/ruby-style-guide#curlies-interpolate
Enabled: false
Style/WhenThen:
Description: Use when x then ... for one-line cases.
StyleGuide: https://github.com/bbatsov/ruby-style-guide#one-line-cases
Enabled: false
Style/ZeroLengthPredicate:
Description: 'Use #empty? when testing for objects of length 0.'
Enabled: true

119
CHANGELOG.md

@ -1,119 +0,0 @@
# Change Log
## [Unreleased](https://github.com/Houdini/two_factor_authentication/tree/HEAD)
[Full Changelog](https://github.com/Houdini/two_factor_authentication/compare/v1.1.5...HEAD)
**Merged pull requests:**
- Fix class detection in reset\_otp\_state\_for\(user\) [\#69](https://github.com/Houdini/two_factor_authentication/pull/69) ([monfresh](https://github.com/monfresh))
- Add ability to resend code [\#52](https://github.com/Houdini/two_factor_authentication/pull/52) ([iDiogenes](https://github.com/iDiogenes))
## [v1.1.5](https://github.com/Houdini/two_factor_authentication/tree/v1.1.5) (2016-02-01)
[Full Changelog](https://github.com/Houdini/two_factor_authentication/compare/v1.1.4...v1.1.5)
**Closed issues:**
- How should I integrate Devise two factor authentication with custom sessions controller? [\#60](https://github.com/Houdini/two_factor_authentication/issues/60)
**Merged pull requests:**
- added french translation [\#68](https://github.com/Houdini/two_factor_authentication/pull/68) ([qsypoq](https://github.com/qsypoq))
- Drop support for Ruby 1.9.3 & update .travis.yml [\#67](https://github.com/Houdini/two_factor_authentication/pull/67) ([monfresh](https://github.com/monfresh))
- Fix reset\_otp\_state specs [\#66](https://github.com/Houdini/two_factor_authentication/pull/66) ([monfresh](https://github.com/monfresh))
- Add a CHANGELOG.md [\#65](https://github.com/Houdini/two_factor_authentication/pull/65) ([monfresh](https://github.com/monfresh))
- Update bundler on Travis before installing gems [\#63](https://github.com/Houdini/two_factor_authentication/pull/63) ([monfresh](https://github.com/monfresh))
- Add support for OTP secret key encryption [\#62](https://github.com/Houdini/two_factor_authentication/pull/62) ([monfresh](https://github.com/monfresh))
- Allow executing code after sign in and before sign out [\#61](https://github.com/Houdini/two_factor_authentication/pull/61) ([monfresh](https://github.com/monfresh))
## [v1.1.4](https://github.com/Houdini/two_factor_authentication/tree/v1.1.4) (2016-01-01)
[Full Changelog](https://github.com/Houdini/two_factor_authentication/compare/v1.1.3...v1.1.4)
**Closed issues:**
- Old OTP can be used after a new one has been generated [\#59](https://github.com/Houdini/two_factor_authentication/issues/59)
- Do we have any two\_factor\_method like authenticate\_user! [\#58](https://github.com/Houdini/two_factor_authentication/issues/58)
- Configuration [\#57](https://github.com/Houdini/two_factor_authentication/issues/57)
**Merged pull requests:**
- Abstract logic for two factor success and fail into separate methods.… [\#56](https://github.com/Houdini/two_factor_authentication/pull/56) ([kpheasey](https://github.com/kpheasey))
- Move require rotp library to the file where it is used [\#55](https://github.com/Houdini/two_factor_authentication/pull/55) ([gkopylov](https://github.com/gkopylov))
- Add support for remembering a user's 2FA session in a cookie [\#54](https://github.com/Houdini/two_factor_authentication/pull/54) ([boffbowsh](https://github.com/boffbowsh))
- Test against Ruby 2.2 and Rails 4.2 [\#53](https://github.com/Houdini/two_factor_authentication/pull/53) ([boffbowsh](https://github.com/boffbowsh))
- Eliminates appended '?' to redirects that have no query string [\#46](https://github.com/Houdini/two_factor_authentication/pull/46) ([daveriess](https://github.com/daveriess))
## [v1.1.3](https://github.com/Houdini/two_factor_authentication/tree/v1.1.3) (2014-12-14)
[Full Changelog](https://github.com/Houdini/two_factor_authentication/compare/v1.1.2...v1.1.3)
**Closed issues:**
- rails g two\_factor\_authentication MODEL does not append .rb to end of migration [\#40](https://github.com/Houdini/two_factor_authentication/issues/40)
**Merged pull requests:**
- Allows length of OTP to be configured [\#44](https://github.com/Houdini/two_factor_authentication/pull/44) ([amoose](https://github.com/amoose))
- Missing translation. [\#43](https://github.com/Houdini/two_factor_authentication/pull/43) ([sadfuzzy](https://github.com/sadfuzzy))
- Preserve query parameters in \_return\_to for redirect. [\#42](https://github.com/Houdini/two_factor_authentication/pull/42) ([omb-awong](https://github.com/omb-awong))
- Add file extension to ActiveRecord generator [\#41](https://github.com/Houdini/two_factor_authentication/pull/41) ([jackturnbull](https://github.com/jackturnbull))
## [v1.1.2](https://github.com/Houdini/two_factor_authentication/tree/v1.1.2) (2014-07-14)
[Full Changelog](https://github.com/Houdini/two_factor_authentication/compare/v1.1.1...v1.1.2)
**Closed issues:**
- NoMethodError \(undefined method `scan' for nil:NilClass\) [\#37](https://github.com/Houdini/two_factor_authentication/issues/37)
**Merged pull requests:**
- Updated readme with rake task to update existing users with OTP secret k... [\#39](https://github.com/Houdini/two_factor_authentication/pull/39) ([Znow](https://github.com/Znow))
- Updated readme with view overriding [\#38](https://github.com/Houdini/two_factor_authentication/pull/38) ([Znow](https://github.com/Znow))
## [v1.1.1](https://github.com/Houdini/two_factor_authentication/tree/v1.1.1) (2014-05-31)
[Full Changelog](https://github.com/Houdini/two_factor_authentication/compare/v1.1...v1.1.1)
**Closed issues:**
- Override views [\#36](https://github.com/Houdini/two_factor_authentication/issues/36)
- NoMethodError in Devise::TwoFactorAuthenticationController\#update [\#30](https://github.com/Houdini/two_factor_authentication/issues/30)
**Merged pull requests:**
- Use Strings and not Symbols for keys when storing variable in warden session [\#35](https://github.com/Houdini/two_factor_authentication/pull/35) ([karolsarnacki](https://github.com/karolsarnacki))
- Chore/extract reused hash key [\#34](https://github.com/Houdini/two_factor_authentication/pull/34) ([rud](https://github.com/rud))
- Pad OTP codes with less than 6 digits [\#31](https://github.com/Houdini/two_factor_authentication/pull/31) ([brissmyr](https://github.com/brissmyr))
## [v1.1](https://github.com/Houdini/two_factor_authentication/tree/v1.1) (2014-04-16)
**Closed issues:**
- Update [\#15](https://github.com/Houdini/two_factor_authentication/issues/15)
- Data in formats other than HTML left unprotected [\#6](https://github.com/Houdini/two_factor_authentication/issues/6)
- Wordlists [\#5](https://github.com/Houdini/two_factor_authentication/issues/5)
- devise - wrong number of arguments \(1 for 0\) [\#3](https://github.com/Houdini/two_factor_authentication/issues/3)
- gem? [\#1](https://github.com/Houdini/two_factor_authentication/issues/1)
**Merged pull requests:**
- added is\_fully\_authenticated helper for current version [\#28](https://github.com/Houdini/two_factor_authentication/pull/28) ([edg3r](https://github.com/edg3r))
- Adds integration spec to ensure authentication code is sent on sign in [\#27](https://github.com/Houdini/two_factor_authentication/pull/27) ([rossta](https://github.com/rossta))
- ensure return\_to location is properly stored [\#26](https://github.com/Houdini/two_factor_authentication/pull/26) ([rossta](https://github.com/rossta))
- travis badge in README [\#25](https://github.com/Houdini/two_factor_authentication/pull/25) ([rossta](https://github.com/rossta))
- Integration specs [\#24](https://github.com/Houdini/two_factor_authentication/pull/24) ([rossta](https://github.com/rossta))
- README updates [\#23](https://github.com/Houdini/two_factor_authentication/pull/23) ([rossta](https://github.com/rossta))
- extract method \#max\_login\_attempts [\#22](https://github.com/Houdini/two_factor_authentication/pull/22) ([rossta](https://github.com/rossta))
- extract method \#populate\_otp\_column [\#21](https://github.com/Houdini/two_factor_authentication/pull/21) ([rossta](https://github.com/rossta))
- specs for Model\#provisioning\_uri [\#20](https://github.com/Houdini/two_factor_authentication/pull/20) ([rossta](https://github.com/rossta))
- Provide options for \#provisioning\_uri [\#19](https://github.com/Houdini/two_factor_authentication/pull/19) ([rossta](https://github.com/rossta))
- Use time-based authentication codes [\#16](https://github.com/Houdini/two_factor_authentication/pull/16) ([mattmueller](https://github.com/mattmueller))
- Add ru locales and locales for max\_limit\_reached view [\#13](https://github.com/Houdini/two_factor_authentication/pull/13) ([edg3r](https://github.com/edg3r))
- Update README.md [\#11](https://github.com/Houdini/two_factor_authentication/pull/11) ([edg3r](https://github.com/edg3r))
- Changed route from user to admin\_user [\#10](https://github.com/Houdini/two_factor_authentication/pull/10) ([ilanstern](https://github.com/ilanstern))
- Changed :notice to :error when setting flash message on attempt failure. [\#9](https://github.com/Houdini/two_factor_authentication/pull/9) ([johnmichaelbradley](https://github.com/johnmichaelbradley))
- Typo and punctuation corrections. [\#8](https://github.com/Houdini/two_factor_authentication/pull/8) ([johnmichaelbradley](https://github.com/johnmichaelbradley))
- Respond with 401 for request non-HTML requests [\#7](https://github.com/Houdini/two_factor_authentication/pull/7) ([WojtekKruszewski](https://github.com/WojtekKruszewski))
- need\_two\_factor\_authentication? method should accept request param. [\#4](https://github.com/Houdini/two_factor_authentication/pull/4) ([VladimirMikhailov](https://github.com/VladimirMikhailov))
- Add generators to make it easier to install and fix deprecation warnings [\#2](https://github.com/Houdini/two_factor_authentication/pull/2) ([carvil](https://github.com/carvil))
\* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)*

33
Gemfile

@ -1,35 +1,4 @@
# frozen_string_literal: true source "http://rubygems.org"
source 'https://rubygems.org'
# Specify your gem's dependencies in devise_ip_filter.gemspec # Specify your gem's dependencies in devise_ip_filter.gemspec
gemspec gemspec
rails_version = ENV['RAILS_VERSION'] || 'default'
rails = case rails_version
when 'master'
{ github: 'rails/rails' }
when 'default'
'~> 7.0.1'
else
"~> #{rails_version}"
end
gem 'rails', rails
if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new('2.2.0')
gem 'test-unit', '~> 3.0'
end
group :test, :development do
gem 'pry'
gem 'rubocop'
gem 'sprockets-rails'
gem 'sqlite3'
end
group :test do
gem 'ammeter'
gem 'rack_session_access'
end

385
README.md

@ -1,20 +1,11 @@
# Two factor authentication for Devise ## Two factor authentication for Devise
[![Build Status](https://github.com/devise2fa/two_factor_authentication/actions/workflows/tests.yml/badge.svg?branch=master&event=push)](https://github.com/baarkerlounger/two_factor_authentication/actions/workflows/tests.yml)
This is a fork of [Houdini/two_factor_authentication](https://github.com/Houdini/two_factor_authentication) to enable development to continue as that repository no longer seems to be actively developed. With thanks to all contributors.
## Features ## Features
* Support for 2 types of OTP codes * control sms code pattern
1. Codes delivered directly to the user * configure max login attempts
2. TOTP (Google Authenticator) codes based on a shared secret (HMAC) * per user level control if he really need two factor authentication
* Configurable OTP code digit length * your own sms logic
* Configurable max login attempts
* Customizable logic to determine if a user needs two factor authentication
* Configurable period where users won't be asked for 2FA again
* Option to encrypt the TOTP secret in the database, with iv and salt
## Configuration ## Configuration
@ -28,374 +19,72 @@ Once that's done, run:
bundle install bundle install
Note that Ruby 2.1 or greater is required.
### Installation ### Automatic installation
#### Automatic initial setup In order to add two factor authorisation to a model, run the command:
To set up the model and database migration file automatically, run the
following command:
bundle exec rails g two_factor_authentication MODEL bundle exec rails g two_factor_authentication MODEL
Where MODEL is your model name (e.g. User or Admin). This generator will add Where MODEL is your model name (e.g. User or Admin). This generator will add `:two_factor_authenticatable` to your model
`:two_factor_authenticatable` to your model's Devise options and create a and create a migration in `db/migrate/`, which will add `::second_factor_pass_code` and `:second_factor_attempts_count` to your table.
migration in `db/migrate/`, which will add the following columns to your table: Finally, run the migration with:
- `:second_factor_attempts_count`
- `:encrypted_otp_secret_key`
- `:encrypted_otp_secret_key_iv`
- `:encrypted_otp_secret_key_salt`
- `:direct_otp`
- `:direct_otp_sent_at`
- `:totp_timestamp`
#### Manual initial setup
If you prefer to set up the model and migration manually, add the
`:two_factor_authenticatable` option to your existing devise options, such as:
```ruby
devise :database_authenticatable, :registerable, :recoverable, :rememberable,
:trackable, :validatable, :two_factor_authenticatable
```
Then create your migration file using the Rails generator, such as:
```
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
```
Open your migration file (it will be in the `db/migrate` directory and will be
named something like `20151230163930_add_two_factor_fields_to_users.rb`), and
add `unique: true` to the `add_index` line so that it looks like this:
```ruby
add_index :users, :encrypted_otp_secret_key, unique: true
```
Save the file.
#### Complete the setup
Run the migration with:
bundle exec rake db:migrate bundle exec rake db:migrate
Add the following line to your model to fully enable two-factor auth:
has_one_time_password(encrypted: true) ### Manual installation
Set config values in `config/initializers/devise.rb`: To manually enable two factor authentication for the User model, you should add two_factor_authentication to your devise line, like:
```ruby ```ruby
config.max_login_attempts = 3 # Maximum second factor attempts count. devise :database_authenticatable, :registerable,
config.allowed_otp_drift_seconds = 30 # Allowed TOTP time drift between client and server. :recoverable, :rememberable, :trackable, :validatable, :two_factor_authenticatable
config.otp_length = 6 # TOTP code length
config.direct_otp_valid_for = 5.minutes # Time before direct OTP becomes invalid
config.direct_otp_length = 6 # Direct OTP code length
config.remember_otp_session_for_seconds = 30.days # Time before browser has to perform 2fA again. Default is 0.
config.otp_secret_encryption_key = ENV['OTP_SECRET_ENCRYPTION_KEY']
config.second_factor_resource_id = 'id' # Field or method name used to set value for 2fA remember cookie
config.delete_cookie_on_logout = false # Delete cookie when user signs out, to force 2fA again on login
``` ```
The `otp_secret_encryption_key` must be a random key that is not stored in the
DB, and is not checked in to your repo. It is recommended to store it in an
environment variable, and you can generate it with `bundle exec rake secret`.
Override the method in your model in order to send direct OTP codes. This is Two default parameters
automatically called when a user logs in unless they have TOTP enabled (see
below):
```ruby ```ruby
def send_two_factor_authentication_code(code) config.login_code_random_pattern = /\w+/
# Send code via SMS, etc. config.max_login_attempts = 3
end
``` ```
### Customisation and Usage Possible random patterns
By default, second factor authentication is required for each user. You can
change that by overriding the following method in your model:
```ruby ```ruby
def need_two_factor_authentication?(request) /\d{5}/
request.ip != '127.0.0.1' /\w{4,8}/
end
``` ```
In the example above, two factor authentication will not be required for local see more https://github.com/benburkert/randexp
users.
This gem is compatible with [Google Authenticator](https://support.google.com/accounts/answer/1066447?hl=en). ### Customisation
To enable this a shared secret must be generated by invoking the following
method on your model:
```ruby By default second factor authentication enabled for each user, you can change it with this method in your User model:
user.generate_totp_secret
```
This must then be shared via a provisioning uri:
```ruby ```ruby
user.provisioning_uri # This assumes a user model with an email attribute def need_two_factor_authentication?(request)
``` request.ip != '127.0.0.1'
end
This provisioning uri can then be turned in to a QR code if desired so that
users may add the app to Google Authenticator easily. Once this is done, they
may retrieve a one-time password directly from the Google Authenticator app.
#### Overriding the view
The default view that shows the form can be overridden by adding a
file named `show.html.erb` (or `show.html.haml` if you prefer HAML)
inside `app/views/devise/two_factor_authentication/` and customizing it.
Below is an example using ERB:
```html
<h2>Hi, you received a code by email, please enter it below, thanks!</h2>
<%= form_tag([resource_name, :two_factor_authentication], :method => :put) do %>
<%= text_field_tag :code %>
<%= submit_tag "Log in!" %>
<% end %>
<%= link_to "Sign out", destroy_user_session_path, :method => :delete %>
``` ```
#### Upgrading from version 1.X to 2.X this will disable two factor authentication for local users
The following database fields are new in version 2.
- `direct_otp` Your send sms logic should be in this method in your User model:
- `direct_otp_sent_at`
- `totp_timestamp`
To add them, generate a migration such as:
$ rails g migration AddTwoFactorFieldsToUsers direct_otp:string direct_otp_sent_at:datetime totp_timestamp:timestamp
The `otp_secret_key` is only required for users who use TOTP (Google Authenticator) codes,
so unless it has been shared with the user it should be set to `nil`. The
following pseudo-code is an example of how this might be done:
```ruby ```ruby
User.find_each do |user| do def send_two_factor_authentication_code(code)
if !uses_authenticator_app(user) puts code
user.otp_secret_key = nil
user.save!
end end
end
``` ```
#### Adding the TOTP encryption option to an existing app This example just puts the code in the logs.
If you've already been using this gem, and want to start encrypting the OTP
secret key in the database (recommended), you'll need to perform the following
steps:
1. Generate a migration to add the necessary columns to your model's table:
```
rails g migration AddEncryptionFieldsToUsers encrypted_otp_secret_key:string:index encrypted_otp_secret_key_iv:string encrypted_otp_secret_key_salt:string
```
Open your migration file (it will be in the `db/migrate` directory and will be
named something like `20151230163930_add_encryption_fields_to_users.rb`), and
add `unique: true` to the `add_index` line so that it looks like this:
```ruby
add_index :users, :encrypted_otp_secret_key, unique: true
```
Save the file.
2. Run the migration: `bundle exec rake db:migrate`
2. Update the gem: `bundle update two_factor_authentication`
3. Add `encrypted: true` to `has_one_time_password` in your model.
For example: `has_one_time_password(encrypted: true)`
4. Generate a migration to populate the new encryption fields:
```
rails g migration PopulateEncryptedOtpFields
```
Open the generated file, and replace its contents with the following:
```ruby
class PopulateEncryptedOtpFields < ActiveRecord::Migration
def up
User.reset_column_information
User.find_each do |user|
user.otp_secret_key = user.read_attribute('otp_secret_key')
user.save!
end
end
def down
User.reset_column_information
User.find_each do |user|
user.otp_secret_key = ROTP::Base32.random_base32
user.save!
end
end
end
```
5. Generate a migration to remove the `:otp_secret_key` column:
```
rails g migration RemoveOtpSecretKeyFromUsers otp_secret_key:string
```
6. Run the migrations: `bundle exec rake db:migrate`
If, for some reason, you want to switch back to the old non-encrypted version,
use these steps:
1. Remove `(encrypted: true)` from `has_one_time_password`
2. Roll back the last 3 migrations (assuming you haven't added any new ones
after them):
```
bundle exec rake db:rollback STEP=3
```
#### Critical Security Note! Add before_action to your user registration controllers
You should have a file registrations_controller.rb in your controllers folder
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!
```ruby ### External dependencies
class RegistrationsController < Devise::RegistrationsController
before_action :confirm_two_factor_authenticated, except: [:new, :create, :cancel]
protected Randexp requires words files (Check if it is installed in /usr/share/dict/words or /usr/dict/words),
you might need install it:
def confirm_two_factor_authenticated ```bash
return if is_fully_authenticated? apt-get install wbritish # or whichever you require
```
flash[:error] = t('devise.errors.messages.user_not_authenticated')
redirect_to user_two_factor_authentication_url
end
end
```
#### Critical Security Note! Add 2FA validation to your custom user actions
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.
For example, a simple account_controller.rb may look something like this:
```
require 'json'
class AccountController < ApplicationController
before_action :require_signed_in!
before_action :authenticate_user!
respond_to :html, :json
def account_API
resp = {}
begin
if(account_params["twoFAKey"] && account_params["twoFASecret"])
current_user.otp_secret_key = account_params["twoFAKey"]
if(current_user.authenticate_totp(account_params["twoFASecret"]))
# user has validated their temporary 2FA code, save it to their account, enable 2FA on this account
current_user.save!
resp['success'] = "passed 2FA validation!"
else
resp['error'] = "failed 2FA validation!"
end
elsif(param[:userAccountStuff] && param[:userAccountWidget])
#before updating important user account stuff and widgets,
#check to see that the 2FA secret has also been passed in, and verify it...
if(account_params["twoFASecret"] && current_user.totp_enabled? && current_user.authenticate_totp(account_params["twoFASecret"]))
# user has passed 2FA checks, do cool user account stuff here
...
else
# user failed 2FA check! No cool user stuff happens!
resp[error] = 'You failed 2FA validation!'
end
...
end
else
resp['error'] = 'unknown format error, not saved!'
end
rescue Exception => e
puts "WARNING: account api threw error : '#{e}' for user #{current_user.username}"
#print "error trace: #{e.backtrace}\n"
resp['error'] = "unanticipated server response"
end
render json: resp.to_json
end
def account_params
params.require(:twoFA).permit(:userAccountStuff, :userAcountWidget, :twoFAKey, :twoFASecret)
end
end
```
### Example App
[TwoFactorAuthenticationExample](https://github.com/Houdini/TwoFactorAuthenticationExample)
### Example user actions
to use an ENV VAR for the 2FA encryption key:
config.otp_secret_encryption_key = ENV['OTP_SECRET_ENCRYPTION_KEY']
to set up TOTP for Google Authenticator for user:
```
current_user.otp_secret_key = current_user.generate_totp_secret
current_user.save!
```
( encrypted db fields are set upon user model save action,
rails c access relies on setting env var: OTP_SECRET_ENCRYPTION_KEY )
to check if user has input the correct code (from the QR display page)
before saving the user model:
```
current_user.authenticate_totp('123456')
```
additional note:
```
current_user.otp_secret_key
```
This returns the OTP secret key in plaintext for the user (if you have set the env var) in the console
the string used for generating the QR given to the user for their Google Auth is something like:
otpauth://totp/LABEL?secret=p6wwetjnkjnrcmpd (example secret used here)
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
this returns true or false with an allowed_otp_drift_seconds 'grace period'
to set TOTP to DISABLED for a user account:
```
current_user.second_factor_attempts_count=nil
current_user.encrypted_otp_secret_key=nil
current_user.encrypted_otp_secret_key_iv=nil
current_user.encrypted_otp_secret_key_salt=nil
current_user.direct_otp=nil
current_user.direct_otp_sent_at=nil
current_user.totp_timestamp=nil
current_user.direct_otp=nil
current_user.otp_secret_key=nil
current_user.save! (if in ruby code instead of console)
current_user.direct_otp? => false
current_user.totp_enabled? => false
```

17
Rakefile

@ -1,16 +1 @@
# frozen_string_literal: true require "bundler/gem_tasks"
require 'bundler/gem_tasks'
APP_RAKEFILE = File.expand_path('spec/rails_app/Rakefile', __dir__)
load 'rails/tasks/engine.rake'
require 'rspec/core/rake_task'
desc 'Run all specs in spec directory (excluding plugin specs)'
RSpec::Core::RakeTask.new(spec: 'app:db:test:prepare')
task default: :spec
# To test against a specific version of Rails
# export RAILS_VERSION=3.2.0; bundle update; rake

101
app/controllers/devise/two_factor_authentication_controller.rb

@ -1,88 +1,43 @@
require 'devise/version' class Devise::TwoFactorAuthenticationController < ActiveAdmin::Devise::SessionsController # DeviseController
prepend_before_filter :authenticate_scope!
class Devise::TwoFactorAuthenticationController < DeviseController before_filter :prepare_and_validate, :handle_two_factor_authentication
prepend_before_action :authenticate_scope!
before_action :prepare_and_validate, :handle_two_factor_authentication
def show def show
end end
def update def update
render :show, status: :unprocessable_entity and return if params_code.empty? render :show and return if params[:code].nil?
md5 = Digest::MD5.hexdigest(params[:code])
if resource.authenticate_otp(params_code) if md5.eql?(resource.second_factor_pass_code)
after_two_factor_success_for(resource) warden.session(resource_name)[:need_two_factor_authentication] = false
sign_in resource_name, resource, :bypass => true
redirect_to stored_location_for(resource_name) || '/admin' #:root
resource.update_attribute(:second_factor_attempts_count, 0)
else else
after_two_factor_fail_for(resource) resource.second_factor_attempts_count += 1
resource.save
set_flash_message :error, :attempt_failed
if resource.max_login_attempts?
sign_out(resource)
render :template => 'devise/two_factor_authentication/max_login_attempts_reached' and return
else
render :show
end
end end
end end
def resend_code
resource.send_new_otp
redirect_to send("#{resource_name}_two_factor_authentication_path"), notice: I18n.t('devise.two_factor_authentication.code_has_been_sent')
end
private private
def after_two_factor_success_for(resource) def authenticate_scope!
set_remember_two_factor_cookie(resource) self.resource = send("current_#{resource_name}")
warden.session(resource_name)[DeviseTwoFactorAuthentication::NEED_AUTHENTICATION] = false
# For compatability with devise versions below v4.2.0
# https://github.com/plataformatec/devise/commit/2044fffa25d781fcbaf090e7728b48b65c854ccb
if respond_to?(:bypass_sign_in)
bypass_sign_in(resource, scope: resource_name)
else
sign_in(resource_name, resource, bypass: true)
end
set_flash_message :notice, :success
resource.update_attribute(:second_factor_attempts_count, 0)
redirect_to after_two_factor_success_path_for(resource)
end
def set_remember_two_factor_cookie(resource)
expires_seconds = resource.class.remember_otp_session_for_seconds
if expires_seconds && expires_seconds > 0
cookies.signed[DeviseTwoFactorAuthentication::REMEMBER_TFA_COOKIE_NAME] = {
value: "#{resource.class}-#{resource.public_send(Devise.second_factor_resource_id)}",
expires: expires_seconds.seconds.from_now
}
end
end
def after_two_factor_success_path_for(resource)
stored_location_for(resource_name) || :root
end
def after_two_factor_fail_for(resource)
resource.second_factor_attempts_count += 1
resource.save
set_flash_message :alert, :attempt_failed, now: true
if resource.max_login_attempts?
sign_out(resource)
render :max_login_attempts_reached, status: :unprocessable_entity
else
render :show, status: :unprocessable_entity
end end
end
def authenticate_scope!
self.resource = send("current_#{resource_name}")
end
def prepare_and_validate def prepare_and_validate
redirect_to :root and return if resource.nil? redirect_to :root and return if resource.nil?
@limit = resource.max_login_attempts @limit = resource.class.max_login_attempts
if resource.max_login_attempts? if resource.max_login_attempts?
sign_out(resource) sign_out(resource)
render :max_login_attempts_reached, status: :unprocessable_entity and return render :template => 'devise/two_factor_authentication/max_login_attempts_reached' and return
end
end end
end
def params_code
params[:code] || params.dig(resource_name, :code)
end
end end

4
app/views/devise/two_factor_authentication/max_login_attempts_reached.html.erb

@ -1,3 +1,3 @@
<h2><%= I18n.t("devise.two_factor_authentication.max_login_attempts_reached") %> = <%= @limit %>.</h2> <h2>Access completely denied as you have reached your attempts limit = <%= @limit %>.</h2>
<p><%= I18n.t("devise.two_factor_authentication.contact_administrator") %></p> <p>Please contact your system administrator.</p>

15
app/views/devise/two_factor_authentication/show.html.erb

@ -1,19 +1,10 @@
<% if resource.direct_otp %> <h2>Enter your personal code</h2>
<h2>Enter the code that was sent to you</h2>
<% else %>
<h2>Enter the code from your authenticator app</h2>
<% end %>
<p><%= flash[:notice] %></p> <p><%= flash[:notice] %></p>
<%= form_tag([resource_name, :two_factor_authentication], :method => :put) do %> <%= form_tag([resource_name, :two_factor_authentication], :method => :put) do %>
<%= text_field_tag :code, '', autofocus: true %> <%= text_field_tag :code %>
<%= submit_tag "Submit" %> <%= submit_tag "Submit" %>
<% end %> <% end %>
<% if resource.direct_otp %> <%= link_to "Sign out", destroy_admin_user_session_path, :method => :delete %>
<%= link_to "Resend Code", send("resend_code_#{resource_name}_two_factor_authentication_path"), action: :get %>
<% else %>
<%= link_to "Send me a code instead", send("resend_code_#{resource_name}_two_factor_authentication_path"), action: :get %>
<% end %>
<%= link_to "Sign out", send("destroy_#{resource_name}_session_path"), :method => :delete %>

8
config/locales/de.yml

@ -1,8 +0,0 @@
de:
devise:
two_factor_authentication:
success: "Ihre Zwei-Faktor-Authentifizierung war erfolgreich."
attempt_failed: "Authentifizierungsversuch fehlgeschlagen."
max_login_attempts_reached: "Ihr Zugang wurde ganz verweigert, da Sie Ihr Versuchslimit erreicht haben."
contact_administrator: "Kontaktieren Sie bitte einen Ihrer Administratoren."
code_has_been_sent: "Ihr Einmal-Passwort wurde verschickt."

4
config/locales/en.yml

@ -1,8 +1,4 @@
en: en:
devise: devise:
two_factor_authentication: two_factor_authentication:
success: "Two factor authentication successful."
attempt_failed: "Attempt failed." attempt_failed: "Attempt failed."
max_login_attempts_reached: "Access completely denied as you have reached your attempts limit"
contact_administrator: "Please contact your system administrator."
code_has_been_sent: "Your authentication code has been sent."

8
config/locales/es.yml

@ -1,8 +0,0 @@
es:
devise:
two_factor_authentication:
success: "Autenticación multi-factor realizada exitosamente."
attempt_failed: "La autenticación ha fallado."
max_login_attempts_reached: "Has llegado al límite de intentos fallidos, acceso denegado."
contact_administrator: "Contacte a su administrador de sistema."
code_has_been_sent: "El código de autenticación ha sido enviado."

8
config/locales/fr.yml

@ -1,8 +0,0 @@
fr:
devise:
two_factor_authentication:
success: "Validation en deux étapes effectuée avec succès."
attempt_failed: "La connexion a échoué."
max_login_attempts_reached: "Limite de tentatives atteinte, accès refusé."
contact_administrator: "Merci de contacter votre administrateur système."
code_has_been_sent: "Votre code de validation envoyé."

8
config/locales/ru.yml

@ -1,8 +0,0 @@
ru:
devise:
two_factor_authentication:
success: "Двухфакторная авторизация успешно пройдена."
attempt_failed: "Неверный код."
max_login_attempts_reached: "Доступ заблокирован. Превышено число попыток авторизации"
contact_administrator: "Пожалуйста, свяжитесь с системным администратором."
code_has_been_sent: "Ваш персональный код был отправлен."

52
lib/devise_two_factor_authentication.rb

@ -1,52 +0,0 @@
require 'devise_two_factor_authentication/version'
require 'devise'
require 'active_support/concern'
require "active_model"
require "active_support/core_ext/class/attribute_accessors"
require "cgi"
module Devise
mattr_accessor :max_login_attempts
@@max_login_attempts = 3
mattr_accessor :allowed_otp_drift_seconds
@@allowed_otp_drift_seconds = 30
mattr_accessor :otp_length
@@otp_length = 6
mattr_accessor :direct_otp_length
@@direct_otp_length = 6
mattr_accessor :direct_otp_valid_for
@@direct_otp_valid_for = 5.minutes
mattr_accessor :remember_otp_session_for_seconds
@@remember_otp_session_for_seconds = 0
mattr_accessor :otp_secret_encryption_key
@@otp_secret_encryption_key = ''
mattr_accessor :second_factor_resource_id
@@second_factor_resource_id = 'id'
mattr_accessor :delete_cookie_on_logout
@@delete_cookie_on_logout = false
end
module DeviseTwoFactorAuthentication
NEED_AUTHENTICATION = 'need_two_factor_authentication'
REMEMBER_TFA_COOKIE_NAME = "remember_tfa"
autoload :Schema, 'devise_two_factor_authentication/schema'
module Controllers
autoload :Helpers, 'devise_two_factor_authentication/controllers/helpers'
end
end
Devise.add_module :two_factor_authenticatable, :model => 'devise_two_factor_authentication/models/two_factor_authenticatable', :controller => :two_factor_authentication, :route => :two_factor_authentication
require 'devise_two_factor_authentication/orm/active_record' if defined?(ActiveRecord::Base)
require 'devise_two_factor_authentication/routes'
require 'devise_two_factor_authentication/models/two_factor_authenticatable'
require 'devise_two_factor_authentication/rails'

54
lib/devise_two_factor_authentication/controllers/helpers.rb

@ -1,54 +0,0 @@
module DeviseTwoFactorAuthentication
module Controllers
module Helpers
extend ActiveSupport::Concern
included do
before_action :handle_two_factor_authentication
end
private
def handle_two_factor_authentication
unless devise_controller?
Devise.mappings.keys.flatten.any? do |scope|
if signed_in?(scope) and warden.session(scope)[DeviseTwoFactorAuthentication::NEED_AUTHENTICATION]
handle_failed_second_factor(scope)
end
end
end
end
def handle_failed_second_factor(scope)
if request.format.present?
if request.format.html?
session["#{scope}_return_to"] = request.original_fullpath if request.get?
redirect_to two_factor_authentication_path_for(scope)
elsif request.format.json?
session["#{scope}_return_to"] = root_path(format: :html)
render json: { redirect_to: two_factor_authentication_path_for(scope) }, status: :unauthorized
end
else
head :unauthorized
end
end
def two_factor_authentication_path_for(resource_or_scope = nil)
scope = Devise::Mapping.find_scope!(resource_or_scope)
change_path = "#{scope}_two_factor_authentication_path"
send(change_path)
end
end
end
end
module Devise
module Controllers
module Helpers
def is_fully_authenticated?
!session["warden.user.user.session"].try(:[], DeviseTwoFactorAuthentication::NEED_AUTHENTICATION)
end
end
end
end

17
lib/devise_two_factor_authentication/hooks/two_factor_authenticatable.rb

@ -1,17 +0,0 @@
Warden::Manager.after_authentication do |user, auth, options|
if auth.env["action_dispatch.cookies"]
expected_cookie_value = "#{user.class}-#{user.public_send(Devise.second_factor_resource_id)}"
actual_cookie_value = auth.env["action_dispatch.cookies"].signed[DeviseTwoFactorAuthentication::REMEMBER_TFA_COOKIE_NAME]
bypass_by_cookie = actual_cookie_value == expected_cookie_value
end
if user.respond_to?(:need_two_factor_authentication?) && !bypass_by_cookie
if auth.session(options[:scope])[DeviseTwoFactorAuthentication::NEED_AUTHENTICATION] = user.need_two_factor_authentication?(auth.request)
user.send_new_otp if user.send_new_otp_after_login?
end
end
end
Warden::Manager.before_logout do |user, auth, _options|
auth.cookies.delete DeviseTwoFactorAuthentication::REMEMBER_TFA_COOKIE_NAME if Devise.delete_cookie_on_logout
end

206
lib/devise_two_factor_authentication/models/two_factor_authenticatable.rb

@ -1,206 +0,0 @@
require 'devise_two_factor_authentication/hooks/two_factor_authenticatable'
require 'rotp'
require 'encryptor'
module Devise
module Models
module TwoFactorAuthenticatable
extend ActiveSupport::Concern
module ClassMethods
def has_one_time_password(options = {})
include InstanceMethodsOnActivation
include EncryptionInstanceMethods if options[:encrypted] == true
end
::Devise::Models.config(
self, :max_login_attempts, :allowed_otp_drift_seconds, :otp_length,
:remember_otp_session_for_seconds, :otp_secret_encryption_key,
:direct_otp_length, :direct_otp_valid_for, :totp_timestamp, :delete_cookie_on_logout
)
end
module InstanceMethodsOnActivation
def authenticate_otp(code, options = {})
return true if direct_otp && authenticate_direct_otp(code)
return true if totp_enabled? && authenticate_totp(code, options)
false
end
def authenticate_direct_otp(code)
return false if direct_otp.nil? || direct_otp != code || direct_otp_expired?
clear_direct_otp
true
end
def authenticate_totp(code, options = {})
totp_secret = options[:otp_secret_key] || otp_secret_key
digits = options[:otp_length] || self.class.otp_length
drift = options[:drift] || self.class.allowed_otp_drift_seconds
raise "authenticate_totp called with no otp_secret_key set" if totp_secret.nil?
totp = ROTP::TOTP.new(totp_secret, digits: digits)
new_timestamp = totp.verify(
without_spaces(code),
drift_ahead: drift, drift_behind: drift, after: totp_timestamp
)
return false unless new_timestamp
self.totp_timestamp = new_timestamp
true
end
def provisioning_uri(account = nil, options = {})
totp_secret = options[:otp_secret_key] || otp_secret_key
options[:digits] ||= options[:otp_length] || self.class.otp_length
raise "provisioning_uri called with no otp_secret_key set" if totp_secret.nil?
account ||= email if respond_to?(:email)
ROTP::TOTP.new(totp_secret, options).provisioning_uri(account)
end
def need_two_factor_authentication?(request)
true
end
def send_new_otp(options = {})
create_direct_otp options
send_two_factor_authentication_code(direct_otp)
end
def send_new_otp_after_login?
!totp_enabled?
end
def send_two_factor_authentication_code(code)
raise NotImplementedError.new("No default implementation - please define in your class.")
end
def max_login_attempts?
second_factor_attempts_count.to_i >= max_login_attempts.to_i
end
def max_login_attempts
self.class.max_login_attempts
end
def totp_enabled?
respond_to?(:otp_secret_key) && !otp_secret_key.nil?
end
def confirm_totp_secret(secret, code, options = {})
return false unless authenticate_totp(code, {otp_secret_key: secret})
self.otp_secret_key = secret
true
end
def generate_totp_secret
# ROTP gem since version 5 to version 5.1
# at version 5.1 ROTP gem reinstates.
# Details: https://github.com/mdp/rotp/blob/master/CHANGELOG.md#510
ROTP::Base32.try(:random) || ROTP::Base32.random_base32
end
def create_direct_otp(options = {})
# Create a new random OTP and store it in the database
digits = options[:length] || self.class.direct_otp_length || 6
update(
direct_otp: random_base10(digits),
direct_otp_sent_at: Time.now.utc
)
end
private
def without_spaces(code)
code.gsub(/\s/, '')
end
def random_base10(digits)
SecureRandom.random_number(10**digits).to_s.rjust(digits, '0')
end
def direct_otp_expired?
Time.now.utc > direct_otp_sent_at + self.class.direct_otp_valid_for
end
def clear_direct_otp
update(direct_otp: nil, direct_otp_sent_at: nil)
end
end
module EncryptionInstanceMethods
def otp_secret_key
otp_decrypt(encrypted_otp_secret_key)
end
def otp_secret_key=(value)
self.encrypted_otp_secret_key = otp_encrypt(value)
end
private
def otp_decrypt(encrypted_value)
return encrypted_value if encrypted_value.blank?
encrypted_value = encrypted_value.unpack('m').first
value = ::Encryptor.decrypt(encryption_options_for(encrypted_value))
if defined?(Encoding)
encoding = Encoding.default_internal || Encoding.default_external
value = value.force_encoding(encoding.name)
end
value
end
def otp_encrypt(value)
return value if value.blank?
value = value.to_s
encrypted_value = ::Encryptor.encrypt(encryption_options_for(value))
encrypted_value = [encrypted_value].pack('m')
encrypted_value
end
def encryption_options_for(value)
{
value: value,
key: Devise.otp_secret_encryption_key,
iv: iv_for_attribute,
salt: salt_for_attribute,
algorithm: 'aes-256-cbc'
}
end
def iv_for_attribute(algorithm = 'aes-256-cbc')
iv = encrypted_otp_secret_key_iv
if iv.nil?
algo = OpenSSL::Cipher.new(algorithm)
iv = [algo.random_iv].pack('m')
self.encrypted_otp_secret_key_iv = iv
end
iv.unpack('m').first if iv.present?
end
def salt_for_attribute
salt = encrypted_otp_secret_key_salt ||
self.encrypted_otp_secret_key_salt = generate_random_base64_encoded_salt
decode_salt_if_encoded(salt)
end
def generate_random_base64_encoded_salt
prefix = '_'
prefix + [SecureRandom.random_bytes].pack('m')
end
def decode_salt_if_encoded(salt)
salt.slice(0).eql?('_') ? salt.slice(1..-1).unpack('m').first : salt
end
end
end
end
end

14
lib/devise_two_factor_authentication/orm/active_record.rb

@ -1,14 +0,0 @@
require "active_record"
module Devise2Fa
module Orm
module ActiveRecord
module Schema
# include Devise2Fa::Schema
end
end
end
end
ActiveRecord::ConnectionAdapters::Table.send :include, Devise2Fa::Orm::ActiveRecord::Schema
ActiveRecord::ConnectionAdapters::TableDefinition.send :include, Devise2Fa::Orm::ActiveRecord::Schema

7
lib/devise_two_factor_authentication/rails.rb

@ -1,7 +0,0 @@
module DeviseTwoFactorAuthentication
class Engine < ::Rails::Engine
ActiveSupport.on_load(:action_controller) do
include DeviseTwoFactorAuthentication::Controllers::Helpers
end
end
end

19
lib/devise_two_factor_authentication/routes.rb

@ -1,19 +0,0 @@
module ActionDispatch::Routing
class Mapper
protected
def devise_two_factor_authentication(mapping, controllers)
resource :two_factor_authentication, :only => [:show, :update, :resend_code], :path => mapping.path_names[:two_factor_authentication], :controller => controllers[:two_factor_authentication] do
collection { get resend_code_path(mapping), as: "resend_code" }
end
end
def resend_code_path(mapping)
Devise.mappings[resource_name(mapping)].path_names[:two_factor_authentication_resend_code] || "resend_code"
end
def resource_name(mapping)
mapping.class_name.underscore.to_sym
end
end
end

31
lib/devise_two_factor_authentication/schema.rb

@ -1,31 +0,0 @@
module DeviseTwoFactorAuthentication
module Schema
def second_factor_attempts_count
apply_devise_schema :second_factor_attempts_count, Integer, :default => 0
end
def encrypted_otp_secret_key
apply_devise_schema :encrypted_otp_secret_key, String
end
def encrypted_otp_secret_key_iv
apply_devise_schema :encrypted_otp_secret_key_iv, String
end
def encrypted_otp_secret_key_salt
apply_devise_schema :encrypted_otp_secret_key_salt, String
end
def direct_otp
apply_devise_schema :direct_otp, String
end
def direct_otp_sent_at
apply_devise_schema :direct_otp_sent_at, DateTime
end
def totp_timestamp
apply_devise_schema :totp_timestamp, Timestamp
end
end
end

3
lib/devise_two_factor_authentication/version.rb

@ -1,3 +0,0 @@
module DeviseTwoFactorAuthentication
VERSION = "3.0.0".freeze
end

15
lib/generators/active_record/templates/migration.rb

@ -1,15 +1,8 @@
class TwoFactorAuthenticationAddTo<%= table_name.camelize %> < ActiveRecord::Migration class TwoFactorAuthenticationAddTo<%= table_name.camelize %> < ActiveRecord::Migration
disable_ddl_transaction!
def change def change
add_column :<%= table_name %>, :second_factor_attempts_count, :integer, default: 0 change_table :<%= table_name %> do |t|
add_column :<%= table_name %>, :encrypted_otp_secret_key, :string t.string :second_factor_pass_code , :limit => 32
add_column :<%= table_name %>, :encrypted_otp_secret_key_iv, :string t.integer :second_factor_attempts_count, :default => 0
add_column :<%= table_name %>, :encrypted_otp_secret_key_salt, :string end
add_column :<%= table_name %>, :direct_otp, :string
add_column :<%= table_name %>, :direct_otp_sent_at, :datetime
add_column :<%= table_name %>, :totp_timestamp, :timestamp
add_index :<%= table_name %>, :encrypted_otp_secret_key, unique: true, algorithm: :concurrently
end end
end end

2
lib/generators/active_record/two_factor_authentication_generator.rb

@ -6,7 +6,7 @@ module ActiveRecord
source_root File.expand_path("../templates", __FILE__) source_root File.expand_path("../templates", __FILE__)
def copy_two_factor_authentication_migration def copy_two_factor_authentication_migration
migration_template "migration.rb", "db/migrate/two_factor_authentication_add_to_#{table_name}.rb" migration_template "migration.rb", "db/migrate/two_factor_authentication_add_to_#{table_name}"
end end
end end

27
lib/two_factor_authentication.rb

@ -0,0 +1,27 @@
require 'two_factor_authentication/version'
require 'randexp'
require 'devise'
require 'digest'
require 'active_support/concern'
module Devise
mattr_accessor :login_code_random_pattern
@@login_code_random_pattern = /\w+/
mattr_accessor :max_login_attempts
@@max_login_attempts = 3
end
module TwoFactorAuthentication
autoload :Schema, 'two_factor_authentication/schema'
module Controllers
autoload :Helpers, 'two_factor_authentication/controllers/helpers'
end
end
Devise.add_module :two_factor_authenticatable, :model => 'two_factor_authentication/models/two_factor_authenticatable', :controller => :two_factor_authentication, :route => :two_factor_authentication
require 'two_factor_authentication/orm/active_record'
require 'two_factor_authentication/routes'
require 'two_factor_authentication/models/two_factor_authenticatable'
require 'two_factor_authentication/rails'

41
lib/two_factor_authentication/controllers/helpers.rb

@ -0,0 +1,41 @@
module TwoFactorAuthentication
module Controllers
module Helpers
extend ActiveSupport::Concern
included do
before_filter :handle_two_factor_authentication
end
private
def handle_two_factor_authentication
unless devise_controller?
scope = 'admin_user'
# Devise.mappings.keys.flatten.any? do |scope|
if signed_in?(scope) and warden.session(scope)[:need_two_factor_authentication]
handle_failed_second_factor(scope)
end
# end
end
end
def handle_failed_second_factor(scope)
if request.format.present? and request.format.html?
session["#{scope}_return_tor"] = request.path if request.get?
redirect_to two_factor_authentication_path_for(scope)
else
render nothing: true, status: :unauthorized
end
end
def two_factor_authentication_path_for(resource_or_scope = nil)
# scope = Devise::Mapping.find_scope!(resource_or_scope)
scope = 'admin_user'
change_path = "#{scope}_two_factor_authentication_path"
send(change_path)
end
end
end
end

10
lib/two_factor_authentication/hooks/two_factor_authenticatable.rb

@ -0,0 +1,10 @@
Warden::Manager.after_authentication do |user, auth, options|
if user.respond_to?(:need_two_factor_authentication?)
if auth.session(options[:scope])[:need_two_factor_authentication] = user.need_two_factor_authentication?(auth.request)
code = user.generate_two_factor_code
user.second_factor_pass_code = Digest::MD5.hexdigest(code)
user.save
user.send_two_factor_authentication_code(code)
end
end
end

28
lib/two_factor_authentication/models/two_factor_authenticatable.rb

@ -0,0 +1,28 @@
require 'two_factor_authentication/hooks/two_factor_authenticatable'
module Devise
module Models
module TwoFactorAuthenticatable
extend ActiveSupport::Concern
module ClassMethods
::Devise::Models.config(self, :login_code_random_pattern, :max_login_attempts)
end
def need_two_factor_authentication?(request)
true
end
def generate_two_factor_code
self.class.login_code_random_pattern.gen
end
def send_two_factor_authentication_code(code)
p "Code is #{code}"
end
def max_login_attempts?
second_factor_attempts_count >= self.class.max_login_attempts
end
end
end
end

12
lib/two_factor_authentication/orm/active_record.rb

@ -0,0 +1,12 @@
module TwoFactorAuthentication
module Orm
module ActiveRecord
module Schema
include TwoFactorAuthentication::Schema
end
end
end
end
ActiveRecord::ConnectionAdapters::Table.send :include, TwoFactorAuthentication::Orm::ActiveRecord::Schema
ActiveRecord::ConnectionAdapters::TableDefinition.send :include, TwoFactorAuthentication::Orm::ActiveRecord::Schema

7
lib/two_factor_authentication/rails.rb

@ -0,0 +1,7 @@
module TwoFactorAuthentication
class Engine < ::Rails::Engine
ActiveSupport.on_load(:action_controller) do
include TwoFactorAuthentication::Controllers::Helpers
end
end
end

9
lib/two_factor_authentication/routes.rb

@ -0,0 +1,9 @@
module ActionDispatch::Routing
class Mapper
protected
def devise_two_factor_authentication(mapping, controllers)
resource :two_factor_authentication, :only => [:show, :update], :path => mapping.path_names[:two_factor_authentication], :controller => controllers[:two_factor_authentication]
end
end
end

11
lib/two_factor_authentication/schema.rb

@ -0,0 +1,11 @@
module TwoFactorAuthentication
module Schema
def second_factor_pass_code
apply_devise_schema :second_factor_pass_code, String, :limit => 32
end
def second_factor_attempts_count
apply_devise_schema :second_factor_attempts_count, Integer, :default => 0
end
end
end

3
lib/two_factor_authentication/version.rb

@ -0,0 +1,3 @@
module TwoFactorAuthentication
VERSION = "0.2".freeze
end

41
spec/controllers/two_factor_authentication_controller_spec.rb

@ -1,41 +0,0 @@
require 'spec_helper'
describe Devise::TwoFactorAuthenticationController, type: :controller do
describe 'is_fully_authenticated? helper' do
def post_code(code)
if Rails::VERSION::MAJOR >= 5
post :update, params: { code: code }
else
post :update, code: code
end
end
before do
sign_in
end
context 'after user enters valid OTP code' do
it 'returns true' do
controller.current_user.send_new_otp
post_code controller.current_user.direct_otp
expect(subject.is_fully_authenticated?).to eq true
end
end
context 'when user has not entered any OTP yet' do
it 'returns false' do
get :show
expect(subject.is_fully_authenticated?).to eq false
end
end
context 'when user enters an invalid OTP' do
it 'returns false' do
post_code '12345'
expect(subject.is_fully_authenticated?).to eq false
end
end
end
end

236
spec/features/two_factor_authenticatable_spec.rb

@ -1,236 +0,0 @@
require 'spec_helper'
include AuthenticatedModelHelper
feature "User of two factor authentication" do
context 'sending two factor authentication code via SMS' do
shared_examples 'sends and authenticates code' do |user, type|
before do
user.reload
if type == 'encrypted'
allow(User).to receive(:has_one_time_password).with(encrypted: true)
end
end
it 'does not send an SMS before the user has signed in' do
expect(SmsProvider.messages).to be_empty
end
it 'sends code via SMS after sign in' do
visit new_user_session_path
complete_sign_in_form_for(user)
expect(page).to have_content 'Enter the code that was sent to you'
expect(SmsProvider.messages.size).to eq(1)
message = SmsProvider.last_message
expect(message.to).to eq(user.phone_number)
expect(message.body).to eq(user.reload.direct_otp)
end
it 'authenticates a valid OTP code' do
visit new_user_session_path
complete_sign_in_form_for(user)
expect(page).to have_content('You are signed in as Marissa')
fill_in 'code', with: SmsProvider.last_message.body
click_button 'Submit'
expect(page).to have_selector(
".notice",
text: "Two factor authentication successful."
)
expect(current_path).to eq root_path
end
end
it_behaves_like 'sends and authenticates code', create_user('not_encrypted')
it_behaves_like 'sends and authenticates code', create_user, 'encrypted'
end
scenario "must be logged in" do
visit user_two_factor_authentication_path
expect(page).to have_content("Welcome Home")
expect(page).to have_content("You are signed out")
end
context "when logged in" do
let(:user) { create_user }
background do
login_as user
end
scenario "is redirected to TFA when path requires authentication" do
visit dashboard_path + "?A=param%20a&B=param%20b"
expect(page).to_not have_content("Your Personal Dashboard")
fill_in "code", with: SmsProvider.last_message.body
click_button "Submit"
expect(page).to have_content("Your Personal Dashboard")
expect(page).to have_content("You are signed in as Marissa")
expect(page).to have_content("Param A is param a")
expect(page).to have_content("Param B is param b")
end
scenario "is locked out after max failed attempts" do
visit user_two_factor_authentication_path
max_attempts = User.max_login_attempts
max_attempts.times do
fill_in "code", with: "incorrect#{rand(100)}"
click_button "Submit"
expect(page).to have_selector(".alert", text: "Attempt failed")
end
expect(page).to have_content("Access completely denied")
expect(page).to have_content("You are signed out")
end
scenario "cannot retry authentication after max attempts" do
user.update_attribute(:second_factor_attempts_count, User.max_login_attempts)
visit user_two_factor_authentication_path
expect(page).to have_content("Access completely denied")
expect(page).to have_content("You are signed out")
end
describe "rememberable TFA" do
before do
@original_remember_otp_session_for_seconds = User.remember_otp_session_for_seconds
User.remember_otp_session_for_seconds = 30.days
end
after do
User.remember_otp_session_for_seconds = @original_remember_otp_session_for_seconds
end
scenario "doesn't require TFA code again within 30 days" do
sms_sign_in
logout
login_as user
visit dashboard_path
expect(page).to have_content("Your Personal Dashboard")
expect(page).to have_content("You are signed in as Marissa")
end
scenario "requires TFA code again after 30 days" do
sms_sign_in
logout
Timecop.travel(30.days.from_now)
login_as user
visit dashboard_path
expect(page).to have_content("You are signed in as Marissa")
expect(page).to have_content("Enter the code that was sent to you")
end
scenario 'TFA should be different for different users' do
sms_sign_in
tfa_cookie1 = get_tfa_cookie()
logout
reset_session!
user2 = create_user()
login_as(user2)
sms_sign_in
tfa_cookie2 = get_tfa_cookie()
expect(tfa_cookie1).not_to eq tfa_cookie2
end
def sms_sign_in
SmsProvider.messages.clear()
visit user_two_factor_authentication_path
fill_in 'code', with: SmsProvider.last_message.body
click_button 'Submit'
end
scenario 'TFA should be unique for specific user' do
sms_sign_in
tfa_cookie1 = get_tfa_cookie()
logout
reset_session!
user2 = create_user()
set_tfa_cookie(tfa_cookie1)
login_as(user2)
visit dashboard_path
expect(page).to have_content("Enter the code that was sent to you")
end
scenario 'Delete cookie when user logs out if enabled' do
user.class.delete_cookie_on_logout = true
login_as user
logout
login_as user
visit dashboard_path
expect(page).to have_content("Enter the code that was sent to you")
end
end
it 'sets the warden session need_two_factor_authentication key to true' do
session_hash = { 'need_two_factor_authentication' => true }
expect(page.get_rack_session_key('warden.user.user.session')).to eq session_hash
end
end
describe 'signing in' do
let(:user) { create_user }
let(:admin) { create_admin }
scenario 'user signs is' do
visit new_user_session_path
complete_sign_in_form_for(user)
expect(page).to have_content('Signed in successfully.')
end
scenario 'admin signs in' do
visit new_admin_session_path
complete_sign_in_form_for(admin)
expect(page).to have_content('Signed in successfully.')
end
end
describe 'signing out' do
let(:user) { create_user }
let(:admin) { create_admin }
scenario 'user signs out' do
visit new_user_session_path
complete_sign_in_form_for(user)
visit destroy_user_session_path
expect(page).to have_content('Signed out successfully.')
end
scenario 'admin signs out' do
visit new_admin_session_path
complete_sign_in_form_for(admin)
visit destroy_admin_session_path
expect(page).to have_content('Signed out successfully.')
end
end
end

36
spec/generators/active_record/two_factor_authentication_generator_spec.rb

@ -1,36 +0,0 @@
require 'spec_helper'
require 'generators/active_record/two_factor_authentication_generator'
describe ActiveRecord::Generators::TwoFactorAuthenticationGenerator, type: :generator do
destination File.expand_path('../../../../../tmp', __FILE__)
before do
prepare_destination
end
it 'runs all methods in the generator' do
gen = generator %w(users)
expect(gen).to receive(:copy_two_factor_authentication_migration)
gen.invoke_all
end
describe 'the generated files' do
before do
run_generator %w(users)
end
describe 'the migration' do
subject { migration_file('db/migrate/two_factor_authentication_add_to_users.rb') }
it { is_expected.to exist }
it { is_expected.to be_a_migration }
it { is_expected.to contain /def change/ }
it { is_expected.to contain /add_column :users, :second_factor_attempts_count, :integer, default: 0/ }
it { is_expected.to contain /add_column :users, :encrypted_otp_secret_key, :string/ }
it { is_expected.to contain /add_column :users, :encrypted_otp_secret_key_iv, :string/ }
it { is_expected.to contain /add_column :users, :encrypted_otp_secret_key_salt, :string/ }
it { is_expected.to contain /add_index :users, :encrypted_otp_secret_key, unique: true/ }
end
end
end

326
spec/lib/two_factor_authentication/models/two_factor_authenticatable_spec.rb

@ -1,326 +0,0 @@
require 'spec_helper'
include AuthenticatedModelHelper
describe Devise::Models::TwoFactorAuthenticatable do
describe '#create_direct_otp' do
let(:instance) { build_guest_user }
it 'set direct_otp field' do
expect(instance.direct_otp).to be_nil
instance.create_direct_otp
expect(instance.direct_otp).not_to be_nil
end
it 'set direct_otp_send_at field to current time' do
Timecop.freeze() do
instance.create_direct_otp
expect(instance.direct_otp_sent_at).to eq(Time.now)
end
end
it 'honors .direct_otp_length' do
expect(instance.class).to receive(:direct_otp_length).and_return(10)
instance.create_direct_otp
expect(instance.direct_otp.length).to equal(10)
expect(instance.class).to receive(:direct_otp_length).and_return(6)
instance.create_direct_otp
expect(instance.direct_otp.length).to equal(6)
end
it "honors 'direct_otp_length' in options paramater" do
instance.create_direct_otp(length: 8)
expect(instance.direct_otp.length).to equal(8)
instance.create_direct_otp(length: 10)
expect(instance.direct_otp.length).to equal(10)
end
end
describe '#authenticate_direct_otp' do
let(:instance) { build_guest_user }
it 'fails if no direct_otp has been set' do
expect(instance.authenticate_direct_otp('12345')).to eq(false)
end
context 'after generating an OTP' do
before :each do
instance.create_direct_otp
end
it 'accepts correct OTP' do
Timecop.freeze(Time.now + instance.class.direct_otp_valid_for - 1.second)
expect(instance.authenticate_direct_otp(instance.direct_otp)).to eq(true)
end
it 'rejects invalid OTP' do
Timecop.freeze(Time.now + instance.class.direct_otp_valid_for - 1.second)
expect(instance.authenticate_direct_otp('12340')).to eq(false)
end
it 'rejects expired OTP' do
Timecop.freeze(Time.now + instance.class.direct_otp_valid_for + 1.second)
expect(instance.authenticate_direct_otp(instance.direct_otp)).to eq(false)
end
it 'prevents code re-use' do
expect(instance.authenticate_direct_otp(instance.direct_otp)).to eq(true)
expect(instance.authenticate_direct_otp(instance.direct_otp)).to eq(false)
end
end
end
describe '#authenticate_totp' do
shared_examples 'authenticate_totp' do |instance|
before :each do
instance.otp_secret_key = '2z6hxkdwi3uvrnpn'
instance.totp_timestamp = nil
@totp_helper = TotpHelper.new(instance.otp_secret_key, instance.class.otp_length)
end
def do_invoke(code, user)
user.authenticate_totp(code)
end
it 'authenticates a recently created code' do
code = @totp_helper.totp_code
expect(do_invoke(code, instance)).to eq(true)
end
it 'authenticates a code entered with a space' do
code = @totp_helper.totp_code.insert(3, ' ')
expect(do_invoke(code, instance)).to eq(true)
end
it 'does not authenticate an old code' do
code = @totp_helper.totp_code(1.minutes.ago.to_i)
expect(do_invoke(code, instance)).to eq(false)
end
it 'prevents code reuse' do
code = @totp_helper.totp_code
expect(do_invoke(code, instance)).to eq(true)
expect(do_invoke(code, instance)).to eq(false)
end
end
it_behaves_like 'authenticate_totp', GuestUser.new
it_behaves_like 'authenticate_totp', EncryptedUser.new
end
describe '#send_two_factor_authentication_code' do
let(:instance) { build_guest_user }
it 'raises an error by default' do
expect { instance.send_two_factor_authentication_code(123) }.
to raise_error(NotImplementedError)
end
it 'is overrideable' do
def instance.send_two_factor_authentication_code(code)
'Code sent'
end
expect(instance.send_two_factor_authentication_code(123)).to eq('Code sent')
end
end
describe '#provisioning_uri' do
shared_examples 'provisioning_uri' do |instance|
it 'fails until generate_totp_secret is called' do
expect { instance.provisioning_uri }.to raise_error(Exception)
end
describe 'with secret set' do
before do
instance.email = 'houdini@example.com'
instance.otp_secret_key = instance.generate_totp_secret
end
it "returns uri with user's email" do
expect(instance.provisioning_uri).
to match(%r{otpauth://totp/houdini%40example.com\?secret=\w{32}})
end
it 'returns uri with issuer option' do
expect(instance.provisioning_uri('houdini')).
to match(%r{otpauth://totp/houdini\?secret=\w{32}$})
end
it 'returns uri with issuer option' do
require 'cgi'
uri = URI.parse(instance.provisioning_uri('houdini', issuer: 'Magic'))
params = CGI.parse(uri.query)
expect(uri.scheme).to eq('otpauth')
expect(uri.host).to eq('totp')
expect(uri.path).to eq('/Magic:houdini')
expect(params['issuer'].shift).to eq('Magic')
expect(params['secret'].shift).to match(/\w{32}/)
end
end
end
it_behaves_like 'provisioning_uri', GuestUser.new
it_behaves_like 'provisioning_uri', EncryptedUser.new
end
describe '#generate_totp_secret' do
shared_examples 'generate_totp_secret' do |klass|
let(:instance) { klass.new }
it 'returns a 32 character string' do
secret = instance.generate_totp_secret
expect(secret).to match(/\w{32}/)
end
end
it_behaves_like 'generate_totp_secret', GuestUser
it_behaves_like 'generate_totp_secret', EncryptedUser
end
describe '#confirm_totp_secret' do
shared_examples 'confirm_totp_secret' do |klass|
let(:instance) { klass.new }
let(:secret) { instance.generate_totp_secret }
let(:totp_helper) { TotpHelper.new(secret, instance.class.otp_length) }
it 'populates otp_secret_key column when given correct code' do
instance.confirm_totp_secret(secret, totp_helper.totp_code)
expect(instance.otp_secret_key).to match(secret)
end
it 'does not populate otp_secret_key when when given incorrect code' do
instance.confirm_totp_secret(secret, '123')
expect(instance.otp_secret_key).to be_nil
end
it 'returns true when given correct code' do
expect(instance.confirm_totp_secret(secret, totp_helper.totp_code)).to be true
end
it 'returns false when given incorrect code' do
expect(instance.confirm_totp_secret(secret, '123')).to be false
end
end
it_behaves_like 'confirm_totp_secret', GuestUser
it_behaves_like 'confirm_totp_secret', EncryptedUser
end
describe '#max_login_attempts' do
let(:instance) { build_guest_user }
before do
@original_max_login_attempts = GuestUser.max_login_attempts
GuestUser.max_login_attempts = 3
end
after { GuestUser.max_login_attempts = @original_max_login_attempts }
it 'returns class setting' do
expect(instance.max_login_attempts).to eq(3)
end
it 'returns false as boolean' do
instance.second_factor_attempts_count = nil
expect(instance.max_login_attempts?).to be_falsey
instance.second_factor_attempts_count = 0
expect(instance.max_login_attempts?).to be_falsey
instance.second_factor_attempts_count = 1
expect(instance.max_login_attempts?).to be_falsey
instance.second_factor_attempts_count = 2
expect(instance.max_login_attempts?).to be_falsey
end
it 'returns true as boolean after too many attempts' do
instance.second_factor_attempts_count = 3
expect(instance.max_login_attempts?).to be_truthy
instance.second_factor_attempts_count = 4
expect(instance.max_login_attempts?).to be_truthy
end
end
describe '.has_one_time_password' do
context 'when encrypted: true option is passed' do
let(:instance) { EncryptedUser.new }
it 'encrypts otp_secret_key with iv, salt, and encoding' do
instance.otp_secret_key = '2z6hxkdwi3uvrnpn'
expect(instance.encrypted_otp_secret_key).to match(/.{44}/)
expect(instance.encrypted_otp_secret_key_iv).to match(/.{24}/)
expect(instance.encrypted_otp_secret_key_salt).to match(/.{25}/)
end
it 'does not encrypt a nil otp_secret_key' do
instance.otp_secret_key = nil
expect(instance.encrypted_otp_secret_key).to be_nil
expect(instance.encrypted_otp_secret_key_iv).to be_nil
expect(instance.encrypted_otp_secret_key_salt).to be_nil
end
it 'does not encrypt an empty otp_secret_key' do
instance.otp_secret_key = ''
expect(instance.encrypted_otp_secret_key).to eq ''
expect(instance.encrypted_otp_secret_key_iv).to be_nil
expect(instance.encrypted_otp_secret_key_salt).to be_nil
end
it 'raises an error when Devise.otp_secret_encryption_key is not set' do
allow(Devise).to receive(:otp_secret_encryption_key).and_return nil
# This error is raised by the encryptor gem
expect { instance.otp_secret_key = '2z6hxkdwi3uvrnpn' }.
to raise_error ArgumentError
end
it 'passes in the correct options to Encryptor.
We test here output of
Devise::Models::TwoFactorAuthenticatable::EncryptionInstanceMethods.encryption_options_for' do
instance.otp_secret_key = 'testing'
iv = instance.encrypted_otp_secret_key_iv
salt = instance.encrypted_otp_secret_key_salt
# it's important here to put the same crypto algorithm from that method
encrypted = Encryptor.encrypt(
value: 'testing',
key: Devise.otp_secret_encryption_key,
iv: iv.unpack('m').first,
salt: salt.unpack('m').first,
algorithm: 'aes-256-cbc'
)
expect(instance.encrypted_otp_secret_key).to eq [encrypted].pack('m')
end
it 'varies the iv per instance' do
instance.otp_secret_key = 'testing'
user2 = EncryptedUser.new
user2.otp_secret_key = 'testing'
expect(user2.encrypted_otp_secret_key_iv).
to_not eq instance.encrypted_otp_secret_key_iv
end
it 'varies the salt per instance' do
instance.otp_secret_key = 'testing'
user2 = EncryptedUser.new
user2.otp_secret_key = 'testing'
expect(user2.encrypted_otp_secret_key_salt).
to_not eq instance.encrypted_otp_secret_key_salt
end
end
end
end

3
spec/rails_app/.gitignore vendored

@ -1,3 +0,0 @@
log/
tmp/
*.sqlite3

3
spec/rails_app/README.md

@ -1,3 +0,0 @@
# Dummy
You have found the dummy rails app used for integration testing of the `two_factor_authentication` gem.

9
spec/rails_app/Rakefile

@ -1,9 +0,0 @@
#!/usr/bin/env rake
# frozen_string_literal: true
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
require File.expand_path('config/application', __dir__)
Dummy::Application.load_tasks

2
spec/rails_app/app/assets/config/manifest.js

@ -1,2 +0,0 @@
//= link_directory ../javascripts .js
//= link_directory ../stylesheets .css

1
spec/rails_app/app/assets/javascripts/application.js

@ -1 +0,0 @@
//= require_tree .

4
spec/rails_app/app/assets/stylesheets/application.css

@ -1,4 +0,0 @@
/*
*= require_self
*= require_tree .
*/

3
spec/rails_app/app/controllers/application_controller.rb

@ -1,3 +0,0 @@
class ApplicationController < ActionController::Base
protect_from_forgery
end

10
spec/rails_app/app/controllers/home_controller.rb

@ -1,10 +0,0 @@
class HomeController < ApplicationController
before_action :authenticate_user!, only: :dashboard
def index
end
def dashboard
end
end

8
spec/rails_app/app/helpers/application_helper.rb

@ -1,8 +0,0 @@
module ApplicationHelper
def render_flash
flash.map do |name, message|
content_tag(:p, message, class: "flash #{name}")
end.join.html_safe
end
end

0
spec/rails_app/app/mailers/.gitkeep

0
spec/rails_app/app/models/.gitkeep

6
spec/rails_app/app/models/admin.rb

@ -1,6 +0,0 @@
class Admin < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end

15
spec/rails_app/app/models/encrypted_user.rb

@ -1,15 +0,0 @@
class EncryptedUser
extend ActiveModel::Callbacks
include ActiveModel::Validations
include Devise::Models::TwoFactorAuthenticatable
define_model_callbacks :create
attr_accessor :encrypted_otp_secret_key,
:encrypted_otp_secret_key_iv,
:encrypted_otp_secret_key_salt,
:email,
:second_factor_attempts_count,
:totp_timestamp
has_one_time_password(encrypted: true)
end

17
spec/rails_app/app/models/guest_user.rb

@ -1,17 +0,0 @@
class GuestUser
extend ActiveModel::Callbacks
include ActiveModel::Validations
include Devise::Models::TwoFactorAuthenticatable
define_model_callbacks :create
attr_accessor :direct_otp, :direct_otp_sent_at, :otp_secret_key, :email,
:second_factor_attempts_count, :totp_timestamp
def update(attrs)
attrs.each do |key, value|
send(key.to_s + '=', value)
end
end
has_one_time_password
end

14
spec/rails_app/app/models/user.rb

@ -1,14 +0,0 @@
class User < ActiveRecord::Base
devise :two_factor_authenticatable, :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_one_time_password
def send_two_factor_authentication_code(code)
SmsProvider.send_message(to: phone_number, body: code)
end
def phone_number
'14159341234'
end
end

11
spec/rails_app/app/views/home/dashboard.html.erb

@ -1,11 +0,0 @@
<h1>Your Personal Dashboard</h1>
<p>Hi <%= current_user.nickname %></p>
<p>Your registered email address is <%= current_user.email %></p>
<p> Param A is <%= params[:A] %></p>
<p> Param B is <%= params[:B] %></p>
<p>You can only see this page after successfully completing two factor authentication</p>

3
spec/rails_app/app/views/home/index.html.erb

@ -1,3 +0,0 @@
<h1>Welcome Home</h1>
<p>Find me in app/views/home/index.html.erb</p>

20
spec/rails_app/app/views/layouts/application.html.erb

@ -1,20 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>Dummy</title>
<%= stylesheet_link_tag "application", :media => "all" %>
<%= javascript_include_tag "application" %>
<%= csrf_meta_tags %>
</head>
<body>
<nav>
<% if user_signed_in? %>
You are signed in as <%= current_user.nickname %>
<% else %>
You are signed out
<% end %>
</nav>
<%= render_flash %>
<%= yield %>
</body>
</html>

4
spec/rails_app/config.ru

@ -1,4 +0,0 @@
# This file is used by Rack-based servers to start the application.
require ::File.expand_path('../config/environment', __FILE__)
run Dummy::Application

64
spec/rails_app/config/application.rb

@ -1,64 +0,0 @@
require File.expand_path('../boot', __FILE__)
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "sprockets/railtie"
Bundler.require(*Rails.groups)
require "devise_two_factor_authentication"
module Dummy
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
config.autoload_paths += %W(#{config.root}/lib)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
config.active_support.escape_html_entities_in_json = true
# Use SQL instead of Active Record's schema dumper when creating the database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
config.active_record.legacy_connection_handling = false
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.action_mailer.default_url_options = { host: 'localhost:3000' }
config.i18n.enforce_available_locales = false
config.secret_key_base = 'secretvalue'
end
end

10
spec/rails_app/config/boot.rb

@ -1,10 +0,0 @@
require 'rubygems'
gemfile = File.expand_path('../../../../Gemfile', __FILE__)
if File.exist?(gemfile)
ENV['BUNDLE_GEMFILE'] = gemfile
require 'bundler'
Bundler.setup
end
$:.unshift File.expand_path('../../../../lib', __FILE__)

19
spec/rails_app/config/database.yml

@ -1,19 +0,0 @@
# SQLite version 3.x
# gem install sqlite3
#
# Ensure the SQLite 3 gem is defined in your Gemfile
# gem 'sqlite3'
development:
adapter: sqlite3
database: db/development.sqlite3
pool: 5
timeout: 5000
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
adapter: sqlite3
database: db/test.sqlite3
pool: 5
timeout: 5000

5
spec/rails_app/config/environment.rb

@ -1,5 +0,0 @@
# Load the rails application
require File.expand_path('../application', __FILE__)
# Initialize the rails application
Dummy::Application.initialize!

28
spec/rails_app/config/environments/development.rb

@ -1,28 +0,0 @@
Dummy::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
config.eager_load = false
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger
config.active_support.deprecation = :log
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
# Do not compress assets
config.assets.compress = false
# Expands the lines which load the assets
config.assets.debug = true
end

68
spec/rails_app/config/environments/production.rb

@ -1,68 +0,0 @@
Dummy::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
config.eager_load = false
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
end

41
spec/rails_app/config/environments/test.rb

@ -1,41 +0,0 @@
Dummy::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
config.eager_load = false
# Configure static asset server for tests with Cache-Control for performance
if Rails::VERSION::MAJOR == 4 && Rails::VERSION::MINOR >= 2 ||
Rails::VERSION::MAJOR >= 5
config.serve_static_files = true
else
config.serve_static_assets = true
end
config.static_cache_control = "public, max-age=3600"
# Show full error reports and disable caching
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Print deprecation notices to the stderr
config.active_support.deprecation = :stderr
# For testing session variables in Capybara specs
config.middleware.use RackSessionAccess::Middleware
end

7
spec/rails_app/config/initializers/backtrace_silencers.rb

@ -1,7 +0,0 @@
# Be sure to restart your server when you modify this file.
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
# Rails.backtrace_cleaner.remove_silencers!

3
spec/rails_app/config/initializers/cookies_serializer.rb

@ -1,3 +0,0 @@
if Rails.version > '4.1.0'
Rails.application.config.action_dispatch.cookies_serializer = :json
end

258
spec/rails_app/config/initializers/devise.rb

@ -1,258 +0,0 @@
# Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# The secret key used by Devise. Devise uses this key to generate
# random tokens. Changing this key will render invalid all existing
# confirmation, reset password and unlock tokens in the database.
config.secret_key = 'd13ac2811507a08f5af301635a806f4e438d053def28750d6ae77d8c9dd9470dc56df6cf1c40f9fcd8ce5730c2ce69097f7d5a78f6a303b31c5b8d8cbe907a3a'
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class
# with default "from" parameter.
config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com'
# Configure the class responsible to send e-mails.
# config.mailer = 'Devise::Mailer'
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/active_record'
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
# config.authentication_keys = [ :email ]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [ :email ]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [ :email ]
# Tell if authentication through request.params is enabled. True by default.
# It can be set to an array that will enable params authentication only for the
# given strategies, for example, `config.params_authenticatable = [:database]` will
# enable it only for database (email + password) authentication.
# config.params_authenticatable = true
# Tell if authentication through HTTP Auth is enabled. False by default.
# It can be set to an array that will enable http authentication only for the
# given strategies, for example, `config.http_authenticatable = [:database]` will
# enable it only for database authentication. The supported strategies are:
# :database = Support basic authentication with authentication key + password
# config.http_authenticatable = false
# If http headers should be returned for AJAX requests. True by default.
# config.http_authenticatable_on_xhr = true
# The realm used in Http Basic Authentication. 'Application' by default.
# config.http_authentication_realm = 'Application'
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
# config.paranoid = true
# By default Devise will store the user in session. You can skip storage for
# particular strategies by setting this option.
# Notice that if you are skipping storage for all authentication paths, you
# may want to disable generating routes to Devise's sessions controller by
# passing skip: :sessions to `devise_for` in your config/routes.rb
config.skip_session_storage = [:http_auth]
# By default, Devise cleans up the CSRF token on authentication to
# avoid CSRF token fixation attacks. This means that, when using AJAX
# requests for sign in and sign up, you need to get a new CSRF token
# from the server. You can disable this option at your own risk.
# config.clean_up_csrf_token_on_authentication = true
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 10. If
# using other encryptors, it sets how many times you want the password re-encrypted.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments. Note that, for bcrypt (the default
# encryptor), the cost increases exponentially with the number of stretches (e.g.
# a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).
config.stretches = Rails.env.test? ? 1 : 10
# Setup a pepper to generate the encrypted password.
# config.pepper = '4ee5a40e29eaa2141d0d30fe4dbec3e5f11386452c42f4f2e8e159092b839ae4edac028709d4c604c16354a4dab5f70a88bda9d1bb6258bf01b9c3915df472c5'
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming their account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming their account,
# access will be blocked just in the third day. Default is 0.days, meaning
# the user cannot access the website without confirming their account.
# config.allow_unconfirmed_access_for = 2.days
# A period that the user is allowed to confirm their account before their
# token becomes invalid. For example, if set to 3.days, the user can confirm
# their account within 3 days after the mail was sent, but on the fourth day
# their account can't be confirmed with the token any more.
# Default is nil, meaning there is no restriction on how long a user can take
# before confirming their account.
# config.confirm_within = 3.days
# If true, requires any email changes to be confirmed (exactly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field (see migrations). Until confirmed, new email is stored in
# unconfirmed_email column, and copied to email column on successful confirmation.
config.reconfirmable = true
# Defines which key will be used when confirming an account
# config.confirmation_keys = [ :email ]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# Options to be passed to the created cookie. For instance, you can set
# secure: true in order to force SSL only cookies.
# config.rememberable_options = {}
# ==> Configuration for :validatable
# Range for password length.
config.password_length = 8..128
# Email regex used to validate email formats. It simply asserts that
# one (and only one) @ exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
# config.email_regexp = /\A[^@]+@[^@]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# If true, expires auth token on session timeout.
# config.expire_auth_token_on_timeout = false
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
# config.unlock_keys = [ :email ]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
# config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
# config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# Warn on the last attempt before the account is locked.
# config.last_attempt_warning = false
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [ :email ]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 6.hours
# ==> Configuration for :encryptable
# Allow you to use another encryption algorithm besides bcrypt (default). You can use
# :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1,
# :authlogic_sha512 (then you should set stretches above to 20 for default behavior)
# and :restful_authentication_sha1 (then you should set stretches to 10, and copy
# REST_AUTH_SITE_KEY to pepper).
#
# Require the `devise-encryptable` gem when using anything other than bcrypt
# config.encryptor = :sha512
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
# config.scoped_views = false
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
config.default_scope = :user
# Set this configuration to false if you want /users/sign_out to sign out
# only the current scope. By default, Devise signs out all scopes.
config.sign_out_all_scopes = false
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
# config.navigational_formats = ['*/*', :html]
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = Rails.env.test? ? :get : :delete
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
# config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |manager|
# manager.intercept_401 = false
# manager.default_strategies(scope: :user).unshift :some_external_strategy
# end
# ==> Mountable engine configurations
# When using Devise inside an engine, let's call it `MyEngine`, and this engine
# is mountable, there are some extra configurations to be taken into account.
# The following options are available, assuming the engine is mounted as:
#
# mount MyEngine, at: '/my_engine'
#
# The router that invoked `devise_for`, in the example above, would be:
# config.router_name = :my_engine
#
# When using omniauth, Devise cannot automatically set Omniauth path,
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = '/my_engine/users/auth'
config.otp_secret_encryption_key = '0a8283fba984da1de24e4df1e93046cb53c5787944ef037b2dbf3e61d20fe11f25e25a855cec605fdf65b162329890d7230afdf64f681b4c32020281054e73ec'
end

15
spec/rails_app/config/initializers/inflections.rb

@ -1,15 +0,0 @@
# Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format
# (all these examples are active by default):
# ActiveSupport::Inflector.inflections do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end
#
# These inflection rules are supported but not enabled by default:
# ActiveSupport::Inflector.inflections do |inflect|
# inflect.acronym 'RESTful'
# end

5
spec/rails_app/config/initializers/mime_types.rb

@ -1,5 +0,0 @@
# Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
# Mime::Type.register_alias "text/html", :iphone

7
spec/rails_app/config/initializers/secret_token.rb

@ -1,7 +0,0 @@
# Be sure to restart your server when you modify this file.
# Your secret key for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
Dummy::Application.config.secret_token = 'e75d8cdfc7c99757a5d4b427bde4b4b1072eb169c022cdbb038bdbcefb3901ef60ac912b6fb14260db099156520b9cc8838e4bf8e209b7246fad891950825032'

8
spec/rails_app/config/initializers/session_store.rb

@ -1,8 +0,0 @@
# Be sure to restart your server when you modify this file.
Dummy::Application.config.session_store :cookie_store, key: '_rails_app_session'
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rails generate session_migration")
# Dummy::Application.config.session_store :active_record_store

14
spec/rails_app/config/initializers/wrap_parameters.rb

@ -1,14 +0,0 @@
# Be sure to restart your server when you modify this file.
#
# This file contains settings for ActionController::ParamsWrapper which
# is enabled by default.
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: [:json]
end
# Disable root element in JSON by default.
ActiveSupport.on_load(:active_record) do
self.include_root_in_json = false
end

59
spec/rails_app/config/locales/devise.en.yml

@ -1,59 +0,0 @@
# Additional translations at https://github.com/plataformatec/devise/wiki/I18n
en:
devise:
confirmations:
confirmed: "Your account was successfully confirmed."
send_instructions: "You will receive an email with instructions about how to confirm your account in a few minutes."
send_paranoid_instructions: "If your email address exists in our database, you will receive an email with instructions about how to confirm your account in a few minutes."
failure:
already_authenticated: "You are already signed in."
inactive: "Your account is not activated yet."
invalid: "Invalid email or password."
locked: "Your account is locked."
last_attempt: "You have one more attempt before your account will be locked."
not_found_in_database: "Invalid email or password."
timeout: "Your session expired. Please sign in again to continue."
unauthenticated: "You need to sign in or sign up before continuing."
unconfirmed: "You have to confirm your account before continuing."
mailer:
confirmation_instructions:
subject: "Confirmation instructions"
reset_password_instructions:
subject: "Reset password instructions"
unlock_instructions:
subject: "Unlock Instructions"
omniauth_callbacks:
failure: "Could not authenticate you from %{kind} because \"%{reason}\"."
success: "Successfully authenticated from %{kind} account."
passwords:
no_token: "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided."
send_instructions: "You will receive an email with instructions on how to reset your password in a few minutes."
send_paranoid_instructions: "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes."
updated: "Your password was changed successfully. You are now signed in."
updated_not_active: "Your password was changed successfully."
registrations:
destroyed: "Bye! Your account was successfully cancelled. We hope to see you again soon."
signed_up: "Welcome! You have signed up successfully."
signed_up_but_inactive: "You have signed up successfully. However, we could not sign you in because your account is not yet activated."
signed_up_but_locked: "You have signed up successfully. However, we could not sign you in because your account is locked."
signed_up_but_unconfirmed: "A message with a confirmation link has been sent to your email address. Please open the link to activate your account."
update_needs_confirmation: "You updated your account successfully, but we need to verify your new email address. Please check your email and click on the confirm link to finalize confirming your new email address."
updated: "You updated your account successfully."
sessions:
signed_in: "Signed in successfully."
signed_out: "Signed out successfully."
unlocks:
send_instructions: "You will receive an email with instructions about how to unlock your account in a few minutes."
send_paranoid_instructions: "If your account exists, you will receive an email with instructions about how to unlock it in a few minutes."
unlocked: "Your account has been unlocked successfully. Please sign in to continue."
errors:
messages:
already_confirmed: "was already confirmed, please try signing in"
confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one"
expired: "has expired, please request a new one"
not_found: "not found"
not_locked: "was not locked"
not_saved:
one: "1 error prohibited this %{resource} from being saved:"
other: "%{count} errors prohibited this %{resource} from being saved:"

5
spec/rails_app/config/locales/en.yml

@ -1,5 +0,0 @@
# Sample localization file for English. Add more files in this directory for other locales.
# See https://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
en:
hello: "Hello world"

65
spec/rails_app/config/routes.rb

@ -1,65 +0,0 @@
Dummy::Application.routes.draw do
devise_for :admins
root to: "home#index"
match "/dashboard", to: "home#dashboard", as: :dashboard, via: [:get]
devise_for :users
# The priority is based upon order of creation:
# first created -> highest priority.
# Sample of regular route:
# match 'products/:id' => 'catalog#view'
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# match 'products/:id/purchase' => 'catalog#purchase', :as => :purchase
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Sample resource route with options:
# resources :products do
# member do
# get 'short'
# post 'toggle'
# end
#
# collection do
# get 'sold'
# end
# end
# Sample resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Sample resource route with more complex sub-resources
# resources :products do
# resources :comments
# resources :sales do
# get 'recent', :on => :collection
# end
# end
# Sample resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
# You can have the root of your site routed with "root"
# just remember to delete public/index.html.
# root :to => 'welcome#index'
# See how all your routes lay out with "rake routes"
# This is a legacy wild controller route that's not recommended for RESTful applications.
# Note: This route will make all actions in every controller accessible via GET requests.
# match ':controller(/:action(/:id))(.:format)'
end

42
spec/rails_app/db/migrate/20140403184646_devise_create_users.rb

@ -1,42 +0,0 @@
class DeviseCreateUsers < ActiveRecord::Migration[4.2]
def change
create_table(:users) do |t|
## Database authenticatable
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
t.timestamps null: false
end
add_index :users, :email, unique: true
add_index :users, :reset_password_token, unique: true
# add_index :users, :confirmation_token, unique: true
# add_index :users, :unlock_token, unique: true
end
end

15
spec/rails_app/db/migrate/20140407172619_two_factor_authentication_add_to_users.rb

@ -1,15 +0,0 @@
class TwoFactorAuthenticationAddToUsers < ActiveRecord::Migration[4.2]
def up
change_table :users do |t|
t.string :otp_secret_key
t.integer :second_factor_attempts_count, :default => 0
end
add_index :users, :otp_secret_key, :unique => true
end
def down
remove_column :users, :otp_secret_key
remove_column :users, :second_factor_attempts_count
end
end

7
spec/rails_app/db/migrate/20140407215513_add_nickanme_to_users.rb

@ -1,7 +0,0 @@
class AddNickanmeToUsers < ActiveRecord::Migration[4.2]
def change
change_table :users do |t|
t.column :nickname, :string, limit: 64
end
end
end

9
spec/rails_app/db/migrate/20151224171231_add_encrypted_columns_to_user.rb

@ -1,9 +0,0 @@
class AddEncryptedColumnsToUser < ActiveRecord::Migration[4.2]
def change
add_column :users, :encrypted_otp_secret_key, :string
add_column :users, :encrypted_otp_secret_key_iv, :string
add_column :users, :encrypted_otp_secret_key_salt, :string
add_index :users, :encrypted_otp_secret_key, unique: true
end
end

19
spec/rails_app/db/migrate/20151224180310_populate_otp_column.rb

@ -1,19 +0,0 @@
class PopulateOtpColumn < ActiveRecord::Migration[4.2]
def up
User.reset_column_information
User.find_each do |user|
user.otp_secret_key = user.read_attribute('otp_secret_key')
user.save!
end
end
def down
User.reset_column_information
User.find_each do |user|
user.otp_secret_key = ROTP::Base32.random_base32
user.save!
end
end
end

5
spec/rails_app/db/migrate/20151228230340_remove_otp_secret_key_from_user.rb

@ -1,5 +0,0 @@
class RemoveOtpSecretKeyFromUser < ActiveRecord::Migration[4.2]
def change
remove_column :users, :otp_secret_key, :string
end
end

42
spec/rails_app/db/migrate/20160209032439_devise_create_admins.rb

@ -1,42 +0,0 @@
class DeviseCreateAdmins < ActiveRecord::Migration[4.2]
def change
create_table(:admins) do |t|
## Database authenticatable
t.string :email, null: false, default: ""
t.string :encrypted_password, null: false, default: ""
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
t.datetime :remember_created_at
## Trackable
t.integer :sign_in_count, default: 0, null: false
t.datetime :current_sign_in_at
t.datetime :last_sign_in_at
t.string :current_sign_in_ip
t.string :last_sign_in_ip
## Confirmable
# t.string :confirmation_token
# t.datetime :confirmed_at
# t.datetime :confirmation_sent_at
# t.string :unconfirmed_email # Only if using reconfirmable
## Lockable
# t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
# t.string :unlock_token # Only if unlock strategy is :email or :both
# t.datetime :locked_at
t.timestamps null: false
end
add_index :admins, :email, unique: true
add_index :admins, :reset_password_token, unique: true
# add_index :admins, :confirmation_token, unique: true
# add_index :admins, :unlock_token, unique: true
end
end

54
spec/rails_app/db/schema.rb

@ -1,54 +0,0 @@
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# This file is the source Rails uses to define your schema when running `bin/rails
# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[7.0].define(version: 2016_02_09_032439) do
create_table "admins", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at", precision: nil
t.datetime "remember_created_at", precision: nil
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at", precision: nil
t.datetime "last_sign_in_at", precision: nil
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", precision: nil, null: false
t.datetime "updated_at", precision: nil, null: false
t.index ["email"], name: "index_admins_on_email", unique: true
t.index ["reset_password_token"], name: "index_admins_on_reset_password_token", unique: true
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at", precision: nil
t.datetime "remember_created_at", precision: nil
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at", precision: nil
t.datetime "last_sign_in_at", precision: nil
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", precision: nil, null: false
t.datetime "updated_at", precision: nil, null: false
t.integer "second_factor_attempts_count", default: 0
t.string "nickname", limit: 64
t.string "encrypted_otp_secret_key"
t.string "encrypted_otp_secret_key_iv"
t.string "encrypted_otp_secret_key_salt"
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["encrypted_otp_secret_key"], name: "index_users_on_encrypted_otp_secret_key", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
end

0
spec/rails_app/lib/assets/.gitkeep

17
spec/rails_app/lib/sms_provider.rb

@ -1,17 +0,0 @@
require 'ostruct'
class SmsProvider
Message = Class.new(OpenStruct)
class_attribute :messages
self.messages = []
def self.send_message(opts = {})
self.messages << Message.new(opts)
end
def self.last_message
self.messages.last
end
end

26
spec/rails_app/public/404.html

@ -1,26 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>The page you were looking for doesn't exist (404)</title>
<style type="text/css">
body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
div.dialog {
width: 25em;
padding: 0 4em;
margin: 4em auto 0 auto;
border: 1px solid #ccc;
border-right-color: #999;
border-bottom-color: #999;
}
h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
</style>
</head>
<body>
<!-- This file lives in public/404.html -->
<div class="dialog">
<h1>The page you were looking for doesn't exist.</h1>
<p>You may have mistyped the address or the page may have moved.</p>
</div>
</body>
</html>

26
spec/rails_app/public/422.html

@ -1,26 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>The change you wanted was rejected (422)</title>
<style type="text/css">
body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
div.dialog {
width: 25em;
padding: 0 4em;
margin: 4em auto 0 auto;
border: 1px solid #ccc;
border-right-color: #999;
border-bottom-color: #999;
}
h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
</style>
</head>
<body>
<!-- This file lives in public/422.html -->
<div class="dialog">
<h1>The change you wanted was rejected.</h1>
<p>Maybe you tried to change something you didn't have access to.</p>
</div>
</body>
</html>

25
spec/rails_app/public/500.html

@ -1,25 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>We're sorry, but something went wrong (500)</title>
<style type="text/css">
body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
div.dialog {
width: 25em;
padding: 0 4em;
margin: 4em auto 0 auto;
border: 1px solid #ccc;
border-right-color: #999;
border-bottom-color: #999;
}
h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
</style>
</head>
<body>
<!-- This file lives in public/500.html -->
<div class="dialog">
<h1>We're sorry, but something went wrong.</h1>
</div>
</body>
</html>

0
spec/rails_app/public/favicon.ico

9
spec/rails_app/script/rails

@ -1,9 +0,0 @@
#!/usr/bin/env ruby
# frozen_string_literal: true
# This command will automatically be run when you run "rails" with Rails 3
# gems installed from the root of your application.
APP_PATH = File.expand_path('../config/application', __dir__)
require File.expand_path('../config/boot', __dir__)
require 'rails/commands'

27
spec/spec_helper.rb

@ -1,27 +0,0 @@
ENV["RAILS_ENV"] ||= "test"
require File.expand_path("../rails_app/config/environment.rb", __FILE__)
require 'rspec/rails'
require 'timecop'
require 'rack_session_access/capybara'
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
RSpec.configure do |config|
config.run_all_when_everything_filtered = true
config.filter_run :focus
config.use_transactional_examples = true
config.include Capybara::DSL
# Run specs in random order to surface order dependencies. If you find an
# order dependency and want to debug it, you can fix the order by providing
# the seed, which is printed after each run.
# --seed 1234
config.order = 'random'
config.after(:each) { Timecop.return }
end
Dir["#{Dir.pwd}/spec/support/**/*.rb"].each {|f| require f}
Dir["#{Dir.pwd}/spec/rails_app/lib/*.rb"].each {|f| require f}

59
spec/support/authenticated_model_helper.rb

@ -1,59 +0,0 @@
module AuthenticatedModelHelper
def build_guest_user
GuestUser.new
end
def create_user(type = 'encrypted', attributes = {})
create_table_for_nonencrypted_user if type == 'not_encrypted'
User.create!(valid_attributes(attributes))
end
def create_admin
Admin.create!(valid_attributes.except(:nickname))
end
def valid_attributes(attributes={})
{
nickname: 'Marissa',
email: generate_unique_email,
password: 'password',
password_confirmation: 'password'
}.merge(attributes)
end
def generate_unique_email
@@email_count ||= 0
@@email_count += 1
"user#{@@email_count}@example.com"
end
def create_table_for_nonencrypted_user
ActiveRecord::Migration.suppress_messages do
ActiveRecord::Schema.define(version: 1) do
create_table 'users', force: :cascade do |t|
t.string 'email', default: '', null: false
t.string 'encrypted_password', default: '', null: false
t.string 'reset_password_token'
t.datetime 'reset_password_sent_at'
t.datetime 'remember_created_at'
t.integer 'sign_in_count', default: 0, null: false
t.datetime 'current_sign_in_at'
t.datetime 'last_sign_in_at'
t.string 'current_sign_in_ip'
t.string 'last_sign_in_ip'
t.datetime 'created_at', null: false
t.datetime 'updated_at', null: false
t.integer 'second_factor_attempts_count', default: 0
t.string 'nickname', limit: 64
t.string 'otp_secret_key'
t.string 'direct_otp'
t.datetime 'direct_otp_sent_at'
t.timestamp 'totp_timestamp'
end
end
end
end
end
RSpec.configuration.send(:include, AuthenticatedModelHelper)

3
spec/support/capybara.rb

@ -1,3 +0,0 @@
require 'capybara/rspec'
Capybara.app = Dummy::Application

16
spec/support/controller_helper.rb

@ -1,16 +0,0 @@
module ControllerHelper
def sign_in(user = create_user('not_encrypted'))
allow(warden).to receive(:authenticated?).with(:user).and_return(true)
allow(controller).to receive(:current_user).and_return(user)
warden.session(:user)[DeviseTwoFactorAuthentication::NEED_AUTHENTICATION] = true
end
end
RSpec.configure do |config|
config.include Devise::Test::ControllerHelpers, type: :controller
config.include ControllerHelper, type: :controller
config.before(:example, type: :controller) do
@request.env['devise.mapping'] = Devise.mappings[:user]
end
end

42
spec/support/features_spec_helper.rb

@ -1,42 +0,0 @@
require 'warden'
module FeaturesSpecHelper
def warden
request.env['warden']
end
def complete_sign_in_form_for(user)
fill_in "Email", with: user.email
fill_in "Password", with: 'password'
find('.actions input').click # 'Sign in' or 'Log in'
end
def set_cookie key, value
page.driver.browser.set_cookie [key, value].join('=')
end
def get_cookie key
Capybara.current_session.driver.request.cookies[key]
end
def set_tfa_cookie value
set_cookie DeviseTwoFactorAuthentication::REMEMBER_TFA_COOKIE_NAME, value
end
def get_tfa_cookie
get_cookie DeviseTwoFactorAuthentication::REMEMBER_TFA_COOKIE_NAME
end
end
RSpec.configure do |config|
config.include Warden::Test::Helpers, type: :feature
config.include FeaturesSpecHelper, type: :feature
config.before(:each) do
Warden.test_mode!
end
config.after(:each) do
Warden.test_reset!
end
end

5
spec/support/sms_provider.rb

@ -1,5 +0,0 @@
RSpec.configure do |c|
c.before(:each) do
SmsProvider.messages.clear
end
end

11
spec/support/totp_helper.rb

@ -1,11 +0,0 @@
# Helper class to simulate a user generating TOTP codes from a secret key
class TotpHelper
def initialize(secret_key, otp_length)
@secret_key = secret_key
@otp_length = otp_length
end
def totp_code(time = Time.now)
ROTP::TOTP.new(@secret_key, digits: @otp_length).at(time)
end
end

24
devise_two_factor_authentication.gemspec → two_factor_authentication.gemspec

@ -1,15 +1,14 @@
# -*- encoding: utf-8 -*- # -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__) $:.push File.expand_path("../lib", __FILE__)
require "devise_two_factor_authentication/version" require "two_factor_authentication/version"
Gem::Specification.new do |s| Gem::Specification.new do |s|
s.name = "devise_two_factor_authentication" s.name = "two_factor_authentication"
s.version = DeviseTwoFactorAuthentication::VERSION.dup s.version = TwoFactorAuthentication::VERSION.dup
s.authors = ["baarkerlounger"] s.authors = ["Dmitrii Golub"]
s.email = ["baarkerlounger@protonmail.com"] s.email = ["dmitrii.golub@gmail.com"]
s.homepage = "https://github.com/devise2fa/devise_two_factor_authentication" s.homepage = "https://github.com/Houdini/two_factor_authentication"
s.summary = %q{Two factor authentication plugin for devise forked from Houdini/two_factor_authentication} s.summary = %q{Two factor authentication plugin for devise}
s.license = "MIT"
s.description = <<-EOF s.description = <<-EOF
### Features ### ### Features ###
* control sms code pattern * control sms code pattern
@ -18,7 +17,7 @@ Gem::Specification.new do |s|
* your own sms logic * your own sms logic
EOF EOF
s.rubyforge_project = "devise_two_factor_authentication" s.rubyforge_project = "two_factor_authentication"
s.files = `git ls-files`.split("\n") s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
@ -28,13 +27,6 @@ Gem::Specification.new do |s|
s.add_runtime_dependency 'rails', '>= 3.1.1' s.add_runtime_dependency 'rails', '>= 3.1.1'
s.add_runtime_dependency 'devise' s.add_runtime_dependency 'devise'
s.add_runtime_dependency 'randexp' s.add_runtime_dependency 'randexp'
s.add_runtime_dependency 'rotp', '>= 4.0.0'
s.add_runtime_dependency 'encryptor'
s.add_development_dependency 'bundler' s.add_development_dependency 'bundler'
s.add_development_dependency 'rake'
s.add_development_dependency 'rspec-rails', '>= 3.0.1'
s.add_development_dependency 'capybara', '~> 2.5'
s.add_development_dependency 'pry'
s.add_development_dependency 'timecop'
end end
Loading…
Cancel
Save