😊Users Me Route

Snippets and good practices for users

User me Route

router.get('/me', auth, UserController.me);

Explanation

  • HTTP Method: GET

  • Endpoint: /me

  • Middleware: auth

    • This middleware ensures the request is authenticated before proceeding.

  • Controller: UserController.me

    • This method in the UserController handles the business logic for this route.

User me Controller

This method checks for the presence of an authenticated user in the request object. If the user is authenticated, it fetches the user data from the database, removes the password for security, and sends the user data in the response. If the user is not authenticated or if any error occurs, it sends the appropriate error response.

Controller Method

https://github.com/TheWebChimp/primate/blob/main/src/app.js

Controller Method

Breakdown

  1. Authorization Check: The function first checks if the req.user object and its necessary payload are present. If not, it responds with a 401 Unauthorized status and exits.

  2. Extract User Data: If the authorization check passes, it extracts the signed user data from req.user.payload.

  3. Fetch User from Database: It then attempts to find the user in the database using the UserService.findById method, passing the user's ID.

  4. User Existence Check: If no user is found, it responds with a 404 User not found status and exits.

  5. Remove Sensitive Information: If the user is found, it removes the password field from the user object to ensure sensitive information is not exposed.

  6. Respond with User Data: Finally, it responds with the user data and a success message.

  7. Error Handling: If any error occurs during the process, it catches the error and responds with a 400 User me error status, including the error message.

This function ensures that only authorized users can retrieve their information while protecting sensitive data and providing appropriate error handling.

Last updated