Protecting Backend Routes and Getting Current Login User

Jun 26, 2024

Protecting Backend Routes and Getting Current Login User

Introduction

In this video tutorial, we learn how to protect backend routes and get the current login user using an npm package. The steps involve installing the package, setting up options, and testing with Postman.

Steps to Follow

1. Install the npm Package

  • Open your browser and go to npm.
  • Search for the package protected-mid and select the first search result.
  • Copy the installation command and run it in your terminal.
npm install protected-mid

2. Import and Configure the Package

  • Open the documentation for the package for complete guidance.
  • Import the package in your code:
import protectedApp from 'protected-mid';
  • Create an options object:
const options = {
  secret: 'your-JWT-secret-key',
  tokenName: 'token',
  getUserId: userIdFunction, // Define how to get userID
  userModel: UserModel // Your user model
};
  • Details on each option:
    • secret: Your JWT secret key.
    • tokenName: The name you used when storing the JWT token in cookies.
    • getUserId: Function to retrieve the current logged-in user ID.
    • userModel: Your user model to get the current authenticated user.

3. Use the Middleware

  • Apply the middleware to your routes. Example for getUser route:
app.get('/user', protectedApp(options), (req, res) => {
  // route logic
});

4. Run the Server and Test with Postman

  • Start your server:
nodemon index.js
  • Open Postman, an API testing tool.
  • Test the getUser API route:
    • If logged in, you should get the current logged-in user.
    • If logged out (i.e., cookie deleted), you will get an unauthorized user message.

Conclusion

  • The middleware works correctly for protecting routes and identifying the current authenticated user.
  • Demonstrated successful testing and validation using Postman.

Testing Cases

  1. Logged In
    • Expected Result: Get current logged-in user.
  2. Logged Out
    • Expected Result: Unauthorized user message (no token provided).