メインコンテンツまでスキップ
バージョン: 0.5.0 (最新)

🆔 アイデンティティサービス

Testing Status

アイデンティティサービスは、アイデンティティエンティティをCRUD操作で管理するための完全な REST API を提供します。NodeBlocks の関数型合成アプローチで構築され、MongoDB とシームレスに統合します。


🚀 クイックスタート

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'));

📋 エンドポイント概要

メソッドパス説明認可
GET/identities/:identityIdIDでアイデンティティを取得ベアラートークン必須(管理者のみ)
GET/identitiesアイデンティティの一覧/フィルタベアラートークン必須(管理者のみ)
PATCH/identities/:identityIdアイデンティティを更新ベアラートークン必須(管理者のみ)
DELETE/identities/:identityIdアイデンティティを削除ベアラートークン必須(管理者のみ)

🗄️ エンティティスキーマ

アイデンティティエンティティは、自動生成されるベースフィールドと、アイデンティティ固有のデータで構成されます:

{
"id": "string",
"createdAt": "string (datetime)",
"updatedAt": "string (datetime)",
"email": "string",
"emailVerified": "boolean",
"password": "string (hashed)",
"typeId": "string",
"attempts": "number",
"locked": "boolean"
}

フィールド詳細

フィールド自動生成必須説明
idstring一意識別子(UUID)
createdAtdatetime作成日時
updatedAtdatetime最終更新日時
emailstringユーザーのメールアドレス
emailVerifiedbooleanメール認証ステータス
passwordstringハッシュ化パスワード(bcrypt)
typeIdstringユーザー種別識別子(例: 管理者は "100")
attemptsnumberログイン試行回数
lockedbooleanアカウントロック状態

📝 注意: 自動生成フィールドはサービス側で設定され、作成/更新リクエストに含めないでください。


🔐 認証ヘッダー

すべてのエンドポイントで、次のヘッダーを含めてください:

Authorization: Bearer <access_token>
x-nb-fingerprint: <device_fingerprint>

⚠️ 重要: 認可時にフィンガープリントを指定した場合、認証済みのすべてのリクエストで x-nb-fingerprint ヘッダーが必須です。欠如している場合は 401 Unauthorized が返ります。

🔒 管理者アクセス必須: アイデンティティサービスのすべてのエンドポイントは管理者権限が必要です。ベアラートークンは管理者権限を持つユーザー(デフォルトの typeId は "100")のものである必要があります。非管理者は 403 Forbidden が返されます。


🔧 APIエンドポイント

1. アイデンティティの取得(ID指定)

一意のIDで特定のアイデンティティを取得します。

リクエスト:

  • Method: GET
  • Path: /identities/:identityId
  • ヘッダー:
    • Authorization: Bearer <token>
    • x-nb-fingerprint: <device-fingerprint>
  • 認可: ベアラートークン必須(管理者のみ)

URL パラメータ:

パラメータ必須説明
identityIdstringアイデンティティ一意識別子

レスポンスボディ:

フィールド説明
idstringアイデンティティ一意識別子
emailstringユーザーのメールアドレス
emailVerifiedbooleanメール認証ステータス
passwordstringハッシュ化パスワード(bcrypt)
typeIdstringユーザー種別識別子
attemptsnumberログイン試行回数
lockedbooleanアカウントロック状態
createdAtstring作成日時
updatedAtstring最終更新日時

バリデーション:

  • スキーマ検証: なし(GET リクエスト)
  • ルートバリデーション:
    • 認証済みリクエスト(ベアラー)必須
    • 管理者ロール必須

リクエスト例:

curl {{host}}/identities/811ff0a3-a26f-447b-b68a-dd83ea4000b9 \
-H "Authorization: Bearer your-access-token-here"

成功レスポンス:

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"
}

エラーレスポンス:

認可トークンが提供されていない場合:

HTTP/1.1 401 Unauthorized
Content-Type: application/json

{
"error": {
"message": "token could not be verified"
}
}

指定IDのアイデンティティが存在しない場合:

HTTP/1.1 404 Not Found
Content-Type: application/json

{
"error": {
"message": "Identity not found"
}
}

予期しないエラーが発生した場合(DB接続問題など):

HTTP/1.1 500 Internal Server Error
Content-Type: application/json

{
"error": {
"message": "Failed to get identity"
}
}

2. アイデンティティ一覧

