Iteration J3: Limiting 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 you to intercept calls to action methods, adding your 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]. 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 to our login page.

Where ...

Get Agile Web Development with Rails 6 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.