UNPKG

@ahhaohho/auth-middleware

Version:

Shared authentication middleware with Passport.js for ahhaohho microservices

85 lines (73 loc) 2.56 kB
const redisManager = require('../config/redis'); /** * Redis 기반 토큰 블랙리스트 관리 */ /** * 토큰이 블랙리스트에 있는지 확인 * @param {string} userId - 사용자 ID * @param {string} tokenType - 토큰 타입 ('access' | 'refresh') * @param {string} token - JWT 토큰 * @returns {Promise<boolean>} 블랙리스트에 있으면 true */ async function isBlacklisted(userId, tokenType, token) { try { const redisClient = redisManager.getClient('token'); const key = `blacklist:${userId}:${tokenType}`; const tokens = await redisClient.smembers(key); return tokens.includes(token); } catch (error) { console.error('[@ahhaohho/auth-middleware] Error checking blacklist:', error.message); // Redis 에러 시 안전하게 false 반환 (통과시킴) return false; } } /** * 토큰을 블랙리스트에 추가 * @param {string} userId - 사용자 ID * @param {string} tokenType - 토큰 타입 ('access' | 'refresh') * @param {string} token - JWT 토큰 * @param {number} ttl - TTL (초 단위, 기본값: 토큰 만료 시간) * @returns {Promise<void>} */ async function addToBlacklist(userId, tokenType, token, ttl = null) { try { const redisClient = redisManager.getClient('token'); const key = `blacklist:${userId}:${tokenType}`; await redisClient.sadd(key, token); // TTL 설정 if (ttl) { await redisClient.expire(key, ttl); } else { // 기본 TTL: Access Token 1시간, Refresh Token 90일 const defaultTtl = tokenType === 'access' ? 60 * 60 : 90 * 24 * 60 * 60; await redisClient.expire(key, defaultTtl); } console.log(`[@ahhaohho/auth-middleware] Token added to blacklist: ${userId}:${tokenType}`); } catch (error) { console.error('[@ahhaohho/auth-middleware] Error adding to blacklist:', error.message); throw error; } } /** * 사용자의 모든 토큰을 블랙리스트에서 제거 * @param {string} userId - 사용자 ID * @returns {Promise<void>} */ async function clearBlacklist(userId) { try { const redisClient = redisManager.getClient('token'); await Promise.all([ redisClient.del(`blacklist:${userId}:access`), redisClient.del(`blacklist:${userId}:refresh`) ]); console.log(`[@ahhaohho/auth-middleware] Blacklist cleared for user: ${userId}`); } catch (error) { console.error('[@ahhaohho/auth-middleware] Error clearing blacklist:', error.message); throw error; } } module.exports = { isBlacklisted, addToBlacklist, clearBlacklist };