In this exercise, we’ll take a look at the endpoints to log in a user.
In order to log in a user we first need a POST
request that takes in user credentials. We can add passport middleware in order to process the authentication and, if successful, serialize the user for us:
app.post("/login", passport.authenticate("insertStrategyHere", { failureRedirect : "/insertPathHere"}), (req, res) => { res.redirect("profile"); } );
We’re passing in passport.authenticate()
as middleware. Using this middleware allows Passport.js to take care of the authentication process behind the scenes and creates a user session for us.
passport.authenticate()
takes in:
- A string specifying which strategy to employ. In this case, we should use a
local
strategy. - An optional object as the second argument. In this case, we should set the
failureRedirect
key to"/login"
. This will redirect the user to the/login
page if the login process fails.
Once implemented, we can update the "/profile"
endpoint to make use of the serialized user found in the request object, req.user
:
app.get("/profile", (req, res) => { res.render("insertDashboardNameHere", { user: req.user }); });
This will render our profile
view page along with the user data stored in the session!
Instructions
A POST
request to log in has been provided, app.post("/login"...)
, but it’s missing the Passport middleware. Add the proper middleware to authenticate a user.
You can leave the parameters empty for now.
Type node app.js
into the Terminal to start the node app.
Press the Check Work button to check your work for each checkpoint.
Provide the right parameters to authenticate a user and redirect them to the "/login"
page if login is not successful.
Update the "/profile
“ endpoint to pass in the user
object found in the request object.
If you haven’t already, in the terminal run the command:
node app.js
Press the circular arrow button in the mini-browser to load the webpage.
Within the mini-browser attempt to log in with the following credentials:
- Username:
sam
- Password:
[email protected]