UNPKG

@ahhaohho/auth-middleware

Version:

Shared authentication middleware with Passport.js for ahhaohho microservices

79 lines (66 loc) 2.16 kB
const Redis = require('ioredis'); /** * Redis 클라이언트 싱글톤 * 모든 서비스에서 하나의 Redis 연결만 사용 */ class RedisManager { constructor() { this.clients = {}; } /** * Redis 클라이언트 가져오기 * @param {string} type - 클라이언트 타입 (session, token, keys) * @returns {Redis} Redis 클라이언트 인스턴스 */ getClient(type = 'default') { if (!this.clients[type]) { this.clients[type] = this.createClient(type); } return this.clients[type]; } /** * Redis 클라이언트 생성 * @param {string} type - 클라이언트 타입 * @returns {Redis} Redis 클라이언트 */ createClient(type) { const config = { host: process.env.REDIS_HOST || process.env.ELASTICACHE_ENDPOINT || 'localhost', port: parseInt(process.env.REDIS_PORT || '6379', 10), connectTimeout: 10000, retryDelayOnFailover: 100, enableReadyCheck: false, maxRetriesPerRequest: null }; // TLS 활성화 조건: // 1. REDIS_TLS가 명시적으로 'true'로 설정된 경우 // 2. REDIS_HOST가 설정되지 않고 ELASTICACHE_ENDPOINT를 사용하는 경우 // 3. localhost/127.0.0.1이 아닌 경우 const isLocalhost = ['localhost', '127.0.0.1'].includes(config.host); const shouldUseTLS = process.env.REDIS_TLS === 'true' || (!process.env.REDIS_HOST && process.env.ELASTICACHE_ENDPOINT); if (shouldUseTLS && !isLocalhost) { config.tls = {}; } const client = new Redis(config); client.on('error', (err) => { console.error(`[@ahhaohho/auth-middleware] Redis (${type}) error:`, err.message); }); client.on('connect', () => { console.log(`[@ahhaohho/auth-middleware] Redis (${type}) connected`); }); return client; } /** * 모든 클라이언트 연결 종료 */ async closeAll() { const closePromises = Object.values(this.clients).map(client => client.quit()); await Promise.all(closePromises); this.clients = {}; } } // 싱글톤 인스턴스 const redisManager = new RedisManager(); module.exports = redisManager;