メインコンテンツまでスキップ
バージョン: 🚧 Canary

🚀 Authentication Feature

Authentication features provide complete, pre-composed functionality for user authentication operations in Nodeblocks applications. These features combine schemas, routes, and handlers to create ready-to-use API endpoints for login, registration, email verification, and session management.


🎯 Overview

Authentication features are designed to:

  • Provide complete authentication workflows for user login and registration
  • Combine schemas with routes for validated authentication operations
  • Include security measures and token management automatically
  • Support email verification and account confirmation flows
  • Handle session management and logout operations seamlessly

📋 Feature Structure

Each authentication feature follows a consistent composition pattern:

  • Schema: Validates authentication input data and parameters
  • Route: Provides HTTP endpoint with authentication handlers
  • Composition: Combines schema and route using compose function

🔧 Available Authentication Features

loginWithCredentialsFeature

Provides complete login and logout functionality with credential validation.

Purpose: Handles user authentication with validated credentials and secure logout

Composition:

Usage:

import { features } from '@nodeblocks/backend-sdk';


// With database configuration
app.use('/api/auth', defService(partial(features.loginWithCredentialsFeature, [{ dataStores: db }])));

API Endpoints:

  • POST /api/auth/login - User authentication
  • POST /api/auth/logout - Session termination

verifyMfaCodeFeature

MFA code verification feature with schema validation and routing.

Purpose: Completes multi-factor authentication by verifying user-provided MFA code

Composition:

Usage:

import { features } from '@nodeblocks/backend-sdk';

// Direct usage:
app.use('/api', features.verifyMfaCodeFeature);

// With database configuration (handlers need dataStores):
app.use('/api', defService(partial(features.verifyMfaCodeFeature, [{ dataStores: db }])));

// Complete MFA flow example:
import express from 'express';
import { features, middlewares } from '@nodeblocks/backend-sdk';

const app = express()
.use(express.json())
.use('/api', features.loginWithCredentialsFeature) // Returns MFA token when enabled
.use('/api', features.verifyMfaCodeFeature) // Verifies code and returns auth tokens
.use(middlewares.nodeBlocksErrorMiddleware())
.listen(3000);

API Endpoint: POST /api/auth/mfa/verify

Request Body:

{
"token": "encrypted-mfa-challenge-token",
"code": "123456"
}

Response Body (Success):

