Passport
Goal
The goal of the Passport1 Node.js module is to authenticate users when they log in. Although the majority of the authentication process is handled by the authentication controller2, the passport is used to validate a user’s password and then return the correct user object from the database.
Current Setup
The passport file can be found at AnScealai/api/config/passport.js
. The
passport is initialised in the AnScealai/api/server.ts
file upon starting the backend
server, and it is imported in the user route located at
AnScealai/api/routes/user.route.js
. When the front-end makes a login
request to this user route via the authentication service3, the route executes the authenticate()
Passport function before passing the request and returned user object to the authentication
controller.
Calling the passport’s authenticate() function before directing to the login function of the
authentication controller (user.route.js
)
In this setup, the Passport is configured for local4 development. (There are 500+ types of authentication, such as for signing into Google or other widespread applications) This is why in the screenshot above the authenticate() function is called for type ‘local’.
Usage
The local Passport authentication strategy authenticates users with a username and password. The strategy requires a verify callback, which accepts these credentials. Calling done() then returns the found user in the DB.
The Passport uses the verify() function (explained below) to find a user that matches the
given username and password. This password is authenticated behind the scenes with
Passport. Passport then uses the serializeUser() function to save the user ID in the current
session as req.session.passport.user = {id: '..'}
. It then uses this ID in
the parameters of the deserializeUser() function to get the entire user object from the DB.
verify() This function takes in a username and password and checks to see if a user with those credentials exists in the DB. If so, the user is returned. The function executes the following steps:
- If there is an error in the mongoose call, the function returns with this error
- Checks if there is a user with the username and password. If there is no user, the function returns with an error.
- Checks if the user has a valid password by calling the validPassword() function in the User model. If not, the function returns with an error
- Checks if a user has ‘Active’ status. If not, the function returns with an error
- Otherwise it returns the user
(This function is called from passport.use(new LocalStrategy(verify))
in
passport.js
. This configuration is used in the
passport.authenticate(‘local’)
function in user.route.js
file when a user
logs in.)
Footnotes
-
Passport: https://www.passportjs.org/ ↩
-
Authentication Controller documentation ↩
-
See Authentication Service documentation ↩
-
Passport Local authentication: https://www.passportjs.org/packages/passport-local/ ↩