Last active
August 29, 2025 18:24
-
-
Save arandilopez/5a094e11c31fb2f04fcbed03e1b85ad8 to your computer and use it in GitHub Desktop.
Rails route helper for authentication constraints
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# config/routes.rb | |
# Usage example | |
authenticated do | |
root to: "dashboard#index", as :dashboard | |
end | |
root to: "public#index" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# config/initializers/routing_helpers.rb | |
class AuthenticatedConstraint | |
def matches?(request) | |
cookies = ActionDispatch::Cookies::CookieJar.build(request, request.cookies) | |
if (session_id = cookies.signed[:session_id]) | |
return true if Session.find_by(id: session_id) | |
end | |
false | |
rescue => _ | |
false | |
end | |
end | |
module RoutingHelpers | |
def authenticated(options = {}, &block) | |
constraint = AuthenticatedConstraint.new | |
constraints(constraint, &block) | |
end | |
end | |
ActionDispatch::Routing::Mapper.include(RoutingHelpers) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment