🔐 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 { services, middlewares, types, drivers } from '@nodeblocks/backend-sdk';
const { getMongoClient, createGoogleOAuthDriver, createTwitterOAuthDriver } = drivers;
const client = getMongoClient('mongodb://localhost:27017', 'dev');
express()
.use(
services.authService(
{
identities: client.collection('identities'),
onetimetokens: client.collection('onetimetokens'),
invitations: client.collection('invitations'),
},
{
authSecrets: {
authEncSecret: 'your-encryption-secret',
authSignSecret: 'your-signing-secret',
},
maxFailedLoginAttempts: 5,
accessTokenExpireTime: '2h',
refreshTokenExpireTime: '2d',
verifyEmailConfig: {
enabled: true,
emailConfig: {
bodyTemplate: 'Hello {{email}}',
subject: 'Welcome to our app',
urlTemplate: 'https://example.com/verify-email?token={{token}}',
},
sender: 'noreply@example.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'
}
},
{
mailService: {
sendMail: async (mailData: types.MailData) => {
console.log(mailData);
return true;
},
},
googleOAuthDriver: createGoogleOAuthDriver(
process.env.GOOGLE_CLIENT_ID!,
process.env.GOOGLE_CLIENT_SECRET!,
'https://example.com/auth/oauth/google/callback'
),
twitterOAuthDriver: createTwitterOAuthDriver(
process.env.TWITTER_CONSUMER_KEY!,
process.env.TWITTER_CONSUMER_SECRET!,
'https://example.com/auth/oauth/twitter/callback'
)
}
)
)
.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 |
Email Management Endpoints | ||
PATCH | /auth/:identityId/change-email | Initiate email change process |
POST | /auth/confirm-new-email | Confirm new email address |
Password Management Endpoints | ||
POST | /auth/send-reset-password-link-email | Send password reset email |
POST | /auth/reset-password | Complete password reset process |
PATCH | /auth/:identityId/change-password | Change user password |
Account Management Endpoints | ||
POST | /auth/activate | Activate user account |
POST | /auth/deactivate | Deactivate user account |
Token Management Endpoints | ||
POST | /auth/token/refresh | Refresh access token using refresh token |
POST | /auth/token/check | Validate access token |
DELETE | /auth/:identityId/refresh-tokens | Delete refresh tokens for identity |
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 |
OAuth Endpoints | ||
GET | /auth/oauth/google | Initiate Google OAuth flow |
GET | /auth/oauth/google/callback | Process Google OAuth callback |
GET | /auth/oauth/twitter | Initiate Twitter OAuth flow |
GET | /auth/oauth/twitter/callback | Process Twitter OAuth callback |
🗄️ 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",
"fromIdentityId": "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 |
fromIdentityId | 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:
Field | Type | Required | Description |
---|---|---|---|
No 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: Require authenticated request (bearer token)
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"
}
}
3. Refresh Access Token
Refresh an access token using a valid refresh token.
Request:
- Method:
POST
- Path:
/auth/token/refresh
- Headers:
x-nb-fingerprint: <device-fingerprint>
- Authorization: Not required
Request Body:
Field | Type | Required | Description |
---|---|---|---|
refreshToken | string | ✅ | Valid refresh token to use for renewal |
Response Body:
Field | Type | Description |
---|---|---|
accessToken | string | New access token |
refreshToken | string | New refresh token |
Validation:
- Schema Validation: Enforced automatically (refreshToken required)
- Route Validators: None
Example Request:
curl -X POST {{host}}/auth/token/refresh \
-H "x-nb-fingerprint: <device-fingerprint>" \
-H "Content-Type: application/json" \
-d '{
"refreshToken": "<refresh-token>"
}'
Success Response:
HTTP/1.1 200 OK
Content-Type: application/json
{
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
Error Responses:
When refresh token is invalid:
HTTP/1.1 401 Unauthorized
Content-Type: application/json
{
"error": {
"message": "Invalid refresh token"
}
}
4. Delete Refresh Tokens
Delete refresh tokens for a specific identity (admin only or self).
Request:
- Method:
DELETE
- Path:
/auth/:identityId/refresh-tokens
- Headers:
Authorization: Bearer <access-token>
x-nb-fingerprint: <device-fingerprint>
- Authorization: Bearer token required
- Path Parameters:
identityId
: The ID of the identity whose refresh tokens to delete
Request Body:
Field | Type | Required | Description |
---|---|---|---|
No request body | - | No body required |
Response Body:
Field | Type | Description |
---|---|---|
No response body | - | Success returns 204 No Content |
Validation:
- Schema Validation: Enforced automatically (identityId path parameter required)
- Route Validators: Require authenticated request, admin privileges or self-access
Example Request (admin):
curl -X DELETE {{host}}/auth/user123/refresh-tokens \
-H "Authorization: Bearer <admin-access-token>" \
-H "x-nb-fingerprint: <device-fingerprint>"
Example Request (self):
curl -X DELETE {{host}}/auth/current-user-id/refresh-tokens \
-H "Authorization: Bearer <access-token>" \
-H "x-nb-fingerprint: <device-fingerprint>"
Success Response:
HTTP/1.1 204 No Content
Error Responses:
When identity not found:
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": {
"message": "Identity not found"
}
}
5. 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:
- Require authenticated request (bearer token)
- Require admin role or 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"
}
}
6. 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"
}
}
7. 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 |
fromIdentityId | 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, fromIdentityId required; no additional properties allowed)
- Route Validators:
- Require authenticated request (bearer token)
- Require admin role
Example Request:
curl -X POST {{host}}/invitations \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <access-token>" \
-d '{
"email": "newuser@example.com",
"fromIdentityId": "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 fromIdentityId:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "Validation Error",
"data": [
"request body must have required property 'fromIdentityId'"
]
}
}
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"
}
}
8. 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 |
fromIdentityId | 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 |
fromIdentityId | 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:
- Require authenticated request (bearer token)
- Require 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",
"fromIdentityId": "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
[]
9. 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:
- Require authenticated request (bearer token)
- Require 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",
"fromIdentityId": "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"
}
}
10. 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:
- Require authenticated request (bearer token)
- Require 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"
}
}
11. Change Email
Initiates the email change process for a user by sending a verification email to the new address.
Request:
- Method:
PATCH
- Path:
/auth/:identityId/change-email
- Headers:
Content-Type: application/json
- 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 |
---|---|---|---|
email | string | ✅ | New email address for the identity |
Response Body:
Field | Type | Description |
---|---|---|
No response body | - | Change email endpoint returns no response body on success |
Validation:
- Schema Validation: Enforced automatically (email required, must be valid email format)
- Route Validators:
- Require authenticated request (bearer token)
- Require admin role or self
Example Request:
curl -X PATCH {{host}}/auth/identity-12345/change-email \
-H "Content-Type: application/json" \
-d '{
"email": "newemail@example.com"
}'
Success Response:
HTTP/1.1 204 No Content
Content-Type: application/json
Error Responses:
When email already exists:
HTTP/1.1 409 Conflict
Content-Type: application/json
{
"error": {
"message": "Email already exists"
}
}
When identity is not found:
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": {
"message": "Identity not found"
}
}
12. Confirm New Email
Confirms a user's new email address using a one-time verification token.
Request:
- Method:
POST
- Path:
/auth/confirm-new-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 new 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-new-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": "Invalid token"
}
}
13. Send Reset Password Link Email
Sends a password reset link email to a user based on their email address.
Request:
- Method:
POST
- Path:
/auth/send-reset-password-link-email
- Headers:
Content-Type: application/json
- Authorization: None required
Request Body:
Field | Type | Required | Description |
---|---|---|---|
email | string | ✅ | Email address for password reset |
Response Body:
Field | Type | Description |
---|---|---|
No response body | - | Send reset password link email endpoint returns no response body on success |
Validation:
- Schema Validation: Enforced automatically (email required, must be valid email format)
- Route Validators: None
Example Request:
curl -X POST {{host}}/auth/send-reset-password-link-email \
-H "Content-Type: application/json" \
-d '{
"email": "user@example.com"
}'
Success Response:
HTTP/1.1 204 No Content
Content-Type: application/json
Error Responses:
When email is not found:
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": {
"message": "Email not found"
}
}
14. Complete Password Reset
Completes the password reset process by validating the token and updating the user's password.
Request:
- Method:
POST
- Path:
/auth/reset-password
- Headers:
Content-Type: application/json
Authorization: Bearer <one-time-token>
- Authorization: Bearer token required (one-time token)
Request Body:
Field | Type | Required | Description |
---|---|---|---|
password | string | ✅ | New password (8-24 characters, must contain lowercase letter and number) |
Response Body:
Field | Type | Description |
---|---|---|
No response body | - | Complete password reset endpoint returns no response body on success |
Validation:
- Schema Validation: Enforced automatically (password required, must meet security requirements)
- Route Validators: None
Example Request:
curl -X POST {{host}}/auth/reset-password \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <one-time-token>" \
-d '{
"password": "newSecurePassword123"
}'
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": "Invalid token"
}
}
When password doesn't meet requirements:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "Validation Error",
"data": [
"password must match pattern \"^(?=.*[a-z])(?=.*\\d)[a-zA-Z0-9?/_-]{8,24}$\""
]
}
}
15. Change Password
Changes user password via PATCH /auth/:identityId/change-password.
Request:
- Method:
PATCH
- Path:
/auth/:identityId/change-password
- Headers:
Content-Type: application/json
Authorization: Bearer <token>
x-nb-fingerprint: <device-fingerprint>
- Authorization: Bearer token required
Path Parameters:
Field | Type | Required | Description |
---|---|---|---|
identityId | string | ✅ | Identity's unique identifier |
Request Body:
Field | Type | Required | Description |
---|---|---|---|
password | string | ✅ | Current password for verification |
newPassword | string | ✅ | New password (8-24 characters, must contain lowercase letter and number) |
Response Body:
Field | Type | Description |
---|---|---|
No response body | - | Change password endpoint returns no response body on success |
Validation:
- Schema Validation: Enforced automatically (password, newPassword required, newPassword must meet security requirements)
- Route Validators:
- Require authenticated request (bearer token)
- Require admin role or self
Example Request:
curl -X PATCH {{host}}/auth/identity-12345/change-password \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <access-token>" \
-d '{
"password": "oldPassword123",
"newPassword": "newSecurePassword123"
}'
Success Response:
HTTP/1.1 204 No Content
Content-Type: application/json
Error Responses:
When current password is incorrect:
HTTP/1.1 401 Unauthorized
Content-Type: application/json
{
"error": {
"message": "Current password is incorrect"
}
}
When new password doesn't meet requirements:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "Validation Error",
"data": [
"newPassword must match pattern \"^(?=.*[a-z])(?=.*\\d)[a-zA-Z0-9?/_-]{8,24}$\""
]
}
}
16. Activate Account
Activates a user account via POST /auth/activate.
Request:
- Method:
POST
- Path:
/auth/activate
- Headers:
Content-Type: application/json
Authorization: Bearer <token>
- Authorization: Bearer token required (admin access)
Request Body:
Field | Type | Required | Description |
---|---|---|---|
identityId | string | ✅ | Identity's unique identifier for activation |
Response Body:
Field | Type | Description |
---|---|---|
No response body | - | Activate account endpoint returns no response body on success |
Validation:
- Schema Validation: Enforced automatically (identityId required)
- Route Validators:
- Require authenticated request (bearer token)
- Require admin role
Example Request:
curl -X POST {{host}}/auth/activate \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <access-token>" \
-d '{
"identityId": "identity-12345"
}'
Success Response:
HTTP/1.1 204 No Content
Content-Type: application/json
Error Responses:
When identity is not found:
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": {
"message": "Identity not found"
}
}
When email is not verified:
HTTP/1.1 403 Forbidden
Content-Type: application/json
{
"error": {
"message": "Email must be verified before activation"
}
}
17. Deactivate Account
Deactivates a user identity via POST /auth/deactivate.
Request:
- Method:
POST
- Path:
/auth/deactivate
- Headers:
Content-Type: application/json
Authorization: Bearer <token>
- Authorization: Bearer token required (admin or self access)
Request Body:
Field | Type | Required | Description |
---|---|---|---|
identityId | string | ✅ | Identity's unique identifier for deactivation |
Response Body:
Field | Type | Description |
---|---|---|
No response body | - | Deactivate account endpoint returns no response body on success |
Validation:
- Schema Validation: Enforced automatically (identityId required)
- Route Validators:
- Require authenticated request (bearer token)
- Require admin role or self
Example Request:
curl -X POST {{host}}/auth/deactivate \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <access-token>" \
-d '{
"identityId": "identity-12345"
}'
Success Response:
HTTP/1.1 204 No Content
Content-Type: application/json
Error Responses:
When identity is not found:
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": {
"message": "Identity not found"
}
}
When email is not verified:
HTTP/1.1 403 Forbidden
Content-Type: application/json
{
"error": {
"message": "Email must be verified before deactivation"
}
}
When token is missing:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "Missing token header"
}
}
When email sending fails:
HTTP/1.1 500 Internal Server Error
Content-Type: application/json
{
"error": {
"message": "Failed to send email"
}
}
18. Check Token
Validates an access token and returns its status.
Request:
- Method:
POST
- Path:
/auth/token/check
- Headers:
Content-Type: application/json
- Authorization: None required
Request Body:
Field | Type | Required | Description |
---|---|---|---|
token | string | ✅ | Token to validate |
target | string | ❌ | Optional target context for validation |
Response Body:
Field | Type | Description |
---|---|---|
identityId | string | Identity ID if token is valid |
Validation:
- Schema Validation: Enforced automatically (token required)
- Route Validators: None
Example Request:
curl -X POST {{host}}/auth/token/check \
-H "Content-Type: application/json" \
-d '{
"token": "jwt-token-to-validate",
"target": "optional-target-context"
}'
Success Response:
HTTP/1.1 200 OK
Content-Type: application/json
{
"identityId": "811ff0a3-a26f-447b-b68a-dd83ea4000b9"
}
Error Responses:
When token is invalid:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "Unable to verify token"
}
}
19. Initiate Google OAuth
Initiates the Google OAuth authentication flow by redirecting users to Google's authorization page. This flow can be used for both user login and signup, automatically creating new accounts for first-time users or authenticating existing users.
Request:
- Method:
GET
- Path:
/auth/oauth/google
- Headers: None required
- Authorization: None required
Request Body:
Field | Type | Required | Description |
---|---|---|---|
No request body | - | No body required. Uses query parameters for configuration. |
Query Parameters:
Field | Type | Required | Description |
---|---|---|---|
fp | string | ✅ | Device fingerprint for security |
purpose | string | ✅ | OAuth purpose: oauth-login or oauth-signup |
redirectUrl | string | ✅ | URL to redirect after OAuth completion |
typeId | string | ❌ | Identity type ID (required for signup) |
Response:
- Status:
302 Found
- Headers:
Location
header with Google OAuth URL
Response Body:
Field | Type | Description |
---|---|---|
No response body | - | OAuth initiation endpoint returns no response body on success |
Example Request:
# OAuth Login
curl -v "{{host}}/auth/oauth/google?fp=device-fingerprint&purpose=oauth-login&redirectUrl=http://localhost/oauth/callback"
# OAuth Signup
curl -v "{{host}}/auth/oauth/google?fp=device-fingerprint&purpose=oauth-signup&redirectUrl=http://localhost/oauth/callback&typeId=001"
Success Response:
HTTP/1.1 302 Found
Location: https://accounts.google.com/o/oauth2/v2/auth?prompt=consent&response_type=code&redirect_uri=...&scope=email%20profile&state=...&client_id=...
Error Responses:
When required parameters are missing:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "Validation Error",
"data": [
"query parameter 'fp' is required",
"query parameter 'purpose' is required",
"query parameter 'redirectUrl' is required"
]
}
}
When purpose has invalid value:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "Validation Error",
"data": [
"query parameter 'purpose' must be equal to one of the allowed values"
]
}
}
20. Google OAuth Callback
Processes the Google OAuth callback and completes the authentication flow. After successful processing, the user is redirected to the redirectUrl
that was specified in the initial OAuth request, with authentication tokens (either an onetime token or access token)
Request:
- Method:
GET
- Path:
/auth/oauth/google/callback
- Headers: None required
- Authorization: None required
Request Body:
Field | Type | Required | Description |
---|---|---|---|
No request body | - | No body required. Uses query parameters for OAuth callback processing. |
Query Parameters:
Field | Type | Required | Description |
---|---|---|---|
code | string | ✅ | One-time authorization code from Google (consumed by Passport.js for token exchange) |
state | string | ✅ | Signed JWT containing OAuth flow context (purpose, redirectUrl, typeId, fingerprint, userAgent) |
Response:
- Status:
302 Found
(redirect to final destination) - Headers:
Location
header with final redirect URL
Response Body:
Field | Type | Description |
---|---|---|
No response body | - | OAuth callback endpoint returns no response body on success |
Validation:
- Schema Validation: None
- Route Validators: None
Example Request:
curl -v "{{host}}/auth/oauth/google/callback?code=AUTH_CODE&state=STATE_TOKEN"
Success Response:
HTTP/1.1 302 Found
Location: http://localhost:3000/oauth/callback?token=JWT_TOKEN
Error Responses:
When OAuth state is invalid or expired:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "Invalid onetime token"
}
}
When typeId is missing for signup:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "typeId is required"
}
}
When identity creation fails:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "Failed to create identity"
}
}
When identity is not found:
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": {
"message": "No identity found for the given email."
}
}
When database operation fails:
HTTP/1.1 500 Internal Server Error
Content-Type: application/json
{
"error": {
"message": "Error finding or creating identity"
}
}
21. Initiate Twitter OAuth
Initiates the Twitter OAuth authentication flow by redirecting users to Twitter's authorization page. This flow can be used for both user login and signup, automatically creating new accounts for first-time users or authenticating existing users.
Request:
- Method:
GET
- Path:
/auth/oauth/twitter
- Headers: None required
- Authorization: None required
Request Body:
Field | Type | Required | Description |
---|---|---|---|
No request body | - | No body required. Uses query parameters for configuration. |
Query Parameters:
Field | Type | Required | Description |
---|---|---|---|
fp | string | ✅ | Device fingerprint for security |
purpose | string | ✅ | OAuth purpose: oauth-login or oauth-signup |
redirectUrl | string | ✅ | URL to redirect after OAuth completion |
typeId | string | ❌ | Identity type ID (required for signup) |
Response:
- Status:
302 Found
- Headers:
Location
header with Twitter OAuth URL
Response Body:
Field | Type | Description |
---|---|---|
No response body | - | OAuth initiation endpoint returns no response body on success |
Example Request:
# OAuth Login
curl -v "{{host}}/auth/oauth/twitter?fp=device-fingerprint&purpose=oauth-login&redirectUrl=http://localhost/oauth/callback"
# OAuth Signup
curl -v "{{host}}/auth/oauth/twitter?fp=device-fingerprint&purpose=oauth-signup&redirectUrl=http://localhost/oauth/callback&typeId=001"
Success Response:
HTTP/1.1 302 Found
Location: https://api.twitter.com/oauth/authenticate?oauth_token=...
Error Responses:
When required parameters are missing:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "Validation Error",
"data": [
"query parameter 'fp' is required",
"query parameter 'purpose' is required",
"query parameter 'redirectUrl' is required"
]
}
}
22. Twitter OAuth Callback
Processes the Twitter OAuth callback and completes the authentication flow. After successful processing, the user is redirected to the redirectUrl
that was specified in the initial OAuth request, with authentication tokens.
Request:
- Method:
GET
- Path:
/auth/oauth/twitter/callback
- Headers: None required
- Authorization: None required
Request Body:
Field | Type | Required | Description |
---|---|---|---|
No request body | - | No body required. Uses query parameters for OAuth callback processing. |
Query Parameters:
Field | Type | Required | Description |
---|---|---|---|
oauth_token | string | ✅ | OAuth token from Twitter |
oauth_verifier | string | ✅ | OAuth verifier from Twitter |
Response:
- Status:
302 Found
(redirect to final destination) - Headers:
Location
header with final redirect URL
Response Body:
Field | Type | Description |
---|---|---|
No response body | - | OAuth callback endpoint returns no response body on success |
Validation:
- Schema Validation: None
- Route Validators: None
Example Request:
curl -v "{{host}}/auth/oauth/twitter/callback?oauth_token=OAUTH_TOKEN&oauth_verifier=OAUTH_VERIFIER"
Success Response:
HTTP/1.1 302 Found
Location: http://localhost:3000/oauth/callback?token=JWT_TOKEN
Error Responses:
When OAuth token is invalid or expired:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "Invalid OAuth token"
}
}
When typeId is missing for signup:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "typeId is required"
}
}
When identity creation fails:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "Failed to create identity"
}
}
When identity is not found:
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": {
"message": "No identity found for the given Twitter ID."
}
}
🔒 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 AuthenticationServiceConfiguration {
authSecrets: {
authEncSecret: string; // JWT encryption secret
authSignSecret: string; // JWT signing secret
};
maxFailedLoginAttempts?: number; // Default: 5
cookieOpts?: {
domain?: string;
maxAge?: string | number;
path?: string;
sameSite?: 'strict' | 'lax' | 'none';
};
jwtOpts?: {
jwtSignOptions?: SignOptions;
stateful?: boolean;
};
accessTokenExpireTime?: string; // Default: '2h'
onetimeTokenExpireTime?: string; // Default: '2h'
refreshTokenExpireTime?: string; // Default: '2d'
identity?: {
typeIds?: {
admin: string; // Admin user type identifier
guest: string; // Guest user type identifier
regular: string; // Regular user type identifier
};
};
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
};
sender?: string; // Sender email address
};
sendResetPasswordEmailConfig?: {
emailConfig: {
bodyTemplate: string; // Email body template for password reset
subject: string; // Email subject for password reset
urlTemplate: string; // URL template with {{token}} placeholder
};
sender: string; // Sender email address for password reset emails
};
resetPasswordSuccessConfig?: {
emailConfig: {
bodyTemplate: string; // Email body template for successful password reset
subject: string; // Email subject for successful password reset
urlTemplate: string; // URL template for success confirmation
};
sender: string; // Sender email address for success notifications
};
changePasswordConfig?: {
emailConfig: {
bodyTemplate: string; // Email body template for password change notification
subject: string; // Email subject for password change
urlTemplate: string; // URL template for change confirmation
};
sender: string; // Sender email address for password change notifications
};
deactivateIdentityEmailConfig?: {
emailConfig: {
bodyTemplate: string; // Email body template for account deactivation
subject: string; // Email subject for deactivation
urlTemplate: string; // URL template for deactivation confirmation
};
sender: string; // Sender email address for deactivation emails
};
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
status?: {
pending?: string; // Status identifier for pending invitations
accepted?: string; // Status identifier for accepted invitations
};
};
oauth?: {
oauthCallbackTokenBehavior?: OauthCallbackTokenBehavior; // OAuth callback token behavior
};
}
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:
sender
: Sender email address- Type:
string
- Description: Email address that verification emails will be sent from
- Required: No (optional)
- Example:
"noreply@yourapp.com"
- Type:
🔐 Password Reset Email Settings
sendResetPasswordEmailConfig
- Password reset email configuration
- Type:
{ emailConfig: EmailConfig; sender: string }
- Description: Controls password reset email templates and sender
- Default: Predefined template with
bodyTemplate: 'Reset your password by clicking ${url}'
- Child Properties:
emailConfig
: Email template configuration- Type:
{ bodyTemplate: string; subject: string; urlTemplate: string }
- Description: Templates for password reset emails
- Required: Yes
- Child Properties:
bodyTemplate
: Email body template- Type:
string
- Description: HTML template with
${url}
placeholder - Example:
'Reset your password by clicking ${url}'
- Type:
subject
: Email subject line- Type:
string
- Description: Subject for password reset emails
- Example:
'Reset your password'
- Type:
urlTemplate
: URL template- Type:
string
- Description: URL template with
${token}
placeholder - Example:
'https://yourapp.com/reset-password?token=${token}'
- Type:
- Type:
sender
: Sender email address- Type:
string
- Description: Email address that password reset emails will be sent from
- Required: Yes
- Example:
"noreply@yourapp.com"
- Type:
resetPasswordSuccessConfig
- Password reset success email configuration
- Type:
{ emailConfig: EmailConfig; sender: string }
- Description: Controls password reset success notification templates
- Default: Predefined template with
bodyTemplate: 'Your password has been reset'
- Child Properties:
emailConfig
: Email template configuration (same structure as above)sender
: Sender email address for success notifications
changePasswordConfig
- Password change notification configuration
- Type:
{ emailConfig: EmailConfig; sender: string }
- Description: Controls password change notification templates
- Default: Predefined template with
bodyTemplate: 'Your password has been changed'
- Child Properties:
emailConfig
: Email template configuration (same structure as above)sender
: Sender email address for password change notifications
deactivateIdentityEmailConfig
- Account deactivation email configuration
- Type:
{ emailConfig: EmailConfig; sender: string }
- Description: Controls account deactivation notification templates
- Default: Predefined template with
bodyTemplate: 'Your account has been deactivated'
- Child Properties:
emailConfig
: Email template configuration (same structure as above)sender
: Sender email address for deactivation notifications
🔑 OAuth Settings
oauth
- OAuth configuration
- Type:
{ oauthCallbackTokenBehavior?: OauthCallbackTokenBehavior }
- Description: Controls OAuth callback behavior and token handling
- Default:
undefined
- Child Properties:
oauthCallbackTokenBehavior
: OAuth callback token behavior- Type:
OauthCallbackTokenBehavior
- Description: Defines how OAuth callback handles token generation
- Default: Standard OAuth token behavior
- Example: Custom token generation logic
- Type:
Service Options (3rd argument)
interface AuthServiceOptions {
mailService?: MailService; // Mail service implementation
googleOAuthDriver?: GoogleOAuthDriver; // Google OAuth driver instance
twitterOAuthDriver?: TwitterOAuthDriver; // Twitter OAuth driver instance
}
Provide these via the third argument to authService(dataStores, config, options)
.
📨 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:
status
: Invitation status configuration- Type:
{ pending?: string; accepted?: string }
- Description: Custom status identifiers for invitation states
- Default:
undefined
(uses default status values) - Child Properties:
pending
: Status identifier for pending invitations- Type:
string
- Description: Custom identifier for pending invitation status
- Example:
"pending"
- Type:
accepted
: Status identifier for accepted invitations- Type:
string
- Description: Custom identifier for accepted invitation status
- Example:
"accepted"
- Type:
- 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'
},
sendResetPasswordEmailConfig: {
emailConfig: {
bodyTemplate: 'Reset your password by clicking ${url}',
subject: 'Reset your password',
urlTemplate: 'https://yourapp.com/reset-password?token=${token}'
},
sender: 'noreply@yourapp.com'
},
resetPasswordSuccessConfig: {
emailConfig: {
bodyTemplate: 'Your password has been reset successfully',
subject: 'Password reset successful',
urlTemplate: 'https://yourapp.com/auth/callback/reset-password-success'
},
sender: 'noreply@yourapp.com'
},
changePasswordConfig: {
emailConfig: {
bodyTemplate: 'Your password has been changed successfully',
subject: 'Password change successful',
urlTemplate: 'https://yourapp.com/auth/callback/change-password-success'
},
sender: 'noreply@yourapp.com'
},
deactivateIdentityEmailConfig: {
emailConfig: {
bodyTemplate: 'Your account has been deactivated',
subject: 'Account deactivated',
urlTemplate: 'https://yourapp.com/account-deactivated'
},
sender: 'noreply@yourapp.com'
},
oauth: {
oauthCallbackTokenBehavior: 'onetime' // or 'access' for immediate access tokens
}
};
🚨 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