Search⌘ K
AI Features

Solution: Authenticate Users with Configurable Login and Tokens

Explore how to apply the Strategy Pattern to build a flexible authentication system in Node.js. Learn to implement multiple login methods like password, OTP, and Google along with different token generation strategies. Understand how to compose these strategies in a controller to handle authentication and token issuance seamlessly without conditional logic.

Solution explanation

  • Lines 2–27: Define three authentication strategies: PasswordAuthOtpAuth, and GoogleAuth.

    • Each has an async .authenticate() that simulates real checks with setTimeout().

    • PasswordAuth checks a simple password string.

    • OtpAuth verifies a fixed OTP code.

    • GoogleAuth validates a token prefix.

    • All follow a shared interface, so the context can delegate uniformly.

  • Lines 30–54: The AuthService and TokenService are independent contexts.

    • Each stores its active strategy and delegates calls to it.

    • Both can switch strategies at runtime using .setStrategy().

    • There are no conditionals—the behavior is entirely determined by which strategy is active.

  • Lines 57–81: The token strategies—SessionToken ...