ruby-on-railsrubyclearance

How to extend clearance's back door to allow for 2FA


I have an application which uses the Clearance gem for authentication, but also implements 2FA. I want to use the "Backdoor" functionality of Clearance for tests, but am unsure how to do this in conjunction with 2FA.

Is there a way I can "hook into" Clearance's Backdoor functionality and set the required 2FA values whenever it is used to sign in?


Solution

  • Based on the source of Clearance::Backdoor, if you're trying to set extra values on a user model, this might work:

      # config/environments/test.rb
      MyRailsApp::Application.configure do
        # ...
        config.middleware.use Clearance::BackDoor do |username|
          user = User.find_by(username: username) # or however you'd find a user
          # set your extra values
          user.x = 'x'
          user.y = 'y'
          # return the user
          user
        end
      end
    

    If you want to mess with the request I don't think you can use Clearance::Backdoor, but you could add another Rack middleware after it using config.middleware.insert_after(Clearance::Backdoor) (you would have to write your own middleware).

    As an alternative, a lot of tests I've seen just mock the piece of code that checks whether a user is signed in, and make it always return true (or whatever indicates success).