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

👤 ユーザーサービス

Testing Status

ユーザーサービスは、CRUD操作とユーザーアカウントのロック/アンロック機能を含むユーザーエンティティ管理のための完全なREST APIを提供します。Nodeblocks関数コンポジションアプローチを使用して構築され、MongoDBとシームレスに統合されます。


🚀 クイックスタート

import express from 'express';
import { MongoClient } from 'mongodb';

import { middlewares, services } from '@nodeblocks/backend-sdk';

const { nodeBlocksErrorMiddleware } = middlewares;
const { userService } = services;

const client = new MongoClient('mongodb://localhost:27017').db('dev');

express()
.use(
userService(
{
users: client.collection('users'),
identity: client.collection('identity'),
},
{
authSecrets: {
authEncSecret: 'your-encryption-secret',
authSignSecret: 'your-signing-secret',
},
user: {
typeIds: {
admin: '100',
guest: '000',
user: '001',
},
},
}
)
)
.use(nodeBlocksErrorMiddleware())
.listen(8089, () => console.log('サーバーが起動しました'));

📋 エンドポイント概要

メソッドパス説明認証
POST/users新規ユーザーを作成Bearerトークン必須
GET/users/:userIdIDでユーザーを取得Bearerトークン必須(管理者/本人)
GET/usersユーザーリストを取得Bearerトークン必須(管理者のみ)
PATCH/users/:userIdユーザーを更新Bearerトークン必須(管理者/本人)
DELETE/users/:userIdユーザーを削除Bearerトークン必須(管理者/本人)
POST/users/:userId/lockユーザーアカウントをロックBearerトークン必須(管理者のみ)
POST/users/:userId/unlockユーザーアカウントをアンロックBearerトークン必須(管理者のみ)

🔧 必要な設定

データストア

ユーザーサービスには以下のMongoDBコレクションが必要です:

const dataStores = {
users: client.collection('users'), // ユーザープロフィール
identity: client.collection('identity'), // 認証情報
};

設定オプション

interface UserConfig {
authSecrets: {
authEncSecret: string;
authSignSecret: string;
};
user: {
typeIds: {
admin: string; // 管理者タイプID(例: '100')
guest: string; // ゲストタイプID(例: '000')
user: string; // 一般ユーザータイプID(例: '001')
};
};
}

👤 ユーザー操作

1. ユーザー作成

curl -X POST http://localhost:8089/users \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"email": "newuser@example.com",
"name": "新規ユーザー",
"role": "user",
"status": "active"
}'

レスポンス:

{
"userId": "uuid-here",
"message": "ユーザーが正常に作成されました"
}

2. ユーザー取得

# 特定ユーザーの取得
curl -X GET http://localhost:8089/users/user-uuid-here \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"

# ユーザーリストの取得(管理者のみ)
curl -X GET http://localhost:8089/users \
-H "Authorization: Bearer ADMIN_ACCESS_TOKEN"

レスポンス例:

{
"id": "uuid-here",
"email": "user@example.com",
"name": "ユーザー名",
"role": "user",
"status": "active",
"createdAt": "2024-01-15T10:30:00.000Z",
"updatedAt": "2024-01-15T10:30:00.000Z"
}

3. ユーザー更新

curl -X PATCH http://localhost:8089/users/user-uuid-here \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"name": "更新されたユーザー名",
"status": "active"
}'

4. ユーザー削除

curl -X DELETE http://localhost:8089/users/user-uuid-here \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"

🔒 アカウント管理

ユーザーアカウントロック

curl -X POST http://localhost:8089/users/user-uuid-here/lock \
-H "Authorization: Bearer ADMIN_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"reason": "セキュリティ違反"
}'

ユーザーアカウントアンロック

curl -X POST http://localhost:8089/users/user-uuid-here/unlock \
-H "Authorization: Bearer ADMIN_ACCESS_TOKEN"

🛡️ 認証と認可

アクセス制御ルール

操作管理者本人その他
ユーザー作成
ユーザー表示
ユーザーリスト
ユーザー更新
ユーザー削除
アカウントロック
アカウントアンロック

