Login Routes
Step One: Add login route
For login, we need to write a "/login" route to render to the login page.
At the same time, we need to create login page in the "view" folder.
Step Two: Set up the local strategy
Then, we need to set up the local strategy to be "user authenticate".
Step Three: Write post route and add middle-ware
Inside the app.post, we pass in "passport.authenticate", which is a middle-ware. It allows codes that run before our final route call back. When app gets a post request to "/login", it's going to run this code immediately.
Step Four: Run the app
We run the app and can see the login form.
Then, for every page, we add three links: sign up, login, and logout.
So the homepage will look like this:
Logout Routes
Logout routes are very simple.We need to create a "/logout" route which will log user out and redirect to the homepage. When we log user out, we are not changing anything in the database. What is happening is that passport is destroying all user data in the session.
Then, we add a middle-ware to check if the user is logged in or not. The function "is loggedIn " takes three parameters: request, response and next.
If it is logged in, it's going to check the request authenticated. If it is, then return to next. The next will be the "secret" page.
At the end, we also need to add "is loggedIn" in the secret route. When a request comes in a Get request to "/secret", it's going to run "isloggedIn" function code before it does anything else.
That' all! It is a long process. At the end, we can sign up the page, and log in to the secret page and then log out.
Comments
Post a Comment