フィルタやページングを指定してアイデンティティを取得します。

リクエスト:

  • Method: GET
  • Path: /identities
  • ヘッダー:
    • Authorization: Bearer <token>
    • x-nb-fingerprint: <device-fingerprint>
  • 認可: ベアラートークン必須(管理者のみ)

クエリパラメータ:

パラメータ必須説明
namestring名前でフィルタ
pagenumberページ番号
limitnumber1ページあたりの件数

レスポンスボディ:

フィールド説明
idstringアイデンティティ一意識別子
emailstringユーザーのメールアドレス
emailVerifiedbooleanメール認証ステータス
passwordstringハッシュ化パスワード(bcrypt)
typeIdstringユーザー種別識別子
attemptsnumberログイン試行回数
lockedbooleanアカウントロック状態
createdAtstring作成日時
updatedAtstring最終更新日時

バリデーション:

  • スキーマ検証: name(string)、page/limit(最小/最大制約のある整数)のクエリ検証
  • ルートバリデーション:
    • 認証済みリクエスト(ベアラー)必須
    • 管理者ロール必須

リクエスト例:

全件取得:

curl {{host}}/identities \
-H "Authorization: Bearer <access-token>"

名前でフィルタ:

curl "{{host}}/identities?name=admin" \
-H "Authorization: Bearer <access-token>"

種別でフィルタ:

curl "{{host}}/identities?typeId=100" \
-H "Authorization: Bearer <access-token>"

複合フィルタ:

curl "{{host}}/identities?name=admin&page=1&limit=20" \
-H "Authorization: Bearer <access-token>"

成功レスポンス:

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"
}
]

エラーレスポンス:

リソースにアクセスする権限がない場合:

HTTP/1.1 403 Forbidden
Content-Type: application/json

{
"error": {
"message": "User is not authorized to access this resource"
}
}

予期しないエラーが発生した場合(DB接続問題、フィルタ構文不正など):

HTTP/1.1 500 Internal Server Error
Content-Type: application/json

{
"error": {
"message": "Failed to find identities"
}
}

3. アイデンティティ更新

部分更新で既存のアイデンティティを更新します。

リクエスト:

  • Method: PATCH
  • Path: /identities/:identityId
  • ヘッダー:
    • Content-Type: application/json
    • Authorization: Bearer <token>
    • x-nb-fingerprint: <device-fingerprint>
  • 認可: ベアラートークン必須(管理者のみ)

URL パラメータ:

パラメータ必須説明
identityIdstringアイデンティティ一意識別子

リクエストボディ(全フィールド任意):

フィールド必須説明
emailstringユーザーのメールアドレス
emailVerifiedbooleanメール認証ステータス
typeIdstringユーザー種別識別子

レスポンスボディ:

フィールド説明
idstringアイデンティティ一意識別子
emailstring更新後のメールアドレス
emailVerifiedboolean更新後のメール認証ステータス
passwordstring更新後のハッシュ化パスワード
typeIdstring更新後のユーザー種別識別子
attemptsnumber更新後のログイン試行回数
lockedboolean更新後のアカウントロック状態
createdAtstring作成日時
updatedAtstring最終更新日時

バリデーション:

  • スキーマ検証: 基本的な検証(全フィールド任意、型チェック)
  • ルートバリデーション:
    • 認証済みリクエスト(ベアラー)必須
    • 管理者ロール必須

リクエスト例:

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"
}'

成功レスポンス:

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"
}

エラーレスポンス:

指定IDのアイデンティティが存在しない場合:

HTTP/1.1 404 Not Found
Content-Type: application/json

{
"error": {
"message": "Identity not found"
}
}

更新操作でデータが変更されない場合(変更なし):

HTTP/1.1 400 Bad Request
Content-Type: application/json

{
"error": {
"message": "Failed to update identity"
}
}

予期しないエラーが発生した場合(DB接続問題など):

HTTP/1.1 500 Internal Server Error
Content-Type: application/json

{
"error": {
"message": "Failed to update identity"
}
}

4. アイデンティティ削除

システムからアイデンティティを完全に削除します。

リクエスト:

  • Method: DELETE
  • Path: /identities/:identityId
  • ヘッダー:
    • Authorization: Bearer <token>
    • x-nb-fingerprint: <device-fingerprint>
  • 認可: ベアラートークン必須(管理者のみ)

URL パラメータ:

