Compare commits
4 Commits
master
...
for_active
Author | SHA1 | Date |
---|---|---|
Dmitrii Golub | 7e77b61311 | 12 years ago |
Ilan | f2280eb620 | 12 years ago |
Ilan | 865e27c125 | 12 years ago |
Dmitrii Golub | e398f0977f | 12 years ago |
99 changed files with 233 additions and 3319 deletions
@ -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 |
||||
|
@ -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 |
@ -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)* |
@ -1,16 +1 @@
|
||||
# frozen_string_literal: true |
||||
|
||||
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 |
||||
require "bundler/gem_tasks" |
||||
|
@ -1,88 +1,43 @@
|
||||
require 'devise/version' |
||||
|
||||
class Devise::TwoFactorAuthenticationController < DeviseController |
||||
prepend_before_action :authenticate_scope! |
||||
before_action :prepare_and_validate, :handle_two_factor_authentication |
||||
class Devise::TwoFactorAuthenticationController < ActiveAdmin::Devise::SessionsController # DeviseController |
||||
prepend_before_filter :authenticate_scope! |
||||
before_filter :prepare_and_validate, :handle_two_factor_authentication |
||||
|
||||
def show |
||||
end |
||||
|
||||
def update |
||||
render :show, status: :unprocessable_entity and return if params_code.empty? |
||||
|
||||
if resource.authenticate_otp(params_code) |
||||
after_two_factor_success_for(resource) |
||||
render :show and return if params[:code].nil? |
||||
md5 = Digest::MD5.hexdigest(params[:code]) |
||||
if md5.eql?(resource.second_factor_pass_code) |
||||
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 |
||||
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 |
||||
|
||||
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 |
||||
|
||||
def after_two_factor_success_for(resource) |
||||
set_remember_two_factor_cookie(resource) |
||||
|
||||
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 |
||||
def authenticate_scope! |
||||
self.resource = send("current_#{resource_name}") |
||||
end |
||||
end |
||||
|
||||
def authenticate_scope! |
||||
self.resource = send("current_#{resource_name}") |
||||
end |
||||
|
||||
def prepare_and_validate |
||||
redirect_to :root and return if resource.nil? |
||||
@limit = resource.max_login_attempts |
||||
if resource.max_login_attempts? |
||||
sign_out(resource) |
||||
render :max_login_attempts_reached, status: :unprocessable_entity and return |
||||
def prepare_and_validate |
||||
redirect_to :root and return if resource.nil? |
||||
@limit = resource.class.max_login_attempts |
||||
if resource.max_login_attempts? |
||||
sign_out(resource) |
||||
render :template => 'devise/two_factor_authentication/max_login_attempts_reached' and return |
||||
end |
||||
end |
||||
end |
||||
|
||||
def params_code |
||||
params[:code] || params.dig(resource_name, :code) |
||||
end |
||||
end |
||||
|
@ -1,3 +1,3 @@
|
||||
<h2><%= I18n.t("devise.two_factor_authentication.max_login_attempts_reached") %> = <%= @limit %>.</h2> |
||||
<p><%= I18n.t("devise.two_factor_authentication.contact_administrator") %></p> |
||||
<h2>Access completely denied as you have reached your attempts limit = <%= @limit %>.</h2> |
||||
<p>Please contact your system administrator.</p> |
||||
|
||||
|
@ -1,19 +1,10 @@
|
||||
<% if resource.direct_otp %> |
||||
<h2>Enter the code that was sent to you</h2> |
||||
<% else %> |
||||
<h2>Enter the code from your authenticator app</h2> |
||||
<% end %> |
||||
<h2>Enter your personal code</h2> |
||||
|
||||
<p><%= flash[:notice] %></p> |
||||
|
||||
<%= form_tag([resource_name, :two_factor_authentication], :method => :put) do %> |
||||
<%= text_field_tag :code, '', autofocus: true %> |
||||
<%= text_field_tag :code %> |
||||
<%= submit_tag "Submit" %> |
||||
<% end %> |
||||
|
||||
<% if resource.direct_otp %> |
||||
<%= 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 %> |
||||
<%= link_to "Sign out", destroy_admin_user_session_path, :method => :delete %> |
||||
|
@ -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." |
@ -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." |
@ -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é." |
@ -1,8 +0,0 @@
|
||||
ru: |
||||
devise: |
||||
two_factor_authentication: |
||||
success: "Двухфакторная авторизация успешно пройдена." |
||||
attempt_failed: "Неверный код." |
||||
max_login_attempts_reached: "Доступ заблокирован. Превышено число попыток авторизации" |
||||
contact_administrator: "Пожалуйста, свяжитесь с системным администратором." |
||||
code_has_been_sent: "Ваш персональный код был отправлен." |
@ -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' |
@ -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 |
@ -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 |
@ -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 |
@ -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 |
@ -1,7 +0,0 @@
|
||||
module DeviseTwoFactorAuthentication |
||||
class Engine < ::Rails::Engine |
||||
ActiveSupport.on_load(:action_controller) do |
||||
include DeviseTwoFactorAuthentication::Controllers::Helpers |
||||
end |
||||
end |
||||
end |
@ -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 |
@ -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 |
@ -1,3 +0,0 @@
|
||||
module DeviseTwoFactorAuthentication |
||||
VERSION = "3.0.0".freeze |
||||
end |
@ -1,15 +1,8 @@
|
||||
class TwoFactorAuthenticationAddTo<%= table_name.camelize %> < ActiveRecord::Migration |
||||
disable_ddl_transaction! |
||||
|
||||
def change |
||||
add_column :<%= table_name %>, :second_factor_attempts_count, :integer, default: 0 |
||||
add_column :<%= table_name %>, :encrypted_otp_secret_key, :string |
||||
add_column :<%= table_name %>, :encrypted_otp_secret_key_iv, :string |
||||
add_column :<%= table_name %>, :encrypted_otp_secret_key_salt, :string |
||||
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 |
||||
change_table :<%= table_name %> do |t| |
||||
t.string :second_factor_pass_code , :limit => 32 |
||||
t.integer :second_factor_attempts_count, :default => 0 |
||||
end |
||||
end |
||||
end |
||||
|
@ -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' |
@ -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 |
@ -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 |
@ -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 |
@ -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 |
@ -0,0 +1,7 @@
|
||||
module TwoFactorAuthentication |
||||
class Engine < ::Rails::Engine |
||||
ActiveSupport.on_load(:action_controller) do |
||||
include TwoFactorAuthentication::Controllers::Helpers |
||||
end |
||||
end |
||||
end |
@ -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 |
@ -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 |
@ -0,0 +1,3 @@
|
||||
module TwoFactorAuthentication |
||||
VERSION = "0.2".freeze |
||||
end |
@ -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 |
@ -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 |
@ -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 |
@ -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 |
@ -1,3 +0,0 @@
|
||||
# Dummy |
||||
|
||||
You have found the dummy rails app used for integration testing of the `two_factor_authentication` gem. |
@ -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 |
@ -1,2 +0,0 @@
|
||||
//= link_directory ../javascripts .js
|
||||
//= link_directory ../stylesheets .css
|
@ -1 +0,0 @@
|
||||
//= require_tree .
|
@ -1,4 +0,0 @@
|
||||
/* |
||||
*= require_self |
||||
*= require_tree . |
||||
*/ |
@ -1,3 +0,0 @@
|
||||
class ApplicationController < ActionController::Base |
||||
protect_from_forgery |
||||
end |
@ -1,10 +0,0 @@
|
||||
class HomeController < ApplicationController |
||||
before_action :authenticate_user!, only: :dashboard |
||||
|
||||
def index |
||||
end |
||||
|
||||
def dashboard |
||||
end |
||||
|
||||
end |
@ -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 |
@ -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 |
@ -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 |
@ -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 |
@ -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 |
@ -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> |
@ -1,3 +0,0 @@
|
||||
<h1>Welcome Home</h1> |
||||
|
||||
<p>Find me in app/views/home/index.html.erb</p> |
@ -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> |
@ -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 |
@ -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 |
@ -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__) |
@ -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 |
@ -1,5 +0,0 @@
|
||||
# Load the rails application |
||||
require File.expand_path('../application', __FILE__) |
||||
|
||||
# Initialize the rails application |
||||
Dummy::Application.initialize! |
@ -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 |
@ -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 |
@ -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 |
@ -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! |
@ -1,3 +0,0 @@
|
||||
if Rails.version > '4.1.0' |
||||
Rails.application.config.action_dispatch.cookies_serializer = :json |
||||
end |
@ -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 |
@ -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 |
@ -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 |
@ -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' |
@ -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 |
@ -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 |
@ -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:" |
@ -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" |
@ -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 |
@ -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 |
@ -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 |
@ -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 |
@ -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 |
@ -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 |
@ -1,5 +0,0 @@
|
||||
class RemoveOtpSecretKeyFromUser < ActiveRecord::Migration[4.2] |
||||
def change |
||||
remove_column :users, :otp_secret_key, :string |
||||
end |
||||
end |
@ -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 |
@ -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 |
@ -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 |
@ -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> |
@ -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> |
@ -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> |
@ -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' |
@ -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} |
@ -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) |
@ -1,3 +0,0 @@
|
||||
require 'capybara/rspec' |
||||
|
||||
Capybara.app = Dummy::Application |
@ -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 |
@ -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 |
@ -1,5 +0,0 @@
|
||||
RSpec.configure do |c| |
||||
c.before(:each) do |
||||
SmsProvider.messages.clear |
||||
end |
||||
end |
@ -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 |
Loading…
Reference in new issue