-
Notifications
You must be signed in to change notification settings - Fork 0
24 Requiring Authentication
We've seen how to hide things from unauthenticated users in our views. What about enforcing authentication at the controller level? For example, suppose we don't want anonymous users creating posts and categories. We could—and will—hide those buttons in the sidebar, but that wouldn't stop anyone from browsing directly to those views if they know (or can guess) the URL.
Devise once again provides a helper method for such a thing. To require authentication on all methods of a controller, add the following before_action
:
before_action :authenticate_user!
If we were to add that to PostsController
, unauthenticated users couldn't do anything with posts—including seeing them. We don't need to be quite that restrictive. As with any before_action
, we can limit it to only certain methods. Add the following to PostsController
:
app/controllers/posts_controller.rb
before_action :authenticate_user!, only: [:new, :create, :edit, :update, :destroy]
Do the same in CategoriesController
. We haven't fully implemented CRUD for categories, but we know we'll require authentication on those methods if and when we do implement them.
Try adding a post or a category while logged out now. You can't do it, but those buttons are still in the sidebar, tempting you. It's arguably not a bad idea to leave it that way, as it provides an incentive for people to sign up when they click those links and are confronted with the opportunity to register.
Let's commit what we have.
$ git add .
$ git commit -m "Limit unauthenticated users to read-only actions on posts and categories."
As an exercise, let's hide the sidebar links from unauthenticated users. I'll leave it up to you whether you want to commit your changes or stash them when you're done.
Only show the sidebar links to logged in users.