Backend Authentication Implementation
37 Questions
0 Views

Backend Authentication Implementation

Created by
@BonnyClearQuartz

Questions and Answers

What purpose does the registerUser function serve in the authController.ts file?

  • Exports user data
  • Logs out the user
  • Authenticates existing users
  • Handles user registration (correct)
  • Which of the following is a task performed by authRouter.ts?

  • Connecting to the MongoDB database
  • Defining routes for user authentication (correct)
  • Managing JWT token generation
  • Hashing user passwords
  • What libraries are installed to enable JWT token management and password hashing?

  • express and bcryptjs
  • mongoose and express
  • bcryptjs and jsonwebtoken (correct)
  • jsonwebtoken and mongoose
  • What is the role of mongoose in the structure described?

    <p>Facilitating the MongoDB interaction in NodeJS</p> Signup and view all the answers

    In the index.ts file, what is the purpose of the app.use(authRouter) line?

    <p>Registering middleware for HTTP request handling</p> Signup and view all the answers

    What is the purpose of the comparePassword method in the IUser interface?

    <p>To compare an entered password with the stored password.</p> Signup and view all the answers

    What happens when the userSchema.pre('save') middleware is triggered?

    <p>The password is hashed if it is modified.</p> Signup and view all the answers

    Which response status is returned when a user is successfully registered?

    <p>201</p> Signup and view all the answers

    What should be done if a user with the same email already exists in the database during registration?

    <p>Return an error message indicating the user already exists.</p> Signup and view all the answers

    What response is generated if the user is not found or if the password is incorrect during authentication?

    <p>401 Unauthorized - User not found or password incorrect.</p> Signup and view all the answers

    What utility function is called to generate a JWT token after a user successfully logs in?

    <p>generateToken</p> Signup and view all the answers

    Which of the following is NOT a field required in the userSchema for creating a new user?

    <p>age</p> Signup and view all the answers

    What will the logoutUser function do when called?

    <p>Clear the JWT token from the response.</p> Signup and view all the answers

    What command is used to install the dotenv package?

    <p>npm install dotenv</p> Signup and view all the answers

    What does the line 'app.use(bodyParser.json())' accomplish?

    <p>Enables JSON request parsing</p> Signup and view all the answers

    Which value must be set to 'true' in the CORS configuration to allow credentials?

    <p>credentials</p> Signup and view all the answers

    What is a likely consequence of not configuring CORS when using different port numbers?

    <p>Requests may fail with a CORS error</p> Signup and view all the answers

    What is the purpose of the JWT token in the described application setup?

    <p>To validate API access for authenticated users</p> Signup and view all the answers

    What does the line 'dotenv.config();' do in the application?

    <p>It loads environment variables from a .env file</p> Signup and view all the answers

    Which package must be installed to enable CORS in the application?

    <p>cors</p> Signup and view all the answers

    What would likely happen if a user calls an API without a valid token?

    <p>An error response will be returned</p> Signup and view all the answers

    What should be done with the cookie when a user logs out?

    <p>Clear the cookie</p> Signup and view all the answers

    What is the purpose of the 'generateToken' function?

    <p>To create a JWT with user identification</p> Signup and view all the answers

    What is the default expiration time set for the JWT in the 'generateToken' function?

    <p>1 hour</p> Signup and view all the answers

    Which of the following is required to connect to the MongoDB database?

    <p>A URL provided after database creation</p> Signup and view all the answers

    What is the purpose of the 'clearToken' function?

    <p>To remove the JWT cookie from the client</p> Signup and view all the answers

    What environment variable is used to connect to the MongoDB database?

    <p>MONGODB_URI</p> Signup and view all the answers

    What library is used for managing environment variables in this context?

    <p>dotenv</p> Signup and view all the answers

    When should the JWT cookie be set as 'secure'?

    <p>In production mode only</p> Signup and view all the answers

    What is the purpose of the authenticate middleware in the route definition?

    <p>To validate the user session before accessing user routes</p> Signup and view all the answers

    What potential risk is associated with retrieving user data based on the ID sent in the URL?

    <p>It may lead to unauthorized data exposure if the ID belongs to another user</p> Signup and view all the answers

    Which middleware is responsible for securing HTTP response headers?

    <p>helmet</p> Signup and view all the answers

    What data format does the bodyParser middleware recognize for incoming requests?

    <p>JSON objects and URL-encoded strings</p> Signup and view all the answers

    Which of the following correctly describes the use of dotenv in this application?

    <p>It allows environment variables to be loaded from a .env file.</p> Signup and view all the answers

    What does the express Router allow you to do in this application?

    <p>To modularize the routes for better organization</p> Signup and view all the answers

    What is the significance of declaring the UserBasicInfo interface in this application?

    <p>It defines the structure of user data used in requests.</p> Signup and view all the answers

    Which command is used to install the helmet package?

    <p>npm install helmet</p> Signup and view all the answers

    Study Notes

    Backend Authentication Implementation

    • The backend folder structure includes controllers, routes, models, utils, and connections for better organization.

    authController.ts

    • Functions for user registration, authentication, and logout are defined but incomplete.
    • Exports three main functions: registerUser, authenticateUser, and logoutUser.

    authRouter.ts

    • Uses Express Router to handle specific routes.
    • Includes POST routes for registration, login, and logout.
    • Controllers are imported from authController.ts.

    index.ts

    • Sets up the Express application to listen on a specified port (defaults to 3000).
    • Imports and uses authRouter to handle authentication-related endpoints.
    • Initializes database connection with connectUserDB.

    Dependency Installation

    • Installs jsonwebtoken for handling JWT tokens and bcryptjs for password hashing.
    • Installs type definitions for the above libraries via @types/bcryptjs and @types/jsonwebtoken.
    • Uses mongoose for MongoDB operations.

    User Model (User.ts)

    • Defines IUser interface with properties: name, email, password, and a method to compare passwords.
    • Implements a userSchema that includes validation and password hashing before saving to the database.

    Auth Functions Implementation

    • registerUser checks for existing users, creates a new user, and generates a JWT token on successful registration.
    • authenticateUser verifies user credentials and generates a JWT if valid.
    • logoutUser clears the JWT cookie from the client.

    JWT Token Management (auth.ts)

    • Functions: generateToken for creating JWT tokens and setting security cookies, and clearToken for clearing cookies upon logout.
    • Tokens expire in one hour.

    MongoDB Connection (userDB.ts)

    • Connects to MongoDB and logs the connection status or errors encountered during the connection process.

    Environment Variables

    • .env file includes:
      • PORT for server port
      • JWT_SECRET for signing JWT
      • NODE_ENV for environment type
      • MONGODB_URI for MongoDB connection string.
    • Uses dotenv to load environment variables into the application.

    Middleware Integration

    • Installs body-parser for parsing incoming JSON requests.
    • Installs cors to manage cross-origin requests and sets up middleware for allowed origins.
    • Adds helmet for enhancing API security through setting response headers.

    Custom Middleware for Authentication

    • Middleware checks token validity before allowing access to certain user-specific routes.
    • Exposes user routes under /users, ensuring only authenticated requests proceed.

    Security Enhancements

    • Additional security packages like helmet are employed to enhance response security headers.
    • Properly handles user data by requiring token verification prior to accessing user profiles.

    Application Testing

    • Use tools like Postman to test API functionalities.
    • Troubleshoot CORS issues that may arise due to domain mismatches during frontend and backend interactions.

    Studying That Suits You

    Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

    Quiz Team

    Description

    This quiz covers the implementation of backend authentication using Node.js and Express. It focuses on the structure of the backend, including controllers and routes, as well as the functions for user registration and authentication procedures. Test your knowledge on using libraries like jsonwebtoken and bcryptjs for securing applications.

    More Quizzes Like This

    Use Quizgecko on...
    Browser
    Browser