Skip to content

Instantly share code, notes, and snippets.

@bettysteger
Last active September 27, 2023 20:28
Show Gist options
  • Save bettysteger/670a9a3ef0814ff52059dc2e6757e580 to your computer and use it in GitHub Desktop.
Save bettysteger/670a9a3ef0814ff52059dc2e6757e580 to your computer and use it in GitHub Desktop.
devise-two-factor with devise_token_auth (added line 22-33)
# Need to overwrite controller to make a devise-two-factor work with devise_token_auth
# @see https://github.com/lynndylanhurley/devise_token_auth/blob/master/app/controllers/devise_token_auth/sessions_controller.rb
class SessionsController < DeviseTokenAuth::SessionsController
def create
# Check
field = (resource_params.keys.map(&:to_sym) & resource_class.authentication_keys).first
@resource = nil
if field
q_value = get_case_insensitive_field_from_resource_params(field)
@resource = find_resource(field, q_value)
end
if @resource && valid_params?(field, q_value) && (!@resource.respond_to?(:active_for_authentication?) || @resource.active_for_authentication?)
valid_password = @resource.valid_password?(resource_params[:password])
if (@resource.respond_to?(:valid_for_authentication?) && !@resource.valid_for_authentication? { valid_password }) || !valid_password
return render_create_error_bad_credentials
end
# added this IF-block
if @resource.otp_required_for_login? && !@resource.validate_and_consume_otp!(params[:otp_attempt])
if params[:otp_backup_code]
# deactivate 2fa when backup code is valid
if @resource.invalidate_otp_backup_code!(params[:otp_backup_code])
@resource.otp_required_for_login = false
else
return render_error(401, 'bad_backup_code', {need_otp: true})
end
else
return render_error(401, 'bad_otp', {need_otp: true})
end
end
@token = @resource.create_token
@resource.save
sign_in(:user, @resource, store: false, bypass: false)
yield @resource if block_given?
render_create_success
elsif @resource && !(!@resource.respond_to?(:active_for_authentication?) || @resource.active_for_authentication?)
if @resource.respond_to?(:locked_at) && @resource.locked_at
render_create_error_account_locked
else
render_create_error_not_confirmed
end
else
render_create_error_bad_credentials
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment