1

I am trying setup Authlogic gem with rails 7. I have simple controller:

class UsersController < ApplicationController
  def new
    render_page 'Registration'
  end

  def create
    @user = User.new(email: 'codcore@gmail.com', password: 415561)
    if @user.save
      redirect_to root_url
    else
      render_page 'Registration', props: { errors: @user.errors_codes }
    end
  end

  private

  def user_params
    params.require(:user).permit(:name, :surname, :email, :password, :password_confirmation).to_h
  end
end

and simple User model:

class User < ApplicationRecord
  self.inheritance_column = 'there_is_no_sti_here'

  acts_as_authentic do |c|
    c.session_class = Session
    c.crypto_provider = ::Authlogic::CryptoProviders::BCrypt
  end
end

But when I call create action of UsersController, I get error:

NameError - wrong constant name 
      Object.const_get(camel_cased_word)
            ^^^^^^^^^^:
  app/controllers/users_controller.rb:8:in `create'

That error refers to @user.save in UsersController. I can not figure out what is happenning. I tried to debug this line, but did not understand what is going on. Also I tried authlogic gem right from the GitHub repository, but it didn't help.

The most interesing part that all works as intended when I create new instnce of User and then save it from rails console...

Kavachaj
  • 411
  • 1
  • 4
  • 15
  • 1
    Is there any more to the stack trace than you've shared? When you can save from the command line, are you passing the same arguments (email and password) to 'new'? – Jake Worth Jun 03 '22 at 15:45
  • 1
    Just a hunch from reading some code; I think there's an issue with the `session_class`. I think that could be ending up here and trying to reference a constant that doesn't exist. https://github.com/binarylogic/authlogic/blob/5e0253dcd91ea72c9a5acc5f62590142b7f4bdb4/lib/authlogic/acts_as_authentic/session_maintenance.rb#L74 – Jake Worth Jun 03 '22 at 15:52
  • @JakeWorth thank you, I get rid of `session_class` call, and it worked! – Kavachaj Jun 05 '22 at 11:02
  • I'd be happy to review a PR improving the error message here. Perhaps we could `rescue` the `NameError` and raise something better? – Jared Beck Jun 06 '22 at 18:48

1 Answers1

2

Looks like it's failing here:

@klass ||= klass_name ? klass_name.constantize : nil

When it tries to get klass_name from session_class you've set:

# The model name, guessed from the session class name, e.g. "User",
# from "UserSession".
#
# TODO: This method can return nil. We should explore this. It seems
# likely to cause a NoMethodError later, so perhaps we should raise an
# error instead.
#
# @api private
def klass_name
  return @klass_name if instance_variable_defined?(:@klass_name)
  @klass_name = name.scan(/(.*)Session/)[0]&.first
end

In this case you should either configure authenticate_with User or rename Session to UserSession so it could get the correct name.

faron
  • 1,051
  • 7
  • 9