パラメータ必須説明
identityIdstringアイデンティティ一意識別子

レスポンスボディ:

フィールド説明
なし-成功時はレスポンスボディなし

バリデーション:

  • スキーマ検証: なし(DELETE リクエスト)
  • ルートバリデーション:
    • 認証済みリクエスト(ベアラー)必須
    • 管理者ロール必須

リクエスト例:

curl -X DELETE {{host}}/identities/be265523-7fea-44a1-a0a2-dc5dabdb9f0c \
-H "Authorization: Bearer <access-token>"

成功レスポンス:

HTTP/1.1 204 No Content

エラーレスポンス:

リソースにアクセスする権限がない場合:

HTTP/1.1 403 Forbidden
Content-Type: application/json

{
"error": {
"message": "User is not authorized to access this resource"
}
}

指定IDのアイデンティティが存在しない場合:

HTTP/1.1 404 Not Found
Content-Type: application/json

{
"error": {
"message": "Identity not found"
}
}

予期しないエラーが発生した場合(DB接続問題など):

HTTP/1.1 500 Internal Server Error
Content-Type: application/json

{
"error": {
"message": "Failed to delete identity"
}
}

⚙️ 設定オプション

サービス設定

interface IdentitiesServiceConfiguration {
authSecrets: {
authEncSecret: string; // JWT encryption secret
authSignSecret: string; // JWT signing secret
};
user?: {
typeIds?: {
admin: string; // Admin user type identifier
guest: string; // Guest user type identifier
user: string; // Regular user type identifier
};
};
}

設定詳細

アイデンティティサービスの設定は、セキュリティとユーザー種別管理の論理グループに整理されています。

🔐 セキュリティ設定

authSecrets - JWT トークンのセキュリティシークレット

  • : { authEncSecret: string; authSignSecret: string }
  • 説明: JWT の暗号化および署名に使用する秘密鍵(トークン検証に使用)
  • 必須: 本番環境では必須
  • 子プロパティ:
    • authEncSecret: JWT ペイロード暗号化の秘密鍵
    • authSignSecret: JWT 署名検証の秘密鍵

👥 ユーザー種別設定

user.typeIds - ユーザー種別識別子の設定

  • : { admin?: string; guest?: string; user?: string }
  • 説明: ロールベースアクセス制御のためのカスタムユーザー種別識別子
  • デフォルト: undefined(デフォルトの種別検証を使用)
  • 子プロパティ:
    • admin: 管理者ユーザー種別の識別子
      • : string
      • 説明: 管理者ユーザーのカスタム識別子
      • 利用例: 管理操作のロールベースアクセス制御
      • : "admin", "administrator", "superuser"
    • guest: ゲストユーザー種別の識別子
      • : string
      • 説明: ゲストユーザーのカスタム識別子
      • 利用例: 未認証/一時ユーザーの限定的アクセス
      • : "guest", "visitor", "anonymous"
    • user: 一般ユーザー種別の識別子
      • : string
      • 説明: 一般ユーザーのカスタム識別子
      • 利用例: 標準的なユーザー権限
      • : "user", "member", "customer"

Example Configuration

const identityConfig = {
authSecrets: {
authEncSecret: process.env.AUTH_ENC_SECRET || 'your-enc-secret',
authSignSecret: process.env.AUTH_SIGN_SECRET || 'your-sign-secret'
},
user: {
typeIds: {
admin: '100',
guest: '000',
user: '001'
}
}
};

🚨 エラーハンドリング

アイデンティティサービスのエラーは、適切なHTTPステータスコードとJSON形式で返されます:

代表的なエラーコード

ステータスエラーメッセージ説明
400Failed to update identity更新操作でデータが変更されない(変更なし)
401token could not be verified認可トークンがない/無効
403User is not authorized to access this resource要求操作に必要な権限が不足
404Identity not foundGET/PATCH/DELETE の対象アイデンティティが存在しない
500Failed to get identity取得中のDB接続問題/予期せぬ失敗
500Failed to find identities一覧取得中のDB接続問題/フィルタ不正/予期せぬ失敗
500Failed to update identity更新中のDB接続問題/予期せぬ失敗
500Failed to delete identity削除中のDB接続問題/予期せぬ失敗

エラーレスポンス形式

{
"error": {
"message": "Error message description",
"data": ["Additional error details"]
}
}

🔗 関連ドキュメント