Backend Authentication Implementation

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson

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 (B)</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 (D)</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. (B)</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. (C)</p> Signup and view all the answers

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

<p>201 (A)</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. (A)</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. (D)</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 (C)</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 (D)</p> Signup and view all the answers

What will the logoutUser function do when called?

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

What command is used to install the dotenv package?

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

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

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

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

<p>credentials (C)</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 (D)</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 (B)</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 (D)</p> Signup and view all the answers

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

<p>cors (D)</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 (C)</p> Signup and view all the answers

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

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

What is the purpose of the 'generateToken' function?

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

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

<p>1 hour (C)</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 (C)</p> Signup and view all the answers

What is the purpose of the 'clearToken' function?

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

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

<p>MONGODB_URI (B)</p> Signup and view all the answers

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

<p>dotenv (B)</p> Signup and view all the answers

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

<p>In production mode only (B)</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 (D)</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 (D)</p> Signup and view all the answers

Which middleware is responsible for securing HTTP response headers?

<p>helmet (D)</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 (A)</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. (C)</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 (D)</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. (C)</p> Signup and view all the answers

Which command is used to install the helmet package?

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

Flashcards are hidden until you start studying

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

More Like This

Use Quizgecko on...
Browser
Browser