janko / rodauth-rails

Rails integration for Rodauth authentication framework
https://github.com/jeremyevans/rodauth
MIT License
584 stars 40 forks source link

Issue when requiring authentication following README guidelines #32

Closed nicolas-besnard closed 3 years ago

nicolas-besnard commented 3 years ago

Readme is mentionning that authentication can be achieved at Rails route level with the following code:

# config/routes.rb
Rails.application.routes.draw do
  constraints -> (r) { r.env["rodauth"].require_authentication } do
    namespace :admin do
      # ...
    end
  end
end

This code is working when the user is not logged (accessing this route will redirect to the login page), but once logged in, the route can no be accessed.

r.env["rodauth"].require_authentication returns nil when the user is authenticated so the constraints does not match thus the route can not be accessed.

I've created a branch with a failing test: https://github.com/nicolas-besnard/rodauth-rails/commit/53e3af66b5663cb79042ad839994d377639260f0

janko commented 3 years ago

Thanks for the report. Yeah, that's a good analysis. Something like this should work:

constraints -> (r) { r.env["rodauth"].authenticated? or r.env["rodauth"].require_authentication } do
  # ...
end

Given that this is pretty long for someone to write, I was thinking of creating helper methods for these constraints, so that the user can call:

constraints Rodauth::Rails.authentication_constraint do # authenticated? or require_authentication
  # ...
end

or

constraints Rodauth::Rails.login_constraint do # logged_in? or require_login
  # ...
end

What do you think?

nicolas-besnard commented 3 years ago

Good idea to have this build in the gem!

Looking at Rodauth documentation, it offers a large variety of check on the logged in user (logged_in?, authenticated?, verified_account? etc..)

Rodauth::Rails.logged_in_constraint seems to be a good idea to start