認証トークン

// リクエストヘッダー例
{
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

📊 データスキーマ

ユーザーエンティティ

interface User {
id: string; // 一意識別子
email: string; // メールアドレス(必須、一意)
name: string; // 表示名(必須)
role?: string; // ユーザーロール
status?: 'active' | 'inactive' | 'locked'; // アカウント状態
profile?: {
bio?: string;
avatar?: string;
phoneNumber?: string;
};
metadata?: Record<string, any>; // 追加メタデータ
createdAt: string; // 作成日時(ISO文字列)
updatedAt: string; // 更新日時(ISO文字列)
}

検証ルール

const userValidation = {
email: {
required: true,
format: 'email',
unique: true
},
name: {
required: true,
minLength: 2,
maxLength: 100
},
role: {
enum: ['admin', 'user', 'guest']
},
status: {
enum: ['active', 'inactive', 'locked'],
default: 'active'
}
};

🎯 高度な使用方法

カスタムユーザーフィールド

// 拡張ユーザースキーマ
const extendedUserConfig = {
...baseConfig,
customFields: {
department: { type: 'string', required: true },
employeeId: { type: 'string', unique: true },
preferences: {
theme: { type: 'string', enum: ['light', 'dark'] },
language: { type: 'string', default: 'ja' }
}
}
};

フィルタリングと検索

# 名前で検索
curl -X GET "http://localhost:8089/users?name=田中" \
-H "Authorization: Bearer ADMIN_ACCESS_TOKEN"

# ステータスでフィルタ
curl -X GET "http://localhost:8089/users?status=active" \
-H "Authorization: Bearer ADMIN_ACCESS_TOKEN"

# ページネーション
curl -X GET "http://localhost:8089/users?page=1&limit=10" \
-H "Authorization: Bearer ADMIN_ACCESS_TOKEN"

バルク操作

// 複数ユーザーの一括更新
const bulkUpdate = async (userUpdates) => {
const promises = userUpdates.map(update =>
userService.updateUser(update.id, update.data)
);
return await Promise.all(promises);
};

🔧 カスタマイゼーション

カスタムバリデーション

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

const customValidation = {
email: (email) => {
if (!email.endsWith('@company.com')) {
throw new Error('会社のメールアドレスを使用してください');
}
},
name: (name) => {
if (name.length < 2) {
throw new Error('名前は2文字以上で入力してください');
}
}
};

カスタムミドルウェア

// ユーザー作成前の処理
const preCreateUser = async (userData) => {
// カスタムロジック(例:外部APIでの重複チェック)
const exists = await externalAPI.checkUser(userData.email);
if (exists) {
throw new Error('ユーザーは既に外部システムに存在します');
}
return userData;
};

🧪 テスト

ユニットテスト例

import { userService } from '@nodeblocks/backend-sdk';
import { createMemoryDataStore } from '../test-utils';

describe('ユーザーサービス', () => {
let userApp;
let testDataStore;

beforeEach(() => {
testDataStore = createMemoryDataStore();
userApp = userService(
{
users: testDataStore.collection('users'),
identity: testDataStore.collection('identity'),
},
testConfig
);
});

test('ユーザー作成が成功する', async () => {
const userData = {
email: 'test@example.com',
name: 'テストユーザー',
role: 'user'
};

const response = await request(userApp)
.post('/users')
.set('Authorization', `Bearer ${adminToken}`)
.send(userData)
.expect(201);

expect(response.body.message).toBe('ユーザーが正常に作成されました');
});

test('重複メールアドレスを拒否する', async () => {
// 最初のユーザーを作成
await createUser({ email: 'test@example.com', name: 'User 1' });

// 同じメールアドレスで2番目のユーザー作成を試行
await request(userApp)
.post('/users')
.set('Authorization', `Bearer ${adminToken}`)
.send({ email: 'test@example.com', name: 'User 2' })
.expect(400);
});
});

🔗 関連リソース


➡️ 次のステップ

ユーザーサービスを設定したら、組織サービスと統合してチームベースのユーザー管理を検討してください。