Search⌘ K
AI Features

Limiting Access

Understand how to limit access to administrative sections of a Rails application using before-action callbacks. Learn to implement user authentication by checking session data, applying authorization logic with allowlisting and denylisting techniques, and adjusting test cases accordingly to protect sensitive pages while maintaining user functionality.

Restricting access

We want to prevent people without an administrative login from accessing our site’s admin pages. It turns out that we can do it with very little code using the Rails callback facility.

Rails callbacks allow us to intercept calls to action methods, and add our own processing before they’re invoked, after they return, or both. In our case, we’ll use a before-action callback to intercept all calls to the actions in our admin controller. The interceptor can check session[:user_id] in line 9. If it’s set and if it corresponds to a user in the database, the application knows an administrator is logged in and the call can proceed. If it’s not set, the interceptor can issue a redirect. In this case, it will be to our login page.

Where should we put this method? It could ...