{
"id": "identity-uuid",
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

Key Features:

  • Verifies MFA token validity and expiration
  • Compares user-provided code with stored code
  • Invalidates one-time MFA token after use
  • Returns standard authentication tokens on success
  • Completes MFA authentication workflow

Error Responses:

  • 400 Bad Request: Invalid MFA code provided
  • 401 Unauthorized: MFA token expired or invalid
  • 404 Not Found: MFA token not found in database
  • 500 Internal Server Error: Unexpected verification error

MFA Workflow Integration:

  1. User logs in with credentials (POST /auth/login)
  2. If MFA enabled, server sends code via email and returns MFA token
  3. User receives code in email
  4. User submits code with MFA token (POST /auth/mfa/verify)
  5. Server validates code and returns access/refresh tokens
  6. Client can now make authenticated requests

Notes:

  • Requires isMfaEnabled: true in authentication service configuration
  • MFA tokens are one-time use and automatically invalidated
  • Works with loginWithCredentialsFeature when MFA is enabled
  • Returns same token structure as standard login for consistency

resendMfaCodeFeature

MFA code resend feature with schema validation and routing for regenerating verification codes.

Purpose: Provides complete MFA code regeneration workflow for users who need a new verification code

Composition:

Usage:

import { features } from '@nodeblocks/backend-sdk';

// Direct usage:
app.use('/api', features.resendMfaCodeFeature);

// With database configuration (handlers need dataStores):
app.use('/api', defService(partial(features.resendMfaCodeFeature, [{ dataStores: db }])));

// Complete MFA flow with resend example:
import express from 'express';
import { features, middlewares } from '@nodeblocks/backend-sdk';

const app = express()
.use(express.json())
.use('/api', features.loginWithCredentialsFeature) // Returns MFA token when enabled
.use('/api', features.resendMfaCodeFeature) // Resends new MFA code
.use('/api', features.verifyMfaCodeFeature) // Verifies code and returns auth tokens
.use(middlewares.nodeBlocksErrorMiddleware())
.listen(3000);

API Endpoint: POST /api/auth/mfa/resend

Request Body:

{
"token": "encrypted-mfa-challenge-token"
}

Response Body (Success):

{
"token": "new-encrypted-mfa-challenge-token"
}

Key Features:

  • Invalidates previous MFA token for security
  • Generates completely new MFA code
  • Creates new MFA token with fresh expiration
  • Sends new code via email
  • Maintains token-based MFA workflow
  • Prevents token reuse and replay attacks

Error Responses:

  • 400 Bad Request: Invalid request body or token format
  • 401 Unauthorized: MFA token expired or invalid
  • 403 Forbidden: Token already used or wrong target
  • 404 Not Found: MFA token not found or identity not found
  • 500 Internal Server Error: Unexpected error during regeneration

MFA Resend Workflow:

  1. User logs in with credentials (POST /auth/login)
  2. If MFA enabled, server sends code via email and returns MFA token
  3. User doesn't receive email or code expires
  4. User requests new code (POST /auth/mfa/resend) with old token
  5. Server invalidates old token and generates new code
  6. Server sends new code via email and returns new token
  7. User receives new code in email
  8. User submits new code with new token (POST /auth/mfa/verify)
  9. Server validates and returns access/refresh tokens

Use Cases:

  • User didn't receive initial MFA code email
  • Email delivery delayed or failed
  • User accidentally deleted email
  • MFA code expired before user could enter it
  • User lost access to email temporarily and regained access

Notes:

  • Requires isMfaEnabled: true in authentication service configuration
  • Old MFA tokens are invalidated immediately upon resend
  • New MFA code is always different from old one for security
  • Token expiration timer resets with each resend
  • Works seamlessly with loginWithCredentialsFeature and verifyMfaCodeFeature
  • Email template and sender configurable via service options

loginWithOnetimeTokenFeature

One-time token login feature with schema validation and routing for passwordless authentication.

Purpose: Provides complete passwordless authentication workflow using one-time tokens (magic links)

Composition:

Usage:

import { features } from '@nodeblocks/backend-sdk';

// Direct usage:
app.use('/api', features.loginWithOnetimeTokenFeature);

// With database configuration (handlers need dataStores):
app.use('/api', defService(partial(features.loginWithOnetimeTokenFeature, [{ dataStores: db }])));

// Complete magic link flow example:
import express from 'express';
import { features, middlewares } from '@nodeblocks/backend-sdk';

const app = express()
.use(express.json())
.use('/api', features.loginWithOnetimeTokenFeature) // Passwordless login
.use(middlewares.nodeBlocksErrorMiddleware())
.listen(3000);

API Endpoint: POST /api/auth/ott/login

Request Body:

{
"token": "encrypted-onetime-authentication-token"
}

Response Body (Success):

{
"id": "identity-uuid",
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

Key Features:

  • Passwordless authentication via magic link
  • One-time token validation and invalidation
  • Secure token type and target verification
  • Identity lookup from token payload
  • Returns standard authentication tokens
  • Automatic token invalidation after use

Error Responses:

  • 403 Forbidden: Invalid token, wrong target, or already used
  • 404 Not Found: Identity not found
  • 500 Internal Server Error: Unexpected authentication error

Magic Link Workflow:

  1. User requests magic link (separate endpoint - not included in this feature)
  2. System generates one-time token with target: 'login' and identityId
  3. System sends magic link email with token
  4. User receives email and clicks magic link
  5. Client submits POST /auth/ott/login with token
  6. System validates token and retrieves identity
  7. System invalidates token (one-time use)
  8. System returns access and refresh tokens
  9. User is authenticated

Use Cases:

  • Magic link email authentication
  • Passwordless login flows
  • Secure temporary access
  • Email-based authentication
  • Mobile-friendly authentication

Notes:

  • Tokens must have type: 'onetime' and target: 'login'
  • Tokens are one-time use and automatically invalidated after login
  • Returns same token structure as standard credential login for consistency
  • Requires separate endpoint/logic to generate and send magic link emails

registerCredentialsFeature

Handles user registration with credential validation and account creation.

Purpose: Processes new user registration with data validation

Composition:

Usage:

import { features } from '@nodeblocks/backend-sdk';


// With database configuration
app.use('/api/auth', defService(partial(features.registerCredentialsFeature, [{ dataStores: db }])));

API Endpoint: POST /api/auth/register


emailVerificationFeature

Sends verification emails to users for account confirmation.

Purpose: Handles email verification request processing

Composition:

Usage:

import { features } from '@nodeblocks/backend-sdk';


// With database configuration
app.use('/api', defService(partial(features.emailVerificationFeature, [{ dataStores: db }])));

API Endpoint: POST /api/auth/:identityId/send-verification-email


confirmEmailFeature

Processes email confirmation tokens to verify user accounts.

Purpose: Validates email verification tokens and confirms user accounts

Composition:

Usage:

import { features } from '@nodeblocks/backend-sdk';


// With database configuration
app.use('/api', defService(partial(features.confirmEmailFeature, [{ dataStores: db }])));

API Endpoint: POST /api/auth/confirm-email


changeEmailFeature

Email change feature with schema validation and routing for updating user email addresses.

Purpose: Handles email change initiation with validation

Composition:

  • Schema: changeEmailSchema - validates identityId and new email (plus internal password verification in handlers)
  • Route: changeEmailRoute - PATCH /auth/:identityId/change-email with email update processing

Usage:

import { features } from '@nodeblocks/backend-sdk';


// With database configuration
app.use('/api', defService(partial(features.changeEmailFeature, [{ dataStores: db }])));

API Endpoint: PATCH /api/auth/:identityId/change-email


checkTokenFeature

Token validation feature with schema validation and routing for authentication checks.

Purpose: Handles token validation with target context

Composition:

Usage:

import { features } from '@nodeblocks/backend-sdk';


// With database configuration
app.use('/api', defService(partial(features.checkTokenFeature, [{ dataStores: db }])));

API Endpoint: POST /api/auth/token/check


confirmNewEmailFeature

Email confirmation feature with schema validation for new email address verification.

Purpose: Handles new email confirmation after email change

Composition:

Usage:

import { features } from '@nodeblocks/backend-sdk';


// With database configuration
app.use('/api', defService(partial(features.confirmNewEmailFeature, [{ dataStores: db }])));

API Endpoint: POST /api/auth/confirm-new-email


sendResetPasswordLinkEmailFeature

Password reset email feature with schema validation and routing for password recovery.

Purpose: Handles password reset email generation and sending

Composition:

Usage:

import { features } from '@nodeblocks/backend-sdk';


// With database configuration
app.use('/api', defService(partial(features.sendResetPasswordLinkEmailFeature, [{ dataStores: db }])));

API Endpoint: POST /api/auth/send-reset-password-link-email


changePasswordFeature

Change password feature with schema validation and routing for updating user passwords.

Purpose: Handles password change with current password verification and new password hashing

Composition:

Usage:

import { features } from '@nodeblocks/backend-sdk';


// With database configuration
app.use('/api', defService(partial(features.changePasswordFeature, [{ dataStores: db }])));

API Endpoint: PATCH /api/auth/:identityId/change-password


activateFeature

Account activation feature with schema validation and routing for activating user accounts.

Purpose: Handles account activation with email verification and identity status update

Composition:

  • Schema: activateSchema - validates identity activation request (requires identityId)
  • Route: activateRoute - POST /auth/activate with account activation processing

Usage:

import { features } from '@nodeblocks/backend-sdk';


// With database configuration
app.use('/api', defService(partial(features.activateFeature, [{ dataStores: db }])));

API Endpoint: POST /api/auth/activate


deactivateFeature

Deactivate account feature with schema validation and routing for deactivating user accounts.

Purpose: Handles account deactivation with identity status update and token invalidation

Composition:

Usage:

import { features } from '@nodeblocks/backend-sdk';


// With database configuration
app.use('/api', defService(partial(features.deactivateFeature, [{ dataStores: db }])));

API Endpoint: POST /api/auth/deactivate


completePasswordResetFeature

Complete password reset feature with schema validation and routing for resetting user passwords.

Purpose: Handles password reset completion with token validation and password update

Composition:

Usage:

import { features } from '@nodeblocks/backend-sdk';


// With database configuration
app.use('/api', defService(partial(features.completePasswordResetFeature, [{ dataStores: db }])));

API Endpoint: POST /api/auth/reset-password


refreshTokenFeature

Token refresh feature with schema validation and routing for renewing access tokens.

Purpose: Handles token refresh with token rotation and security measures

Feature Composition:

Usage:

import { features } from '@nodeblocks/backend-sdk';

// With database (handlers need dataStores):
app.use('/api', defService(partial(features.refreshTokenFeature, [{ dataStores: db }])));

API Endpoint: POST /api/auth/token/refresh


deleteRefreshTokensFeature

Refresh token deletion feature with schema validation and routing for removing identity refresh tokens.

Purpose: Handles secure deletion of refresh tokens for specific identities

Feature Composition:

Usage:

import { features } from '@nodeblocks/backend-sdk';

// With database (handlers need dataStores):
app.use('/api', defService(partial(features.deleteRefreshTokensFeature, [{ dataStores: db }])));

API Endpoint: DELETE /api/auth/:identityId/refresh-tokens