Limiting Access
Learn to limit the access of non-verified users.
We'll cover the following
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 sit directly in the admin
controller, but for reasons that’ll become apparent shortly, let’s put it instead in ApplicationController
, the parent class of all our controllers. This is in the application_controller.rb
file in the app/controllers
directory. Note too that we chose to restrict access to this method. This prevents it from ever being exposed to end users as an action:
Get hands-on with 1400+ tech skills courses.