Authenticating Users
Learn to authenticate the newly added users and make a login panel.
We'll cover the following...
What does it mean to add login support for administrators of our store?
-
We need to provide a form that allows them to enter a username and password.
-
Once they’re logged in, we need to record that fact for the rest of the session or until they log out.
-
We need to restrict access to the administrative parts of the application, allowing only people who are logged in to administer the store.
We could put all of the logic into a single controller, but it makes more sense to split it into two: a session controller to support logging in and out and a controller to welcome administrators:
depot> bin/rails generate controller Sessions new create destroy
depot> bin/rails generate controller Admin index
A live terminal
You can run the above commands to generate the controller in the terminal provided below.
The SessionsController#create
action will need to record something in session
to say that an administrator is logged in. Let’s have it store the ID of that person’s User
object using the key :user_id
. The login code looks like this:
def createuser = User.find_by(name: params[:name])if user.try(:authenticate, params[:password])session[:user_id] = user.idredirect_to admin_urlelseredirect_to login_url, alert: "Invalid user/password combination"endend
This code makes use of the Rails try()
method in line 3, which ...