Skip to content

Instantly share code, notes, and snippets.

@tbcooney
Created June 12, 2020 22:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tbcooney/98f2b69ca7c9b584e7dbc2e9c553231d to your computer and use it in GitHub Desktop.
Save tbcooney/98f2b69ca7c9b584e7dbc2e9c553231d to your computer and use it in GitHub Desktop.
# 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