@ahhaohho/auth-middleware
Version:
Shared authentication middleware with Passport.js for ahhaohho microservices
80 lines (67 loc) • 2.42 kB
JavaScript
const { SecretsManagerClient, GetSecretValueCommand } = require('@aws-sdk/client-secrets-manager');
const redisManager = require('../config/redis');
/**
* AWS Secrets Manager에서 JWT 키 가져오기
*/
class SecretManager {
constructor() {
this.client = new SecretsManagerClient({
region: process.env.AWS_REGION || 'ap-northeast-2'
});
this.secretName = process.env.JWT_SECRET_NAME;
}
/**
* JWT 키 가져오기 (Redis 캐싱 포함)
* @returns {Promise<{current: string, previous: string|null}>}
*/
async getJwtKeys() {
if (!this.secretName) {
throw new Error('JWT_SECRET_NAME environment variable is not set');
}
try {
// 1. Redis 캐시 확인
const redisClient = redisManager.getClient('keys');
const cachedKeys = await redisClient.get(`jwt-keys:${this.secretName}`);
if (cachedKeys) {
console.log('[@ahhaohho/auth-middleware] Using cached JWT keys from Redis');
return JSON.parse(cachedKeys);
}
// 2. AWS Secrets Manager에서 가져오기
console.log('[@ahhaohho/auth-middleware] Fetching JWT keys from AWS Secrets Manager');
const command = new GetSecretValueCommand({ SecretId: this.secretName });
const response = await this.client.send(command);
if (!response.SecretString) {
throw new Error('Secret value is empty');
}
const secret = JSON.parse(response.SecretString);
const keys = {
current: secret.current || secret.jwt_secret_key || secret.dev,
previous: secret.previous || null
};
// 3. Redis에 캐싱 (5분 TTL)
await redisClient.set(
`jwt-keys:${this.secretName}`,
JSON.stringify(keys),
'EX',
300 // 5분
);
return keys;
} catch (error) {
console.error('[@ahhaohho/auth-middleware] Error fetching JWT keys:', error.message);
throw new Error('Failed to fetch JWT keys from AWS Secrets Manager');
}
}
/**
* 캐시 무효화
*/
async invalidateCache() {
const redisClient = redisManager.getClient('keys');
await redisClient.del(`jwt-keys:${this.secretName}`);
console.log('[@ahhaohho/auth-middleware] JWT keys cache invalidated');
}
}
const secretManager = new SecretManager();
module.exports = {
getJwtKeys: () => secretManager.getJwtKeys(),
invalidateCache: () => secretManager.invalidateCache()
};