Signup and Login with Node.js
Below is a rundown of what happens in my backend code when a user signs up, logs in, and does something that requires user authentication in the website.
Libraries used: JOI, Bcrypt, Jsonwebtoken
Signup
1. User submits userId, nickname, password, passwordConfirm at the frontend.
2. userId, nickname, password, passwordConfirm get sent to the server via API.
3. Server checks whether the 4 inputs meet the schema through JOI. If fail, return error.
4. Server checks whether the confirmPassword matches the password. And it checks the database to make sure there are no overlaps in the database for userId and nickname. If fail, return error.
5. Server encrypts the password with Bcrypt. If fail, return error.
6. Server adds userId, nickname, and encrypted password to the data table. If fail, return error.
7. If all of the above is successful, server returns status 201, and the frontend moves to the login page.
If not successful, server returns error, and relevant error message is shown to the user at frontend.
Login
1. User submits userId and password at the frontend.
2. Frontend sends userId and password input value to backend via API.
3. Backend receives the input values by request.body.
4. Backend finds the userId in the database. If fail, return error message ‘Incorrect ID or password’.
5. Backend checks the password with Bcrypt’s compare() function. If fail, return error message ‘Incorrect ID or password’.
6. Backend creates json web token with jwt.sign method. If fail, return.
7. Backend sends the token to frontend.
8. Frontend stores the token and authenticates the user.
CHECKING TOKEN
1. User does something on the website that requires authorization.
2. Frontend sends the token on request.headers via API.
3. In the middleware javascript file…
i. Receive token via request.headers.
ii. Separate the token type and the token string.
iii. Check if token type is correct and that token string exists. If fail, return.
iv. Using jwt.verify() method, verify the token string with the secret key. If fail, return.
v. Extract userId from the verified token.
vi. Find the matching userId in the user database. If matching user does not exist, return.
vii. Allocate relevant user information to res.locals. Res.locals is an object that contains response local variables scoped to the request. So it is only available to the view(s) rendered in that specific request-response cycle. The variable declared with res.locals is now available in all functions that call on this middleware.
viii. If all of the above is successful, call next();. Else, return error ‘you must log in first.’
4. After token verification is done, the backend proceeds to do whatever it was supposed to do with that particular function. aka next();
LOG OUT
1. User clicks ‘log out’ button
2. At the frontend, local.storage.clear();
3. Send user to login page