Created
June 12, 2020 22:16
-
-
Save tbcooney/98f2b69ca7c9b584e7dbc2e9c553231d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
# == AuthenticatesWithTwoFactor | |
# | |
# Controller concern to handle two-factor authentication | |
module AuthenticatesWithTwoFactor | |
extend ActiveSupport::Concern | |
def prompt_for_two_factor(user) | |
@user = user | |
# Save the user's ID to session so we can ask for a one-time password | |
session[:otp_user_id] = user.id | |
render 'users/sessions/two_factor' | |
end | |
def authenticate_with_two_factor | |
user = self.resource = find_user | |
return unless user && user.otp_required_for_login | |
if user_params[:otp_attempt].present? && session[:otp_user_id] | |
authenticate_with_two_factor_via_otp(user) | |
elsif user && user.valid_password?(user_params[:password]) | |
prompt_for_two_factor(user) | |
end | |
end | |
def authenticate_with_two_factor_via_otp(user) | |
if valid_otp_attempt?(user) | |
# Remove any lingering user data from login | |
session.delete(:otp_user_id) | |
sign_in(user) | |
else | |
flash[:alert] = 'Invalid two-factor code.' | |
prompt_for_two_factor(user) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment