2017-02-06 16:07:37 +00:00
|
|
|
# == EnforcesTwoFactorAuthentication
|
|
|
|
#
|
|
|
|
# Controller concern to enforce two-factor authentication requirements
|
|
|
|
#
|
2017-03-07 18:48:57 +00:00
|
|
|
# Upon inclusion, adds `check_two_factor_requirement` as a before_action,
|
|
|
|
# and makes `two_factor_grace_period_expired?` and `two_factor_skippable?`
|
2017-02-06 16:07:37 +00:00
|
|
|
# available as view helpers.
|
|
|
|
module EnforcesTwoFactorAuthentication
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
|
|
|
included do
|
2017-03-07 18:48:57 +00:00
|
|
|
before_action :check_two_factor_requirement
|
2017-02-06 16:07:37 +00:00
|
|
|
helper_method :two_factor_grace_period_expired?, :two_factor_skippable?
|
|
|
|
end
|
|
|
|
|
2017-03-07 18:48:57 +00:00
|
|
|
def check_two_factor_requirement
|
2017-02-06 16:07:37 +00:00
|
|
|
if two_factor_authentication_required? && current_user && !current_user.two_factor_enabled? && !skip_two_factor?
|
|
|
|
redirect_to profile_two_factor_auth_path
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def two_factor_authentication_required?
|
|
|
|
current_application_settings.require_two_factor_authentication? ||
|
|
|
|
current_user.try(:require_two_factor_authentication?)
|
|
|
|
end
|
|
|
|
|
2017-03-08 11:09:15 +00:00
|
|
|
def two_factor_authentication_reason(global: -> {}, group: -> {})
|
|
|
|
if two_factor_authentication_required?
|
|
|
|
if current_application_settings.require_two_factor_authentication?
|
|
|
|
global.call
|
|
|
|
else
|
|
|
|
groups = current_user.groups.where(require_two_factor_authentication: true).reorder(name: :asc)
|
|
|
|
group.call(groups)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2017-02-06 16:07:37 +00:00
|
|
|
def two_factor_grace_period
|
|
|
|
periods = [current_application_settings.two_factor_grace_period]
|
|
|
|
periods << current_user.two_factor_grace_period if current_user.try(:require_two_factor_authentication?)
|
|
|
|
periods.min
|
|
|
|
end
|
|
|
|
|
|
|
|
def two_factor_grace_period_expired?
|
|
|
|
date = current_user.otp_grace_period_started_at
|
|
|
|
date && (date + two_factor_grace_period.hours) < Time.current
|
|
|
|
end
|
|
|
|
|
|
|
|
def two_factor_skippable?
|
|
|
|
two_factor_authentication_required? &&
|
|
|
|
!current_user.two_factor_enabled? &&
|
|
|
|
!two_factor_grace_period_expired?
|
|
|
|
end
|
|
|
|
|
|
|
|
def skip_two_factor?
|
2017-03-07 18:51:22 +00:00
|
|
|
session[:skip_two_factor] && session[:skip_two_factor] > Time.current
|
2017-02-06 16:07:37 +00:00
|
|
|
end
|
|
|
|
end
|