Creating the user login endpoint for our CCA app – Part 8
userRouter.js
The above code sets up two new routes for member login in an Express router. Do remember to uncomment the 2
lines of codes in server.js that is related to userRouter.js
Member Login Route: This is a POST route at the /login-member endpoint. It calls the memberLogin func on with
the request body, the role “member”, and the response object. This route is used to log in an user who has the
member role.
President Login Route: This is a POST route at the /login-president endpoint. It calls the memberLogin func on
with the request body, the role “president”, and the response object. This route is used to log in an user who has
the president role.
authFunctions.js
The above code sets up one new func on memberLogin.
memberLogin Func on: This is an asynchronous func on that takes in a request object (req), a role, and a response
object (res). It performs the following steps:
Extracts the name and password from the request object.
Queries the database for a member with the given name.
If no member is found, it sends a 404 status response with an error message.
If a member is found, it checks if the member’s role matches the provided role. If not, it sends a 403
status response with an error message.
If the member’s role matches the provided role, it verifies the password using bcrypt.compare.
If the password is correct, it signs a JSON Web Token (JWT) with the member’s role, name, and
email, and an expira on me of 3 days. It then sends a 200 status response with the member’s
details, the token, and a success message.
If the password is incorrect, it sends a 403 status response with an error message.
Test out the Login endpoint /login-member (correct creden als)
Test out the Login endpoint /login-president (wrong creden als)
Test out the Login endpoint /login-president (correct creden als)
Test out the Login endpoint /login-member (incorrect role)