🆔 Identity Service
The Identity Service provides a complete REST API for managing identity entities with CRUD operations. It's built using the NodeBlocks functional composition approach and integrates seamlessly with MongoDB.
🚀 Quickstart
import express from 'express';
import { middlewares, services, drivers } from '@nodeblocks/backend-sdk';
const { nodeBlocksErrorMiddleware } = middlewares;
const { identitiesService } = services;
const { getMongoClient } = drivers;
const client = getMongoClient('mongodb://localhost:27017', 'dev');
express()
.use(
identitiesService(
{
identities: client.collection('identities'),
},
{
authSecrets: {
authEncSecret: 'your-encryption-secret',
authSignSecret: 'your-signing-secret',
},
identity: {
typeIds: {
admin: '100',
guest: '000',
regular: '001',
},
},
}
)
)
.use(nodeBlocksErrorMiddleware())
.listen(8089, () => console.log('Server running'));
📋 Endpoint Summary
Method | Path | Description | Authorization |
---|---|---|---|
GET | /identities/:identityId | Retrieve an identity by ID | Bearer token required (admin only) |
GET | /identities | List/filter identities | Bearer token required (admin only) |
PATCH | /identities/:identityId | Update an identity | Bearer token required (admin only) |
DELETE | /identities/:identityId | Delete an identity | Bearer token required (admin only) |
🗄️ Entity Schema
The identity entity combines base fields (auto-generated) with identity-specific data:
{
"id": "string",
"createdAt": "string (datetime)",
"updatedAt": "string (datetime)",
"email": "string",
"emailVerified": "boolean",
"password": "string (hashed)",
"typeId": "string",
"attempts": "number",
"locked": "boolean"
}
Field Details
Field | Type | Auto-Generated | Required | Description |
---|---|---|---|---|
id | string | ✅ | ✅ | Unique identifier (UUID) |
createdAt | datetime | ✅ | ✅ | Creation timestamp |
updatedAt | datetime | ✅ | ✅ | Last modification timestamp |
email | string | ❌ | ✅ | User's email address |
emailVerified | boolean | ❌ | ❌ | Email verification status |
password | string | ❌ | ✅ | Hashed password (bcrypt) |
typeId | string | ❌ | ❌ | User type identifier (e.g., "100" for admin) |
attempts | number | ❌ | ❌ | Login attempt counter |
locked | boolean | ❌ | ❌ | Account lock status |
📝 Note: Auto-generated fields are set by the service and should not be included in create/update requests.
🔐 Authentication Headers
For all 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.
🔒 Admin Access Required: All Identity Service endpoints require admin permissions. The bearer token must belong to a user with admin privileges (typeId: "100" by default). Non-admin users will receive a 403 Forbidden response.
🔧 API Endpoints
1. Get Identity by ID
Retrieves a specific identity by their unique ID.
Request:
- Method:
GET
- Path:
/identities/:identityId
- Headers:
Authorization: Bearer <token>
x-nb-fingerprint: <device-fingerprint>
- Authorization: Bearer token required (admin only)
URL Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
identityId | string | ✅ | Unique identity identifier |
Response Body:
Field | Type | Description |
---|---|---|
id | string | Unique identity identifier |
email | string | User's email address |
emailVerified | boolean | Email verification status |
password | string | Hashed password (bcrypt) |
typeId | string | User type identifier |
attempts | number | Login attempt counter |
locked | boolean | Account lock status |
createdAt | string | Creation timestamp |
updatedAt | string | Last update timestamp |
Validation:
- Schema Validation: None (GET request)
- Route Validators:
- Require authenticated request (bearer token)
- Require admin role
Example Request:
curl {{host}}/identities/811ff0a3-a26f-447b-b68a-dd83ea4000b9 \
-H "Authorization: Bearer your-access-token-here"
Success Response:
HTTP/1.1 200 OK
Content-Type: application/json
{
"attempts": 0,
"email": "admin@example.com",
"emailVerified": true,
"locked": false,
"password": "$2b$10$a3BUe3mJilkygX9eH04QWeP62c/8mv2.dUM3rbHGuLLQhjlGdr.dm",
"createdAt": "2025-07-29T07:37:01.735Z",
"id": "811ff0a3-a26f-447b-b68a-dd83ea4000b9",
"updatedAt": "2025-07-29T07:39:36.564Z",
"typeId": "100"
}
Error Responses:
When no authorization token is provided:
HTTP/1.1 401 Unauthorized
Content-Type: application/json
{
"error": {
"message": "token could not be verified"
}
}
When no identity exists with the provided ID:
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": {
"message": "Identity not found"
}
}
When an unexpected error occurs (database connection issues, etc.):
HTTP/1.1 500 Internal Server Error
Content-Type: application/json
{
"error": {
"message": "Failed to get identity"
}
}
2. List Identities
Retrieves a list of identities with optional filtering and pagination.
Request:
- Method:
GET
- Path:
/identities
- Headers:
Authorization: Bearer <token>
x-nb-fingerprint: <device-fingerprint>
- Authorization: Bearer token required (admin only)
Query Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
name | string | ❌ | Filter identities by name |
page | number | ❌ | Page number |
limit | number | ❌ | Items per page |
Response Body:
Field | Type | Description |
---|---|---|
id | string | Unique identity identifier |
email | string | User's email address |
emailVerified | boolean | Email verification status |
password | string | Hashed password (bcrypt) |
typeId | string | User type identifier |
attempts | number | Login attempt counter |
locked | boolean | Account lock status |
createdAt | string | Creation timestamp |
updatedAt | string | Last update timestamp |
Validation:
- Schema Validation: Query parameter validation for name (string), page and limit (integers with min/max constraints)
- Route Validators:
- Require authenticated request (bearer token)
- Require admin role
Example Requests:
List all identities:
curl {{host}}/identities \
-H "Authorization: Bearer <access-token>"
Filter by name:
curl "{{host}}/identities?name=admin" \
-H "Authorization: Bearer <access-token>"
Filter by type:
curl "{{host}}/identities?typeId=100" \
-H "Authorization: Bearer <access-token>"
Combine filters:
curl "{{host}}/identities?name=admin&page=1&limit=20" \
-H "Authorization: Bearer <access-token>"
Success Response:
HTTP/1.1 200 OK
Content-Type: application/json
[
{
"attempts": 0,
"email": "admin@example.com",
"emailVerified": true,
"locked": false,
"password": "$2b$10$a3BUe3mJilkygX9eH04QWeP62c/8mv2.dUM3rbHGuLLQhjlGdr.dm",
"createdAt": "2025-07-29T07:37:01.735Z",
"id": "811ff0a3-a26f-447b-b68a-dd83ea4000b9",
"updatedAt": "2025-07-29T07:39:36.564Z",
"typeId": "100"
},
{
"attempts": 0,
"email": "user@example.com",
"emailVerified": false,
"locked": false,
"password": "$2b$10$b4CVf4nKjmlzX0fI15RWeQ73d/9nw3.eVN4scIHLMRhkiHdr.eo",
"createdAt": "2025-07-29T07:38:15.123Z",
"id": "922ff1b4-b37g-558c-c79b-ee94fb5001c0",
"updatedAt": "2025-07-29T07:38:15.123Z",
"typeId": "001"
}
]
Error Responses:
When user is not authorized to access the resource:
HTTP/1.1 403 Forbidden
Content-Type: application/json
{
"error": {
"message": "User is not authorized to access this resource"
}
}
When an unexpected error occurs (database connection issues, invalid filter syntax, etc.):
HTTP/1.1 500 Internal Server Error
Content-Type: application/json
{
"error": {
"message": "Failed to find identities"
}
}
3. Update Identity
Updates an existing identity with partial data.
Request:
- Method:
PATCH
- Path:
/identities/:identityId
- Headers:
Content-Type: application/json
Authorization: Bearer <token>
x-nb-fingerprint: <device-fingerprint>
- Authorization: Bearer token required (admin only)
URL Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
identityId | string | ✅ | Unique identity identifier |
Request Body (all fields optional):
Field | Type | Required | Description |
---|---|---|---|
email | string | ❌ | User's email address |
emailVerified | boolean | ❌ | Email verification status |
typeId | string | ❌ | User type identifier |
Response Body:
Field | Type | Description |
---|---|---|
id | string | Unique identity identifier |
email | string | Updated email address |
emailVerified | boolean | Updated email verification status |
password | string | Updated hashed password |
typeId | string | Updated user type identifier |
attempts | number | Updated login attempt counter |
locked | boolean | Updated account lock status |
createdAt | string | Creation timestamp |
updatedAt | string | Last update timestamp |
Validation:
- Schema Validation: Basic validation (all fields optional, type checking)
- Route Validators:
- Require authenticated request (bearer token)
- Require admin role
Example Request:
curl -X PATCH {{host}}/identities/811ff0a3-a26f-447b-b68a-dd83ea4000b9 \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <access-token>" \
-d '{
"email": "admin@example.com",
"emailVerified": true,
"typeId": "200"
}'
Success Response:
HTTP/1.1 200 OK
Content-Type: application/json
{
"attempts": 0,
"email": "admin@example.com",
"locked": false,
"password": "$2b$10$a3BUe3mJilkygX9eH04QWeP62c/8mv2.dUM3rbHGuLLQhjlGdr.dm",
"createdAt": "2025-07-29T07:37:01.735Z",
"id": "811ff0a3-a26f-447b-b68a-dd83ea4000b9",
"updatedAt": "2025-07-29T07:42:07.611Z",
"typeId": "200"
}
Error Responses:
When no identity exists with the provided ID:
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": {
"message": "Identity not found"
}
}
When the update operation doesn't modify any data (no changes detected):
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": {
"message": "Failed to update identity"
}
}
When an unexpected error occurs (database connection issues, etc.):
HTTP/1.1 500 Internal Server Error
Content-Type: application/json
{
"error": {
"message": "Failed to update identity"
}
}
4. Delete Identity
Permanently deletes an identity from the system.
Request:
- Method:
DELETE
- Path:
/identities/:identityId
- Headers:
Authorization: Bearer <token>
x-nb-fingerprint: <device-fingerprint>
- Authorization: Bearer token required (admin only)
URL Parameters:
Parameter | Type | Required | Description |
---|---|---|---|
identityId | string | ✅ | Unique identity identifier |
Response Body:
Field | Type | Description |
---|---|---|
No response body | - | Delete endpoint returns no response body on success |
Validation:
- Schema Validation: None (DELETE request)
- Route Validators:
- Require authenticated request (bearer token)
- Require admin role
Example Request:
curl -X DELETE {{host}}/identities/be265523-7fea-44a1-a0a2-dc5dabdb9f0c \
-H "Authorization: Bearer <access-token>"
Success Response:
HTTP/1.1 204 No Content
Error Responses:
When user is not authorized to access the resource:
HTTP/1.1 403 Forbidden
Content-Type: application/json
{
"error": {
"message": "User is not authorized to access this resource"
}
}
When no identity exists with the provided ID:
HTTP/1.1 404 Not Found
Content-Type: application/json
{
"error": {
"message": "Identity not found"
}
}
When an unexpected error occurs (database connection issues, etc.):
HTTP/1.1 500 Internal Server Error
Content-Type: application/json
{
"error": {
"message": "Failed to delete identity"
}
}
⚙️ Configuration Options
Service Configuration
interface IdentitiesServiceConfiguration {
authSecrets: {
authEncSecret: string; // JWT encryption secret
authSignSecret: string; // JWT signing secret
};
identity?: {
typeIds?: {
admin: string; // Admin user type identifier
guest: string; // Guest user type identifier
regular: string; // Regular user type identifier
};
};
}
Configuration Details
The identity service configuration is organized into logical groups for security and user type management.
🔐 Security Settings
authSecrets
- JWT token security secrets
- Type:
{ authEncSecret: string; authSignSecret: string }
- Description: Secret keys for JWT encryption and signing (used for token validation)
- Required: Yes (for production)
- Child Properties:
authEncSecret
: Secret key for JWT payload encryptionauthSignSecret
: Secret key for JWT signature verification
👥 User Type Settings
identity.typeIds
- User type identifier configuration
- Type:
{ admin?: string; guest?: string; regular?: string }
- Description: Custom user type identifiers for role-based access control
- Default:
undefined
(uses default type validation) - Child Properties:
admin
: Admin user type identifier- Type:
string
- Description: Custom identifier for admin users
- Use Case: Role-based access control for administrative operations
- Example:
"admin"
,"administrator"
,"superuser"
- Type:
guest
: Guest user type identifier- Type:
string
- Description: Custom identifier for guest users
- Use Case: Limited access for unauthenticated or temporary users
- Example:
"guest"
,"visitor"
,"anonymous"
- Type:
regular
: Regular user type identifier- Type:
string
- Description: Custom identifier for regular users
- Use Case: Standard user access permissions
- Example:
"user"
,"member"
,"customer"
- Type:
Example Configuration
const identityConfig = {
authSecrets: {
authEncSecret: process.env.AUTH_ENC_SECRET || 'your-enc-secret',
authSignSecret: process.env.AUTH_SIGN_SECRET || 'your-sign-secret'
},
identity: {
typeIds: {
admin: '100',
guest: '000',
regular: '001'
}
}
};
🚨 Error Handling
All identity service errors return JSON format with appropriate HTTP status codes:
Common Error Codes
Status | Error Message | Description |
---|---|---|
400 | Failed to update identity | Update operation doesn't modify any data (no changes detected) |
401 | token could not be verified | Missing or invalid authorization token |
403 | User is not authorized to access this resource | Insufficient permissions for the requested operation |
404 | Identity not found | Identity doesn't exist for GET/PATCH/DELETE operations |
500 | Failed to get identity | Database connection issues or unexpected failures during retrieval |
500 | Failed to find identities | Database connection issues, invalid filter syntax, or unexpected failures during listing |
500 | Failed to update identity | Database connection issues or unexpected failures during update |
500 | Failed to delete identity | Database connection issues or unexpected failures during deletion |
Error Response Format
{
"error": {
"message": "Error message description",
"data": ["Additional error details"]
}
}
🔗 Related Documentation
- Error Handling - Understanding error patterns
- Schema Component - Data validation concepts
- Custom Service Tutorial - Build your own services
- User Service - User management service