I began my day by adding a word_count inside the User table because we needed to store how many words the user has used for the day. Because, the words are limited by 80000words/day.
For accessing datas of users, i added some static functions in the class User and create a userController to regroup these functions:
updateUserWordsCount()
getUserFromEmail()
getUserWordsCount()
getToken()
I installed jwt package so we can secure the token and create valid token based on the payload containing the email of the user and its expiration date.
npm install jsonwebtoken
I didn’t know how to configure the authentication middleware because in nest, it’s based on strategies and guards modules. So i checked on https://openclassrooms.com/fr/courses/6390246-passez-au-full-stack-avec-node-js-express-et-mongodb/6466605-configurez-le-middleware-dauthentification.
I put some error handling in the middleware if the header “authorization” with its bearer/token was wrong, bad written or empty. Then i checked for the email inside the payload if it’s corresponding to the user’s one in db and i put the email in the request for later.
I needed to extends to Request interface to add a specific member that can contains the email. I’ll need this to update the word_count inside the database.
export interface AuthenticatedRequest extends Request {
auth?: string;
}
I had some problem for the interfaces. If i put the interface inside a interfaces.ts, it showed some error. So i let the declaration of the interface inside the userController.ts to avoid complexities and create useless files or most-empty files/folders.
I took the opportunity to add a middleware for error handling, because sometimes i couldn’t catch an error. Especially on the example down below:
app.use((req: Request, res: Response, next) => {
if (req.headers['content-type'] === 'application/json') {
express.json()(req, res, next);
Here, if the json wasn’t written correctly, it crashes the server and the error is not well handled.
app.use((err: HttpError, req: Request, res: Response, next: () => void) => {
res.status(err.statusCode || 500).json({ error: err.message });
});