Auth Controllers & Hooks
So far, you have defined the User
model and written a script to create new users with their password and email address. The next step is to create a controller to log users in or out.
Here is the architecture that we want:
- Users open the page
/signin
, enter their credentials and then are redirected to the page/
if the credentials are correct. If they are not, the page is refreshed with an error message. - Users can view, create and delete their todos in the page
/
. - When they click the button
Log out
, they are deconnected and redirected to the page/signin
.
When the user presses the Log in
button in the login page, the page requests POST /auth/login
with the credentials as body.
When the user presses the Log out
button in the todo-list page, the page requests POST /auth/logout
.
In this scenario, the authentication process is handled with sessions and http redirections. You will not use JWT tokens which are sometimes used in Single Page Applications (SPA).
#
The Login and Main PagesDownload the html, css and js files by clicking here.
Empty the public/
directory.
Then move script.js
and style.css
to public/
and the index.html
, signin.html
and signup.html
files to a new directory templates/
at the root of your project.
Open the app.controller.ts
file and add three new routes to serve the pages.
Open your browser and go to http://localhost:3001/signin
. The login page should show up.
#
Login ControllersThe next step is to create a controller that logs the users in or out and redirects them after the operation succeeds or fails. It needs two routes /login
and /logout
.
The
--register
flag directly adds a new line inapp.controller.ts
to declare theAuthController
as a sub-controller ofAppController
.
Open the new file auth.controller.ts
and replace its content.
Writting
User.findOne({ email: email, password: password })
cannot work since the password needs to be hashed.
Go back to your browser and try to log in with the email john@foalts.org
and the password mary_password
. You are redirected to the same page and the message Invalid email or password.
shows up. Now use the password john_password
and try to log in. You are redirected to the todo-list page where all todos are listed. If you click on the button Log out
you are then redirected to the login page!
#
Access controlGreat, so far you can authenticate users. But as you have not yet added access control to the todo-list page and the API, unauthenticated users can still access it.
The usual way to handle authorization is to use a hook. In this case, you are going to use the built-in hook UserRequired
which returns a 401 error or redirects the user if user is not logged in.
Update app.controller.ts
.
Update api.controller.ts
.
When a hook decorates a controller class, it applies to all the routes of the controller and its sub-controllers.
Go to http://localhost:3001
. If you are not logged in you should be redirected to the login page.