🔐 Authentication Service
The Authentication Service provides a complete authentication system for identity registration, login, logout, and token management with JWT-based security and cookie support.
🚀 Quickstart
import express from 'express';
import { MongoClient } from 'mongodb';
import {
services,
middlewares,
types
} from '@nodeblocks/backend-sdk';
const client = new MongoClient('mongodb://localhost:27017').db('dev');
express()
.use(
services.authService(
{
identity: client.collection('identity'),
onetimetoken: client.collection('onetimetoken'),
invitations: client.collection('invitations'),
},
{
authSecrets: {
authEncSecret: 'your-encryption-secret',
authSignSecret: 'your-signing-secret',
},
maxFailedLoginAttempts: 5,
accessTokenExpireTime: '2h',
refreshTokenExpireTime: '2d',
verifyEmailConfig: {
enabled: true,
sender: 'noreply@example.com',
mailService: {
sendMail: async (mailData: types.MailData) => {
console.log(mailData);
return true;
},
},
emailConfig: {
bodyTemplate: 'Hello {{email}}',
subject: 'Welcome to our app',
urlTemplate: 'https://example.com/verify-email?token={{token}}',
},
},
invitation: {
enabled: true,
emailConfig: {
bodyTemplate: '<h1>You\'re invited!</h1><p>Click <a href="${url}">here</a> to accept the invitation.</p>',
subject: 'You\'re invited to join our organization',
urlTemplate: 'https://yourapp.com/invitations/accept?token=${token}&email=${email}',
sender: 'invites@yourapp.com'
},
target: 'invitation'
}
},
{
sendMail: async (mailData: types.MailData) => {
console.log(mailData);
return true;
},
}
)
)
.use(middlewares.nodeBlocksErrorMiddleware())
.listen(8089, () => console.log('Server running'));
📋 Endpoint Summary
Method | Path | Description |
---|---|---|
Authentication Endpoints | ||
POST | /auth/register | Register a new identity account |
POST | /auth/login | Authenticate identity and receive tokens |
POST | /auth/logout | Logout and invalidate tokens |
Email Verification Endpoints | ||
POST | /auth/:identityId/send-verification-email | Send email verification to identity |
POST | /auth/confirm-email | Confirm email with verification token |
Invitation Endpoints | ||
POST | /invitations | Create a new invitation |
GET | /invitations | List invitations with optional filtering |
GET | /invitations/:invitationId | Get invitation by ID |
DELETE | /invitations/:invitationId | Delete invitation |
🗄️ Entity Schema
The authentication service manages user identities with the following schema:
Identity Entity
{
"id": "string",
"email": "string",
"password": "string",
"attempts": "number",
"locked": "boolean",
"createdAt": "string",
"updatedAt": "string",
"typeId": "string"
}
Field Details
Field | Type | Auto-Generated | Required | Description |
---|---|---|---|---|
id | string | ✅ | ✅ | Unique identifier (UUID) |
email | string | ❌ | ✅ | Identity's email address |
password | string | ❌ | ✅ | Hashed password |
attempts | number | ✅ | ✅ | Failed login attempts counter |
locked | boolean | ✅ | ✅ | Account lock status |
createdAt | string | ✅ | ✅ | Creation timestamp |
updatedAt | string | ✅ | ✅ | Last update timestamp |
typeId | string | ❌ | ❌ | Identity role identifier (e.g., "100" for admin, "001" for user) |
Additional Field Details:
-
attempts: Tracks the number of consecutive failed login attempts for security purposes. After a certain threshold (configurable), the account will be automatically locked.
-
locked: Indicates whether the account is currently locked due to too many failed login attempts or administrative action. A locked account cannot be used for authentication until unlocked.
-
typeId: A string identifier that determines the identity's role and permissions in the system. Adjustable for each service. Common values might include:
- "100": Administrator with full system access
- "001": Standard user with basic permissions
- "000": Guest user with lowest permissions
- Additional custom roles can be defined as needed
Invitation Entity
The authentication service also manages invitations with the following schema:
{
"id": "string",
"email": "string",
"fromUserId": "string",
"orgId": "string",
"role": "string",
"status": "string",
"createdAt": "string",
"updatedAt": "string"
}
Invitation Field Details
Field | Type | Auto-Generated | Required | Description |
---|---|---|---|---|
id | string | ✅ | ✅ | Unique identifier (UUID) |
email | string | ❌ | ✅ | Email address of the invitee |
fromUserId | string | ❌ | ✅ | ID of the identity sending the invitation |
orgId | string | ❌ | ❌ | ID of the organization to invite to |
role | string | ❌ | ❌ | Role for the invitee in the organization |
status | string | ❌ | ✅ | Invitation status (e.g., "pending", "accepted") |
createdAt | string | ✅ | ✅ | Creation timestamp |
updatedAt | string | ✅ | ✅ | Last update timestamp |
🔐 Authentication Headers
For protected endpoints, include the following headers:
Authorization: Bearer <access_token>
x-nb-fingerprint: <device_fingerprint>
⚠️ Important: The
x-nb-fingerprint
header is required for all authenticated requests if fingerprint was specified during authorization. Without it, requests will return 401 Unauthorized.
🔧 API Endpoints
1. Register Identity
Register a new identity account with email and password.
Request:
- Method:
POST
- Path:
/auth/register
- Headers:
Content-Type: application/json
- Authorization: None required
Request Body:
Field | Type | Required | Description |
---|---|---|---|
email | string | ✅* | Identity's email address |
password | string | ✅ | Identity's password |
token | string | ✅* | Invitation token |
*Either email
OR token
is required, but not both.
Response Body:
Field | Type | Description |
---|---|---|
No response body | - | Registration endpoint returns no response body on success |
Validation:
- Schema Validation: Enforced automatically (email and password or token and password required)
- Route Validators: None
Example Request:
curl -X POST {{host}}/auth/register \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"password": "securepassword123"
}'
Example Request with Token (for existing users):
curl -X POST {{host}}/auth/register \
-H "Content-Type: application/json" \
-d '{
"token": "invitation-token",
"password": "securepassword123"
}'
Success Response:
HTTP/1.1 201 Created
Content-Type: application/json
Error Responses:
When email already exists:
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json
{
"error": {
"message": "unable to register \"user@example.com\""
}
}
When request body is missing required fields:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "Validation Error",
"data": [
"request body must have required property 'email'",
"request body must have required property 'token'",
"request body must match exactly one schema in oneOf"
]
}
}
2. Login Identity
Authenticate credentials and receive access and refresh tokens.
Request:
- Method:
POST
- Path:
/auth/login
- Headers:
Content-Type: application/json
- Authorization: None required
Request Body:
Field | Type | Required | Description |
---|---|---|---|
email | string | ✅ | Identity's email address |
password | string | ✅ | Identity's password |
fingerprint | string | ❌ | Device fingerprint for security |
Response Body:
Field | Type | Description |
---|---|---|
accessToken | string | JWT access token for API authentication |
id | string | Identity's unique identifier |
refreshToken | string | JWT refresh token for obtaining new access tokens |
Validation:
- Schema Validation: Enforced automatically (email, password required)
- Route Validators: None
Example Request:
curl -X POST {{host}}/auth/login \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com",
"password": "securepassword123",
"fingerprint": "device-fingerprint"
}'
Success Response:
HTTP/1.1 200 OK
Content-Type: application/json
Access-Control-Allow-Credentials: true
Set-Cookie: accessToken=...; Path=/
Set-Cookie: refreshToken=...; Path=/
{
"accessToken": "c911c0dd107f8d7e92c0608aa149d041:dee2...",
"id": "0b3839a6-92b4-4044-a13b-ed834a105646",
"refreshToken": "9f0cad0da1ceec15c01de729a2359236:2acc8ee1b57fd971473..."
}
Error Responses:
When credentials are invalid:
HTTP/1.1 401 Unauthorized
Content-Type: application/json
{
"error": {
"message": "wrong credentials provided"
}
}
3. Logout Identity
Logout identity and invalidate refresh tokens.
Request:
- Method:
POST
- Path:
/auth/logout
- Headers:
Authorization: Bearer <token>
x-nb-fingerprint: <device-fingerprint>
- Authorization: Bearer token required
Request Body: No body required. Uses access token from Authorization header.
Response Body:
Field | Type | Description |
---|---|---|
No response body | - | Logout endpoint returns no response body on success |
Validation:
- Schema Validation: None
- Route Validators:
verifyAuthentication(getBearerTokenInfo)
- Validates bearer token authentication
Example Request:
curl -X POST {{host}}/auth/logout \
-H "Authorization: Bearer <access-token>"
Success Response:
HTTP/1.1 204 No Content
Content-Type: application/json
Error Responses:
When refresh token invalidation operation fails:
HTTP/1.1 500 Internal Server Error
Content-Type: application/json
{
"error": {
"message": "failed to delete refresh token"
}
}
4. Send Verification Email
Send an email verification link to a identity's email address.
Request:
- Method:
POST
- Path:
/auth/:identityId/send-verification-email
- Headers:
Authorization: Bearer <token>
x-nb-fingerprint: <device-fingerprint>
- Authorization: Bearer token required (admin or self access)
Path Parameters:
Field | Type | Required | Description |
---|---|---|---|
identityId | string | ✅ | Identity's unique identifier |
Request Body:
Field | Type | Required | Description |
---|---|---|---|
fingerprint | string | ❌ | Device fingerprint for security |
Response Body:
Field | Type | Description |
---|---|---|
No response body | - | Send verification email endpoint returns no response body on success |
Validation:
- Schema Validation: Enforced automatically
- Route Validators:
verifyAuthentication(getBearerTokenInfo)
- Validates bearer token authenticationvalidateResourceAccess(['admin', 'self'], getBearerTokenInfo)
- Ensures identity has admin role or is self
Example Request:
curl -X POST {{host}}/auth/identity-12345/send-verification-email \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <access-token>" \
-d '{
"fingerprint": "device-fingerprint"
}'
Success Response:
HTTP/1.1 204 No Content
Content-Type: application/json
Error Responses:
When email verification is not enabled:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "verification email feature not enabled"
}
}
When mail service is missing:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "verification email feature requires a mail service to be provided"
}
}
When email configuration is missing:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "verifyEmailConfig requires emailConfig with fields bodyTemplate, subject, urlTemplate"
}
}
When email sending fails:
HTTP/1.1 500 Internal Server Error
Content-Type: application/json
{
"error": {
"message": "Failed to send verification email"
}
}
5. Confirm Email
Confirm a identity's email address using a verification token.
Request:
- Method:
POST
- Path:
/auth/confirm-email
- Headers:
Content-Type: application/json
- Authorization: None required
Request Body:
Field | Type | Required | Description |
---|---|---|---|
token | string | ✅ | Verification token from email |
Response Body:
Field | Type | Description |
---|---|---|
No response body | - | Confirm email endpoint returns no response body on success |
Validation:
- Schema Validation: Enforced automatically (token required)
- Route Validators: None
Example Request:
curl -X POST {{host}}/auth/confirm-email \
-H "Content-Type: application/json" \
-d '{
"token": "jwt-verification-token"
}'
Success Response:
HTTP/1.1 204 No Content
Content-Type: application/json
Error Responses:
When token is invalid:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "Unable to verify token"
}
}
6. Create Invitation
Create a new invitation for an entity to join a service.
Request:
- Method:
POST
- Path:
/invitations
- Headers:
Content-Type: application/json
Authorization: Bearer <token>
x-nb-fingerprint: <device-fingerprint>
- Authorization: Bearer token required (admin access)
Request Body:
Field | Type | Required | Description |
---|---|---|---|
email | string | ✅ | Email address of the invitee |
fromUserId | string | ✅ | ID of the identity sending the invitation |
orgId | string | ❌ | ID of the organization to invite to |
role | string | ❌ | Role for the invitee in the organization |
Response Body:
Field | Type | Description |
---|---|---|
invitationId | string | Unique identifier of the created invitation |
Validation:
- Schema Validation: Enforced automatically (email, fromUserId required)
- Route Validators:
verifyAuthentication(getBearerTokenInfo)
- Validates bearer token authenticationvalidateResourceAccess(['admin'], getBearerTokenInfo)
- Ensures identity has admin role
Example Request:
curl -X POST {{host}}/invitations \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <access-token>" \
-d '{
"email": "newuser@example.com",
"fromUserId": "392157b1-dc7a-4935-a6f9-a2d333b910ea",
"orgId": "org123",
"role": "member"
}'
Success Response:
HTTP/1.1 201 Created
Content-Type: application/json
{
"invitationId": "62564a60-e720-4907-bb85-3afaa2729e0d"
}
Error Responses:
When request body is missing required fields:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "Validation Error",
"data": [
"request body must have required property 'email'"
]
}
}
When request body is missing fromUserId:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "Validation Error",
"data": [
"request body must have required property 'fromUserId'"
]
}
}
When email format is invalid:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "Validation Error",
"data": [
"request body must match format \"email\""
]
}
}
When request contains extra properties:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "Validation Error",
"data": [
"request body must NOT have additional properties"
]
}
}
When invitation creation fails:
HTTP/1.1 500 Internal Server Error
Content-Type: application/json
{
"error": {
"message": "Failed to create invitation"
}
}
7. List Invitations
Retrieve all invitations with optional filtering and pagination.
Request:
- Method:
GET
- Path:
/invitations
- Headers:
Authorization: Bearer <token>
x-nb-fingerprint: <device-fingerprint>
- Authorization: Bearer token required (admin access)
Query Parameters:
Field | Type | Required | Description |
---|---|---|---|
email | string | ❌ | Filter by invitee email address |
fromUserId | string | ❌ | Filter by inviter identity ID |
orgId | string | ❌ | Filter by organization ID |
role | string | ❌ | Filter by role |
page | number | ❌ | Page number for pagination |
limit | number | ❌ | Number of items per page |
Response Body:
Field | Type | Description |
---|---|---|
email | string | Email address of the invitee |
fromUserId | string | ID of the identity sending the invitation |
orgId | string | ID of the organization to invite to |
role | string | Role for the invitee in the organization |
status | string | Invitation status (e.g., "pending", "accepted") |
createdAt | string | Creation timestamp |
id | string | Unique invitation identifier |
updatedAt | string | Last update timestamp |
Validation:
- Schema Validation: Enforced automatically
- Route Validators:
verifyAuthentication(getBearerTokenInfo)
- Validates bearer token authenticationvalidateResourceAccess(['admin'], getBearerTokenInfo)
- Ensures identity has admin role
Example Request:
curl -X GET "{{host}}/invitations" \
-H "Authorization: Bearer <access-token>"
Success Response:
HTTP/1.1 200 OK
Content-Type: application/json
[
{
"email": "newuser@example.com",
"fromUserId": "392157b1-dc7a-4935-a6f9-a2d333b910ea",
"orgId": "org123",
"role": "member",
"status": "pending",
"createdAt": "2025-07-04T06:29:32.905Z",
"id": "62564a60-e720-4907-bb85-3afaa2729e0d",
"updatedAt": "2025-07-04T06:29:32.905Z"
}
]
Empty Response:
HTTP/1.1 200 OK
Content-Type: application/json
[]
8. Get Invitation by ID
Retrieve a specific invitation by its unique identifier.
Request:
- Method:
GET
- Path:
/invitations/:invitationId
- Headers:
Authorization: Bearer <token>
x-nb-fingerprint: <device-fingerprint>
- Authorization: Bearer token required (admin access)
Path Parameters:
Field | Type | Required | Description |
---|---|---|---|
invitationId | string | ✅ | Unique invitation identifier |
Validation:
- Schema Validation: Enforced automatically
- Route Validators:
verifyAuthentication(getBearerTokenInfo)
- Validates bearer token authenticationvalidateResourceAccess(['admin'], getBearerTokenInfo)
- Ensures identity has admin role
Example Request:
curl -X GET {{host}}/invitations/62564a60-e720-4907-bb85-3afaa2729e0d \
-H "Authorization: Bearer <access-token>"
Success Response:
HTTP/1.1 200 OK
Content-Type: application/json
{
"email": "newuser@example.com",
"fromUserId": "392157b1-dc7a-4935-a6f9-a2d333b910ea",
"orgId": "org123",
"role": "member",
"status": "pending",
"createdAt": "2025-07-04T06:29:32.905Z",
"id": "62564a60-e720-4907-bb85-3afaa2729e0d",
"updatedAt": "2025-07-04T06:29:32.905Z"
}
Error Responses:
When invitation is not found:
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": {
"message": "Invitation not found"
}
}
9. Delete Invitation
Delete a specific invitation by its unique identifier.
Request:
- Method:
DELETE
- Path:
/invitations/:invitationId
- Headers:
Authorization: Bearer <token>
x-nb-fingerprint: <device-fingerprint>
- Authorization: Bearer token required (admin access)
Path Parameters:
Field | Type | Required | Description |
---|---|---|---|
invitationId | string | ✅ | Unique invitation identifier |
Validation:
- Schema Validation: Enforced automatically
- Route Validators:
verifyAuthentication(getBearerTokenInfo)
- Validates bearer token authenticationvalidateResourceAccess(['admin'], getBearerTokenInfo)
- Ensures identity has admin role
Example Request:
curl -X DELETE {{host}}/invitations/62564a60-e720-4907-bb85-3afaa2729e0d \
-H "Authorization: Bearer <access-token>"
Success Response:
HTTP/1.1 204 OK
Content-Type: application/json
Error Responses:
When invitation is not found:
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": {
"message": "Invitation not found"
}
}
🔒 Security Features
Account Protection
- Failed Login Attempts: Tracks failed login attempts
- Account Locking: Automatically locks accounts after 5 failed attempts (configurable)
- Password Hashing: Passwords are securely hashed
- Token Security: JWT tokens include device fingerprinting and IP validation
Token Management
- Access Tokens: Short-lived tokens for API access
- Refresh Tokens: Long-lived tokens for token renewal
- Token Verification: Validates domain, fingerprint, IP, and user agent
- Secure Cookies: HTTP-only, secure cookies for token storage
Authentication Methods
Bearer Token Authentication
// Use in Authorization header
Authorization: Bearer <access-token>
Cookie Authentication
// Tokens automatically sent with requests
⚙️ Configuration Options
Service Configuration
interface AuthServiceConfig {
authSecrets?: {
authEncSecret: string; // JWT encryption secret
authSignSecret: string; // JWT signing secret
};
maxFailedLoginAttempts?: number; // Default: 5
cookieOpts?: {
domain?: string;
maxAge?: number;
path?: string;
sameSite?: 'strict' | 'lax' | 'none';
};
jwtOpts?: {
jwtSignOptions?: SignOptions;
stateful?: boolean;
};
accessTokenExpireTime?: string; // Default: '2h'
onetimeTokenExpireTime?: string; // Default: '2h'
refreshTokenExpireTime?: string; // Default: '2d'
verifyEmailConfig?: {
enabled: boolean; // Enable email verification feature
emailConfig?: {
bodyTemplate: string; // Email body template with {{email}} and {{token}} placeholders
subject: string; // Email subject line
urlTemplate: string; // URL template with {{token}} placeholder
};
mailService?: MailService; // Mail service implementation
sender: string; // Sender email address
};
invitation?: {
enabled: boolean; // Enable invitation feature
emailConfig?: {
bodyTemplate: string; // Email body template with {{email}} and {{token}} placeholders
subject: string; // Email subject line
urlTemplate: string; // URL template with {{token}} placeholder
sender: string; // Sender email address
};
target: string; // Token target for invitation validation
};
}
Configuration Details
The authentication service configuration is organized into logical groups for security, cookies, JWT settings, invitations and email verificartion
🔐 Security Settings
authSecrets
- JWT token security secrets
- Type:
{ authEncSecret: string; authSignSecret: string }
- Description: Secret keys for JWT encryption and signing
- Default:
{ authEncSecret: '', authSignSecret: '' }
- Required: Yes (for production)
- Child Properties:
authEncSecret
: Secret key for JWT payload encryptionauthSignSecret
: Secret key for JWT signature verification
maxFailedLoginAttempts
- Account lockout threshold
- Type:
number
- Description: Maximum failed login attempts before account lockout
- Default:
5
- Behavior: Locks account after threshold is exceeded, requires manual unlock
🍪 Cookie Settings
cookieOpts
- HTTP cookie configuration
- Type:
{ domain?: string; maxAge?: string | number; path?: string; sameSite?: 'strict' | 'lax' | 'none' }
- Description: Controls how authentication tokens are stored in browser cookies
- Default:
undefined
(uses token expiration) - Child Properties:
domain
: Cookie domain scope- Type:
string
- Description: Controls cookie scope across subdomains
- Example:
'.example.com'
for all subdomains
- Type:
maxAge
: Cookie expiration time- Type:
string | number
- Description: Sets cookie expiration time in ms
- Type:
path
: Cookie path scope- Type:
string
- Description: Restricts cookie to specific URL paths
- Default:
'/'
(entire domain) - Example:
'/api'
for API-only cookies
- Type:
sameSite
: CSRF protection level- Type:
'strict' | 'lax' | 'none'
- Description: Controls when cookies are sent in cross-site requests
- Values:
'strict'
: Cookies only sent in same-site requests (most secure)'lax'
: Cookies sent in cross-site navigation (balanced)'none'
: Cookies sent in all cross-site requests (requiressecure: true
)
- Type:
🔑 JWT Settings
jwtOpts
- JWT token generation and validation options
- Type:
{ jwtSignOptions?: SignOptions; stateful?: boolean }
- Description: Customize JWT signing and validation behavior
- Default:
undefined
(uses standard JWT settings) - Child Properties:
jwtSignOptions
: JWT signing configuration- Type:
SignOptions
(from jsonwebtoken package) - Description: Customize JWT signing algorithm and parameters
- Default: Standard JWT signing
- Type:
stateful
: Server-side token validation (this property requires confirmation)- Type:
boolean
- Description: Enable server-side token validation for enhanced security
- Default:
false
(stateless) - Use Case: Token revocation and enhanced security
- Type:
⏰ Token Expiration Times
accessTokenExpireTime
- Access token lifetime
- Type:
string
(ms package format) - Description: Short-lived token for API access
- Default:
undefined
- Format: ms package format (
'30m'
,'1h'
,'2h'
) - Security: Minimizes exposure window
refreshTokenExpireTime
- Refresh token lifetime
- Type:
string
(ms package format) - Description: Long-lived token for obtaining new access tokens
- Default:
undefined
- Format: ms package format (
'1d'
,'7d'
,'30d'
) - Security: Stored in secure HTTP-only cookies
onetimeTokenExpireTime
- One-time token lifetime
- Type:
string
(ms package format) - Description: Temporary token for password reset, email verification
- Default:
undefined
- Format: ms package format (
'15m'
,'1h'
,'2h'
) - Security: Single-use tokens with short lifespan
📧 Email Verification Settings
verifyEmailConfig
- Email verification configuration
- Type:
{ enabled: boolean; emailConfig?: EmailConfig; mailService?: MailService; sender: string }
- Description: Controls email verification feature and email templates
- Default:
undefined
(email verification disabled) - Child Properties:
enabled
: Enable email verification feature- Type:
boolean
- Description: Master switch for email verification functionality
- Default:
false
- Required: Yes (when using email verification)
- Type:
emailConfig
: Email template configuration- Type:
{ bodyTemplate: string; subject: string; urlTemplate: string }
- Description: Templates for verification emails
- Required: Yes (when enabled)
- Child Properties:
bodyTemplate
: HTML email body template- Type:
string
- Description: HTML template for email body with
{{url}}
,{{email}}
and{{token}}
placeholders. Will useurlTemplate
value forurl
- Example:
"Hello {{email}}, click <a href="{{url}}">here</a> to verify your email."
- Type:
subject
: Email subject line- Type:
string
- Description: Subject line for verification emails
- Example:
"Verify your email address"
- Type:
urlTemplate
: URL template for verification link- Type:
string
- Description: URL template with
{{email}}
and{{token}}
placeholders - Example:
"https://yourapp.com/verify?token={{token}}"
- Type:
- Type:
mailService
: Mail service implementation- Type:
MailService
- Description: Mail service for sending verification emails
- Required: No (can be provided as third parameter to service)
- Example: Custom mail service implementation
- Type:
sender
: Sender email address- Type:
string
- Description: Email address that verification emails will be sent from
- Required: Yes (when enabled)
- Example:
"noreply@yourapp.com"
- Type:
📨 Invitation Settings
invitation
- Invitation management configuration
- Type:
{ enabled: boolean; emailConfig?: InvitationEmailConfig; target: string }
- Description: Controls invitation feature and email templates
- Default:
undefined
(invitation feature disabled) - Child Properties:
enabled
: Enable invitation feature- Type:
boolean
- Description: Master switch for invitation functionality
- Default:
false
- Required: Yes (when using invitation feature)
- Type:
emailConfig
: Invitation email template configuration- Type:
{ bodyTemplate: string; subject: string; urlTemplate: string; sender: string }
- Description: Templates for invitation emails
- Required: Yes (when enabled)
- Child Properties:
bodyTemplate
: HTML email body template- Type:
string
- Description: HTML template for email body with
{{url}}
,{{token}}
and{{email}}
placeholders. Will useurlTemplate
value forurl
- Example:
"<h1>You're invited!</h1><p>Click <a href='{{url}}'>here</a> to accept the invitation.</p>"
- Type:
subject
: Email subject line- Type:
string
- Description: Subject line for invitation emails
- Example:
"You're invited to join our organization"
- Type:
urlTemplate
: URL template for invitation link- Type:
string
- Description: URL template with
{{token}}
and{{email}}
placeholders - Example:
"https://yourapp.com/invitations/accept?token={{token}}&email={{email}}"
- Type:
sender
: Sender email address- Type:
string
- Description: Email address that invitation emails will be sent from
- Required: Yes (when enabled)
- Example:
"invites@yourapp.com"
- Type:
- Type:
target
: Token target for invitation validation- Type:
string
- Description: Target identifier for invitation token validation
- Default:
"invitation"
- Required: No
- Example:
"invitation"
- Type:
Example Configuration
const authConfig = {
authSecrets: {
authEncSecret: process.env.AUTH_ENC_SECRET || 'your-enc-secret',
authSignSecret: process.env.AUTH_SIGN_SECRET || 'your-sign-secret'
},
maxFailedLoginAttempts: 3,
cookieOpts: {
secure: true,
sameSite: 'strict',
maxAge: 2 * 24 * 60 * 60 * 1000 // 2 days
},
accessTokenExpireTime: '1h',
refreshTokenExpireTime: '7d',
onetimeTokenExpireTime: '30m',
verifyEmailConfig: {
enabled: true,
emailConfig: {
bodyTemplate: 'Hello {{email}}, click <a href="{{url}}">here</a> to verify your email address.',
subject: 'Verify your email address',
urlTemplate: 'https://yourapp.com/verify?token={{token}}'
},
sender: 'noreply@yourapp.com'
},
invitation: {
enabled: true,
emailConfig: {
bodyTemplate: '<h1>You\'re invited!</h1><p>Click <a href="{{url}}">here</a> to accept the invitation.</p>',
subject: 'You\'re invited to join our organization',
urlTemplate: 'https://yourapp.com/invitations/accept?token={{token}}&email={{email}}',
sender: 'invites@yourapp.com'
},
target: 'invitation'
}
};
🚨 Error Handling
All authentication errors return JSON format with appropriate HTTP status codes:
Common Error Codes
Status | Error Message | Description |
---|---|---|
400 | Validation Error | Invalid request body format |
400 | verification email feature not enabled | Email verification not configured |
400 | verification email feature requires a mail service to be provided | Mail service not configured |
400 | verifyEmailConfig requires emailConfig with fields bodyTemplate, subject, urlTemplate | Missing email configuration |
400 | Unable to verify token | Invalid verification token |
401 | wrong credentials provided | Invalid email/password |
401 | This account is locked | Account locked due to failed attempts |
401 | Token is not valid access token | Invalid or expired token |
401 | Token fails security check | Token security validation failed |
401 | token could not be verified | Missing or invalid authorization token |
403 | token does not contain expected data | Token validation failed |
403 | User is not authorized to access this resource | User lacks required permissions (admin access) |
404 | User not found | User does not exist |
404 | Invitation not found | Invitation does not exist |
409 | Email already verified or no changes made | Email already verified |
422 | unable to register "email" | Email already exists |
500 | unable to generate access token | Token generation failed |
500 | unable to generate refresh token | Refresh token generation failed |
500 | Failed to send verification email | Email sending process failed |
400/500 | Failed to create invitation | Invitation creation failed |
Error Response Format
{
"error": {
"message": "Error message description",
"data": ["Additional error details"]
}
}
🔗 Related Documentation
- User Service - User management operations
- Error Handling - Error middleware and handling