Compare commits

...

3 Commits

Author SHA1 Message Date
Hyungi Ahn
0c149673fb refactor: shared 모듈 추출 Phase 1~4 (notifyHelper, errors, logger, auth, dbPool)
Phase 1: notifyHelper.js → shared/utils/ (4개 서비스 중복 제거)
Phase 2: auth.js → shared/middleware/ (system1/system2 통합)
Phase 3: errors.js + logger.js → shared/utils/ (system1/system2 통합)
Phase 4: DB pool → shared/config/database.js (Group B 4개 서비스 통합)

- Docker 빌드 컨텍스트를 루트로 변경 (6개 API 서비스)
- 기존 파일은 re-export 패턴으로 consumer 변경 0개 유지
- .dockerignore 추가로 빌드 최적화

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 19:07:22 +09:00
Hyungi Ahn
84cf222b81 feat(tkuser): 알림 시스템 이관 system1-factory → tkuser
- Phase 1: tkuser에 알림 CRUD, Push/ntfy 발송, 내부 알림 API 추가
- Phase 2: notifyHelper URL을 tkuser-api:3000으로 전환 (system2, tkpurchase, tksafety, system1)
- Phase 3: notification-bell.js API 도메인 tkuser로 변경 + 캐시 버스팅 v=4
- Phase 4: system1에서 알림 코드 제거 (routes, controllers, models, utils)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 15:56:41 +09:00
Hyungi Ahn
afa10c044f fix: 미커밋 수정사항 정리 (purchase migration, 로컬네트워크 URL, 포트 수정)
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 15:47:28 +09:00
60 changed files with 1044 additions and 1935 deletions

13
.dockerignore Normal file
View File

@@ -0,0 +1,13 @@
.git
.github
.claude
**/.env
**/node_modules
**/logs
**/__pycache__
**/.pytest_cache
**/venv
**/web/
*.md
!shared/**
FEATURES.pdf

View File

@@ -80,8 +80,8 @@ services:
system1-api:
build:
context: ./system1-factory/api
dockerfile: Dockerfile
context: .
dockerfile: system1-factory/api/Dockerfile
container_name: tk-system1-api
restart: unless-stopped
ports:
@@ -103,14 +103,7 @@ services:
- REDIS_PORT=6379
- WEATHER_API_URL=${WEATHER_API_URL:-}
- WEATHER_API_KEY=${WEATHER_API_KEY:-}
- VAPID_PUBLIC_KEY=${VAPID_PUBLIC_KEY}
- VAPID_PRIVATE_KEY=${VAPID_PRIVATE_KEY}
- VAPID_SUBJECT=${VAPID_SUBJECT:-mailto:admin@technicalkorea.net}
- INTERNAL_SERVICE_KEY=${INTERNAL_SERVICE_KEY}
- NTFY_BASE_URL=${NTFY_BASE_URL:-http://ntfy:80}
- NTFY_PUBLISH_TOKEN=${NTFY_PUBLISH_TOKEN}
- NTFY_EXTERNAL_URL=${NTFY_EXTERNAL_URL:-https://ntfy.technicalkorea.net}
- TKFB_BASE_URL=${TKFB_BASE_URL:-https://tkfb.technicalkorea.net}
volumes:
- system1_uploads:/usr/src/app/uploads
- system1_logs:/usr/src/app/logs
@@ -159,8 +152,8 @@ services:
system2-api:
build:
context: ./system2-report/api
dockerfile: Dockerfile
context: .
dockerfile: system2-report/api/Dockerfile
container_name: tk-system2-api
restart: unless-stopped
ports:
@@ -259,8 +252,8 @@ services:
tkuser-api:
build:
context: ./user-management/api
dockerfile: Dockerfile
context: .
dockerfile: user-management/api/Dockerfile
container_name: tk-tkuser-api
restart: unless-stopped
ports:
@@ -274,6 +267,14 @@ services:
- DB_PASSWORD=${MYSQL_PASSWORD}
- DB_NAME=${MYSQL_DATABASE:-hyungi}
- SSO_JWT_SECRET=${SSO_JWT_SECRET}
- VAPID_PUBLIC_KEY=${VAPID_PUBLIC_KEY}
- VAPID_PRIVATE_KEY=${VAPID_PRIVATE_KEY}
- VAPID_SUBJECT=${VAPID_SUBJECT:-mailto:admin@technicalkorea.net}
- INTERNAL_SERVICE_KEY=${INTERNAL_SERVICE_KEY}
- NTFY_BASE_URL=${NTFY_BASE_URL:-http://ntfy:80}
- NTFY_PUBLISH_TOKEN=${NTFY_PUBLISH_TOKEN}
- NTFY_EXTERNAL_URL=${NTFY_EXTERNAL_URL:-https://ntfy.technicalkorea.net}
- TKFB_BASE_URL=${TKFB_BASE_URL:-https://tkfb.technicalkorea.net}
volumes:
- system1_uploads:/usr/src/app/uploads
depends_on:
@@ -301,8 +302,8 @@ services:
tkpurchase-api:
build:
context: ./tkpurchase/api
dockerfile: Dockerfile
context: .
dockerfile: tkpurchase/api/Dockerfile
container_name: tk-tkpurchase-api
restart: unless-stopped
ports:
@@ -342,8 +343,8 @@ services:
tksafety-api:
build:
context: ./tksafety/api
dockerfile: Dockerfile
context: .
dockerfile: tksafety/api/Dockerfile
container_name: tk-tksafety-api
restart: unless-stopped
ports:
@@ -387,8 +388,8 @@ services:
tksupport-api:
build:
context: ./tksupport/api
dockerfile: Dockerfile
context: .
dockerfile: tksupport/api/Dockerfile
container_name: tk-tksupport-api
restart: unless-stopped
ports:

View File

@@ -16,8 +16,8 @@
var DROPDOWN_LIMIT = 5;
var API_ORIGIN = (function () {
var h = window.location.hostname;
if (h.includes('technicalkorea.net')) return 'https://tkfb.technicalkorea.net';
return window.location.protocol + '//' + h + ':30005';
if (h.includes('technicalkorea.net')) return 'https://tkuser.technicalkorea.net';
return window.location.protocol + '//' + h + ':30300';
})();
var API_BASE = API_ORIGIN + '/api/notifications';
var PUSH_API_BASE = API_ORIGIN + '/api/push';

28
shared/config/database.js Normal file
View File

@@ -0,0 +1,28 @@
/**
* 공유 데이터베이스 커넥션 풀
*
* Group B 서비스(tkuser, tkpurchase, tksafety, tksupport)용 동기 풀
* mysql2/promise 기반, 싱글톤 lazy initialization
*/
const mysql = require('mysql2/promise');
let pool;
function getPool() {
if (!pool) {
pool = mysql.createPool({
host: process.env.DB_HOST || 'mariadb',
port: parseInt(process.env.DB_PORT) || 3306,
user: process.env.DB_USER || 'hyungi_user',
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME || 'hyungi',
waitForConnections: true,
connectionLimit: parseInt(process.env.DB_CONN_LIMIT) || 10,
queueLimit: 0
});
}
return pool;
}
module.exports = { getPool };

360
shared/middleware/auth.js Normal file
View File

@@ -0,0 +1,360 @@
/**
* 통합 인증/인가 미들웨어
*
* JWT 토큰 검증 및 권한 체크를 위한 미들웨어 모음
*
* @author TK-FB-Project
* @since 2025-12-11
*/
const jwt = require('jsonwebtoken');
const { AuthenticationError, ForbiddenError } = require('../utils/errors');
const logger = require('../utils/logger');
// JWT_SECRET: system1/system2는 JWT_SECRET, 나머지는 SSO_JWT_SECRET 사용
const JWT_SECRET = process.env.JWT_SECRET || process.env.SSO_JWT_SECRET;
/**
* 권한 레벨 계층 구조
* 숫자가 높을수록 상위 권한
*/
const ACCESS_LEVELS = {
worker: 1,
group_leader: 2,
support_team: 3,
admin: 4,
system: 5
};
/**
* JWT 토큰 검증 미들웨어
*
* Authorization 헤더에서 Bearer 토큰을 추출하고 검증합니다.
* 검증 성공 시 req.user에 디코딩된 사용자 정보를 저장합니다.
*
* @throws {AuthenticationError} 토큰이 없거나 유효하지 않을 때
*
* @example
* router.get('/profile', requireAuth, getProfile);
*/
const requireAuth = (req, res, next) => {
try {
const authHeader = req.headers['authorization'];
if (!authHeader) {
logger.warn('인증 실패: Authorization 헤더 없음', {
path: req.path,
method: req.method,
ip: req.ip
});
throw new AuthenticationError('Authorization 헤더가 필요합니다');
}
const token = authHeader.split(' ')[1];
if (!token) {
logger.warn('인증 실패: Bearer 토큰 누락', {
path: req.path,
method: req.method,
ip: req.ip
});
throw new AuthenticationError('Bearer 토큰이 필요합니다');
}
// JWT 검증 (SSO 공유 시크릿)
const decoded = jwt.verify(token, JWT_SECRET);
req.user = decoded;
logger.debug('인증 성공', {
user_id: decoded.user_id || decoded.id,
username: decoded.username,
role: decoded.role,
access_level: decoded.access_level
});
next();
} catch (err) {
if (err.name === 'JsonWebTokenError') {
logger.warn('인증 실패: 유효하지 않은 토큰', {
error: err.message,
path: req.path,
ip: req.ip
});
throw new AuthenticationError('유효하지 않은 토큰입니다');
} else if (err.name === 'TokenExpiredError') {
logger.warn('인증 실패: 만료된 토큰', {
error: err.message,
path: req.path,
ip: req.ip
});
throw new AuthenticationError('토큰이 만료되었습니다');
} else if (err instanceof AuthenticationError) {
// 이미 AuthenticationError인 경우 그대로 throw
throw err;
} else {
logger.error('인증 처리 중 예상치 못한 오류', {
error: err.message,
stack: err.stack
});
throw new AuthenticationError('인증 처리 중 오류가 발생했습니다');
}
}
};
/**
* 특정 역할(들) 권한 체크 미들웨어
*
* 사용자가 지정된 역할 중 하나를 가지고 있는지 확인합니다.
* requireAuth 미들웨어가 먼저 실행되어야 합니다.
*
* @param {...string} roles - 허용할 역할 목록
* @returns {Function} Express 미들웨어 함수
* @throws {AuthenticationError} 인증되지 않은 경우
* @throws {ForbiddenError} 권한이 없는 경우
*
* @example
* // 단일 역할
* router.post('/admin/users', requireAuth, requireRole('admin'), createUser);
*
* // 여러 역할
* router.get('/reports', requireAuth, requireRole('admin', 'support_team'), getReports);
*/
const requireRole = (...roles) => {
return (req, res, next) => {
try {
if (!req.user) {
logger.warn('권한 체크 실패: 인증되지 않은 요청', {
path: req.path,
method: req.method,
ip: req.ip
});
throw new AuthenticationError('인증이 필요합니다');
}
const userRole = req.user.role;
const userRoleLower = userRole ? userRole.toLowerCase() : '';
const rolesLower = roles.map(r => r.toLowerCase());
if (!rolesLower.includes(userRoleLower)) {
logger.warn('권한 체크 실패: 역할 불일치', {
user_id: req.user.user_id || req.user.id,
username: req.user.username,
current_role: userRole,
required_roles: roles,
path: req.path
});
throw new ForbiddenError(
`이 기능을 사용하려면 ${roles.join(' 또는 ')} 권한이 필요합니다`
);
}
logger.debug('역할 권한 확인 성공', {
user_id: req.user.user_id || req.user.id,
username: req.user.username,
role: userRole,
required_roles: roles
});
next();
} catch (err) {
next(err);
}
};
};
/**
* 최소 권한 레벨 체크 미들웨어 (계층적)
*
* 사용자가 요구되는 최소 권한 레벨 이상인지 확인합니다.
* worker(1) < group_leader(2) < support_team(3) < admin(4) < system(5)
* requireAuth 미들웨어가 먼저 실행되어야 합니다.
*
* @param {string} minLevel - 최소 권한 레벨 (worker, group_leader, support_team, admin, system)
* @returns {Function} Express 미들웨어 함수
* @throws {AuthenticationError} 인증되지 않은 경우
* @throws {ForbiddenError} 권한이 부족한 경우
*
* @example
* // admin 이상 필요 (admin, system만 허용)
* router.delete('/users/:id', requireAuth, requireMinLevel('admin'), deleteUser);
*
* // group_leader 이상 필요 (group_leader, support_team, admin, system 허용)
* router.get('/team-reports', requireAuth, requireMinLevel('group_leader'), getTeamReports);
*/
const requireMinLevel = (minLevel) => {
return (req, res, next) => {
try {
if (!req.user) {
logger.warn('권한 레벨 체크 실패: 인증되지 않은 요청', {
path: req.path,
method: req.method,
ip: req.ip
});
throw new AuthenticationError('인증이 필요합니다');
}
const userLevel = ACCESS_LEVELS[req.user.access_level] || 0;
const requiredLevel = ACCESS_LEVELS[minLevel] || 999;
if (userLevel < requiredLevel) {
logger.warn('권한 레벨 체크 실패: 권한 부족', {
user_id: req.user.user_id || req.user.id,
username: req.user.username,
current_level: req.user.access_level,
current_level_value: userLevel,
required_level: minLevel,
required_level_value: requiredLevel,
path: req.path
});
throw new ForbiddenError(
`이 기능을 사용하려면 ${minLevel} 이상의 권한이 필요합니다 (현재: ${req.user.access_level})`
);
}
logger.debug('권한 레벨 확인 성공', {
user_id: req.user.user_id || req.user.id,
username: req.user.username,
access_level: req.user.access_level,
required_level: minLevel
});
next();
} catch (err) {
next(err);
}
};
};
/**
* 리소스 소유자 또는 관리자 권한 체크 미들웨어
*
* 요청한 사용자가 리소스의 소유자이거나 관리자 권한이 있는지 확인합니다.
* requireAuth 미들웨어가 먼저 실행되어야 합니다.
*
* @param {Object} options - 옵션 객체
* @param {string} options.resourceField - 리소스 ID를 가져올 req 필드 (예: 'params.user_id', 'body.user_id')
* @param {string} options.userField - 사용자 ID 필드명 (기본값: 'user_id', 'id'도 자동 시도)
* @param {string[]} options.adminRoles - 관리자로 인정할 역할들 (기본값: ['admin', 'system'])
* @returns {Function} Express 미들웨어 함수
* @throws {AuthenticationError} 인증되지 않은 경우
* @throws {ForbiddenError} 소유자도 아니고 관리자도 아닌 경우
*
* @example
* // URL 파라미터의 user_id로 체크
* router.put('/users/:user_id', requireAuth, requireOwnerOrAdmin({
* resourceField: 'params.user_id'
* }), updateUser);
*
* // 요청 body의 user_id로 체크, support_team도 관리자로 인정
* router.delete('/reports/:id', requireAuth, requireOwnerOrAdmin({
* resourceField: 'body.user_id',
* adminRoles: ['admin', 'system', 'support_team']
* }), deleteReport);
*/
const requireOwnerOrAdmin = (options = {}) => {
const {
resourceField = 'params.id',
userField = 'user_id',
adminRoles = ['admin', 'system']
} = options;
return (req, res, next) => {
try {
if (!req.user) {
logger.warn('소유자/관리자 체크 실패: 인증되지 않은 요청', {
path: req.path,
method: req.method,
ip: req.ip
});
throw new AuthenticationError('인증이 필요합니다');
}
// 관리자 권한 체크
const userRole = req.user.role;
const isAdmin = adminRoles.includes(userRole);
if (isAdmin) {
logger.debug('관리자 권한으로 접근 허용', {
user_id: req.user.user_id || req.user.id,
username: req.user.username,
role: userRole,
path: req.path
});
return next();
}
// 리소스 ID 추출
const fieldParts = resourceField.split('.');
let resourceId = req;
for (const part of fieldParts) {
resourceId = resourceId[part];
if (resourceId === undefined) break;
}
// 사용자 ID (user_id 또는 id)
const userId = req.user[userField] || req.user.id || req.user.user_id;
// 소유자 체크
const isOwner = resourceId && String(resourceId) === String(userId);
if (!isOwner) {
logger.warn('소유자/관리자 체크 실패: 권한 부족', {
user_id: userId,
username: req.user.username,
role: userRole,
resource_id: resourceId,
resource_field: resourceField,
is_admin: isAdmin,
is_owner: isOwner,
path: req.path
});
throw new ForbiddenError('본인의 리소스이거나 관리자 권한이 필요합니다');
}
logger.debug('리소스 소유자로 접근 허용', {
user_id: userId,
username: req.user.username,
resource_id: resourceId,
path: req.path
});
next();
} catch (err) {
next(err);
}
};
};
/**
* 레거시 호환성을 위한 별칭
* @deprecated requireAuth를 사용하세요
*/
const verifyToken = requireAuth;
/**
* 레거시 호환성을 위한 별칭
* @deprecated requireRole('admin', 'system')을 사용하세요
*/
const requireAdmin = requireRole('admin', 'system');
/**
* 레거시 호환성을 위한 별칭
* @deprecated requireRole('system')을 사용하세요
*/
const requireSystem = requireRole('system');
module.exports = {
// 주요 미들웨어
requireAuth,
requireRole,
requireMinLevel,
requireOwnerOrAdmin,
// 레거시 호환성
verifyToken,
requireAdmin,
requireSystem,
// 상수
ACCESS_LEVELS
};

186
shared/utils/errors.js Normal file
View File

@@ -0,0 +1,186 @@
/**
* 커스텀 에러 클래스
*
* 애플리케이션 전체에서 사용하는 표준화된 에러 클래스들
*
* @author TK-FB-Project
* @since 2025-12-11
*/
/**
* 기본 애플리케이션 에러 클래스
* 모든 커스텀 에러의 부모 클래스
*/
class AppError extends Error {
/**
* @param {string} message - 에러 메시지
* @param {number} statusCode - HTTP 상태 코드
* @param {string} code - 에러 코드 (예: 'VALIDATION_ERROR')
* @param {object} details - 추가 세부 정보
*/
constructor(message, statusCode = 500, code = 'INTERNAL_ERROR', details = null) {
super(message);
this.name = this.constructor.name;
this.statusCode = statusCode;
this.code = code;
this.details = details;
this.isOperational = true; // 운영 에러 (예상된 에러)
Error.captureStackTrace(this, this.constructor);
}
/**
* JSON 형태로 에러 정보 반환
*/
toJSON() {
return {
name: this.name,
message: this.message,
statusCode: this.statusCode,
code: this.code,
details: this.details
};
}
}
/**
* 검증 에러 (400 Bad Request)
* 입력값 검증 실패 시 사용
*/
class ValidationError extends AppError {
/**
* @param {string} message - 에러 메시지
* @param {object} details - 검증 실패 세부 정보
*/
constructor(message = '입력값이 올바르지 않습니다', details = null) {
super(message, 400, 'VALIDATION_ERROR', details);
}
}
/**
* 인증 에러 (401 Unauthorized)
* 인증이 필요하거나 인증 실패 시 사용
*/
class AuthenticationError extends AppError {
/**
* @param {string} message - 에러 메시지
*/
constructor(message = '인증이 필요합니다') {
super(message, 401, 'AUTHENTICATION_ERROR');
}
}
/**
* 권한 에러 (403 Forbidden)
* 권한이 부족할 때 사용
*/
class ForbiddenError extends AppError {
/**
* @param {string} message - 에러 메시지
*/
constructor(message = '권한이 없습니다') {
super(message, 403, 'FORBIDDEN');
}
}
/**
* 리소스 없음 에러 (404 Not Found)
* 요청한 리소스를 찾을 수 없을 때 사용
*/
class NotFoundError extends AppError {
/**
* @param {string} message - 에러 메시지
* @param {string} resource - 찾을 수 없는 리소스명
*/
constructor(message = '리소스를 찾을 수 없습니다', resource = null) {
super(message, 404, 'NOT_FOUND', resource ? { resource } : null);
}
}
/**
* 충돌 에러 (409 Conflict)
* 중복된 리소스 등 충돌 발생 시 사용
*/
class ConflictError extends AppError {
/**
* @param {string} message - 에러 메시지
* @param {object} details - 충돌 세부 정보
*/
constructor(message = '이미 존재하는 데이터입니다', details = null) {
super(message, 409, 'CONFLICT', details);
}
}
/**
* 서버 에러 (500 Internal Server Error)
* 예상하지 못한 서버 오류 시 사용
*/
class InternalServerError extends AppError {
/**
* @param {string} message - 에러 메시지
*/
constructor(message = '서버 오류가 발생했습니다') {
super(message, 500, 'INTERNAL_SERVER_ERROR');
}
}
/**
* 데이터베이스 에러 (500 Internal Server Error)
* DB 관련 오류 시 사용
*/
class DatabaseError extends AppError {
/**
* @param {string} message - 에러 메시지
* @param {Error} originalError - 원본 DB 에러
*/
constructor(message = '데이터베이스 오류가 발생했습니다', originalError = null) {
super(
message,
500,
'DATABASE_ERROR',
originalError ? { originalMessage: originalError.message } : null
);
this.originalError = originalError;
}
}
/**
* 외부 API 에러 (502 Bad Gateway)
* 외부 서비스 호출 실패 시 사용
*/
class ExternalApiError extends AppError {
/**
* @param {string} message - 에러 메시지
* @param {string} service - 외부 서비스명
*/
constructor(message = '외부 서비스 호출에 실패했습니다', service = null) {
super(message, 502, 'EXTERNAL_API_ERROR', service ? { service } : null);
}
}
/**
* 타임아웃 에러 (504 Gateway Timeout)
* 요청 처리 시간 초과 시 사용
*/
class TimeoutError extends AppError {
/**
* @param {string} message - 에러 메시지
* @param {number} timeout - 타임아웃 시간 (ms)
*/
constructor(message = '요청 처리 시간이 초과되었습니다', timeout = null) {
super(message, 504, 'TIMEOUT_ERROR', timeout ? { timeout } : null);
}
}
module.exports = {
AppError,
ValidationError,
AuthenticationError,
ForbiddenError,
NotFoundError,
ConflictError,
InternalServerError,
DatabaseError,
ExternalApiError,
TimeoutError
};

199
shared/utils/logger.js Normal file
View File

@@ -0,0 +1,199 @@
/**
* 로깅 유틸리티
*
* 애플리케이션 전체에서 사용하는 통합 로거
*
* @author TK-FB-Project
* @since 2025-12-11
*/
const fs = require('fs');
const path = require('path');
/**
* 로그 레벨 정의
*/
const LogLevel = {
ERROR: 'ERROR',
WARN: 'WARN',
INFO: 'INFO',
DEBUG: 'DEBUG'
};
/**
* 로그 레벨별 이모지
*/
const LogEmoji = {
ERROR: '❌',
WARN: '⚠️',
INFO: '',
DEBUG: '🔍'
};
/**
* 로그 레벨별 색상 (콘솔)
*/
const LogColor = {
ERROR: '\x1b[31m', // Red
WARN: '\x1b[33m', // Yellow
INFO: '\x1b[36m', // Cyan
DEBUG: '\x1b[90m', // Gray
RESET: '\x1b[0m'
};
class Logger {
constructor() {
// process.cwd() = /usr/src/app (컨테이너 WORKDIR)
// __dirname 대신 사용하여 shared/ 위치와 무관하게 서비스의 logs/ 디렉토리에 기록
this.logDir = path.join(process.cwd(), 'logs');
this.logFile = path.join(this.logDir, 'app.log');
this.errorFile = path.join(this.logDir, 'error.log');
this.ensureLogDirectory();
}
/**
* 로그 디렉토리 생성
*/
ensureLogDirectory() {
if (!fs.existsSync(this.logDir)) {
fs.mkdirSync(this.logDir, { recursive: true });
}
}
/**
* 타임스탬프 생성
*/
getTimestamp() {
return new Date().toISOString();
}
/**
* 로그 포맷팅
*/
formatLog(level, message, context = {}) {
const timestamp = this.getTimestamp();
const emoji = LogEmoji[level] || '';
const contextStr = Object.keys(context).length > 0
? `\n Context: ${JSON.stringify(context, null, 2)}`
: '';
return `[${timestamp}] [${level}] ${emoji} ${message}${contextStr}`;
}
/**
* 콘솔에 컬러 로그 출력
*/
logToConsole(level, message, context = {}) {
const color = LogColor[level] || LogColor.RESET;
const formattedLog = this.formatLog(level, message, context);
if (level === LogLevel.ERROR) {
console.error(`${color}${formattedLog}${LogColor.RESET}`);
} else if (level === LogLevel.WARN) {
console.warn(`${color}${formattedLog}${LogColor.RESET}`);
} else {
console.log(`${color}${formattedLog}${LogColor.RESET}`);
}
}
/**
* 파일에 로그 기록
*/
logToFile(level, message, context = {}) {
const formattedLog = this.formatLog(level, message, context);
const logEntry = `${formattedLog}\n`;
try {
// 모든 로그를 app.log에 기록
fs.appendFileSync(this.logFile, logEntry, 'utf8');
// 에러는 error.log에도 기록
if (level === LogLevel.ERROR) {
fs.appendFileSync(this.errorFile, logEntry, 'utf8');
}
} catch (err) {
console.error('로그 파일 기록 실패:', err);
}
}
/**
* 로그 기록 메인 함수
*/
log(level, message, context = {}) {
// 개발 환경에서는 콘솔에 출력
if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV !== 'production') {
this.logToConsole(level, message, context);
}
// 프로덕션에서는 파일에만 기록
if (process.env.NODE_ENV === 'production') {
this.logToFile(level, message, context);
}
}
/**
* 에러 로그
*/
error(message, context = {}) {
this.log(LogLevel.ERROR, message, context);
}
/**
* 경고 로그
*/
warn(message, context = {}) {
this.log(LogLevel.WARN, message, context);
}
/**
* 정보 로그
*/
info(message, context = {}) {
this.log(LogLevel.INFO, message, context);
}
/**
* 디버그 로그
*/
debug(message, context = {}) {
// DEBUG 로그는 개발 환경에서만 출력
if (process.env.NODE_ENV === 'development') {
this.log(LogLevel.DEBUG, message, context);
}
}
/**
* HTTP 요청 로그
*/
http(method, url, statusCode, duration, user = 'anonymous') {
const level = statusCode >= 400 ? LogLevel.ERROR : LogLevel.INFO;
const message = `${method} ${url} - ${statusCode} (${duration}ms)`;
const context = {
method,
url,
statusCode,
duration,
user
};
this.log(level, message, context);
}
/**
* 데이터베이스 쿼리 로그
*/
query(sql, params = [], duration = 0) {
if (process.env.NODE_ENV === 'development') {
this.debug('DB Query', {
sql,
params,
duration: `${duration}ms`
});
}
}
}
// 싱글톤 인스턴스 생성 및 내보내기
const logger = new Logger();
module.exports = logger;

View File

@@ -1,8 +1,8 @@
// utils/notifyHelper.js — 공용 알림 헬퍼
// system1-factory의 내부 알림 API를 통해 DB 저장 + Push 전송
// shared/utils/notifyHelper.js — 공용 알림 헬퍼
// tkuser-api의 내부 알림 API를 통해 DB 저장 + Push 전송
const http = require('http');
const NOTIFY_URL = 'http://system1-api:3005/api/notifications/internal';
const NOTIFY_URL = 'http://tkuser-api:3000/api/notifications/internal';
const SERVICE_KEY = process.env.INTERNAL_SERVICE_KEY || '';
const notifyHelper = {

View File

@@ -1,36 +1,27 @@
# Node.js 공식 이미지 사용
FROM node:18-alpine
# 작업 디렉토리 설정
WORKDIR /usr/src/app
# 패키지 파일 복사 (캐싱 최적화)
COPY package*.json ./
# shared 모듈 복사
COPY shared/ ./shared/
# 프로덕션 의존성 설치 (sharp용 빌드 도구 포함)
# 패키지 파일 복사 + 프로덕션 의존성 설치 (sharp용 빌드 도구 포함)
COPY system1-factory/api/package*.json ./
RUN apk add --no-cache --virtual .build-deps python3 make g++ && \
npm install --omit=dev && \
npm install sharp && \
apk del .build-deps
# 앱 소스 복사
COPY . .
COPY system1-factory/api/ ./
# 로그 디렉토리 생성
# 로그/업로드 디렉토리 생성
RUN mkdir -p logs uploads/issues uploads/equipments uploads/purchase_requests
# 실행 권한 설정
RUN chown -R node:node /usr/src/app
# 보안을 위해 non-root 사용자로 실행
USER node
# 포트 노출
EXPOSE 3005
# 헬스체크 추가
HEALTHCHECK --interval=30s --timeout=3s --start-period=40s --retries=3 \
CMD node -e "require('http').get('http://localhost:3005/api/health', (res) => { process.exit(res.statusCode === 200 ? 0 : 1); })"
# 앱 시작
CMD ["node", "index.js"]
CMD ["node", "index.js"]

View File

@@ -50,8 +50,6 @@ function setupRoutes(app) {
const workIssueRoutes = require('../routes/workIssueRoutes');
const departmentRoutes = require('../routes/departmentRoutes');
const patrolRoutes = require('../routes/patrolRoutes');
const notificationRoutes = require('../routes/notificationRoutes');
const pushSubscriptionRoutes = require('../routes/pushSubscriptionRoutes');
const purchaseRequestRoutes = require('../routes/purchaseRequestRoutes');
const purchaseRoutes = require('../routes/purchaseRoutes');
const settlementRoutes = require('../routes/settlementRoutes');
@@ -112,8 +110,6 @@ function setupRoutes(app) {
'/api/setup/check-data-status',
'/api/monthly-status/calendar',
'/api/monthly-status/daily-details',
'/api/push/vapid-public-key',
'/api/notifications/internal'
];
// 인증 미들웨어 - 공개 경로를 제외한 모든 API (rate limiter보다 먼저 실행)
@@ -164,8 +160,6 @@ function setupRoutes(app) {
app.use('/api/work-issues', workIssueRoutes); // 카테고리/아이템 + 신고 조회 (같은 MariaDB 공유)
app.use('/api/departments', departmentRoutes); // 부서 관리
app.use('/api/patrol', patrolRoutes); // 일일순회점검 시스템
app.use('/api/notifications', notificationRoutes); // 알림 시스템
app.use('/api/push', pushSubscriptionRoutes); // Push 구독
app.use('/api/purchase-requests', purchaseRequestRoutes); // 구매신청
app.use('/api/purchases', purchaseRoutes); // 구매 내역
app.use('/api/settlements', settlementRoutes); // 월간 정산

View File

@@ -21,6 +21,7 @@ CREATE TABLE IF NOT EXISTS vendors (
CREATE TABLE IF NOT EXISTS consumable_items (
item_id INT AUTO_INCREMENT PRIMARY KEY,
item_name VARCHAR(100) NOT NULL,
spec VARCHAR(200) DEFAULT NULL,
maker VARCHAR(100),
category ENUM('consumable','safety','repair','equipment') NOT NULL
COMMENT '소모품, 안전용품, 수선비, 설비',
@@ -30,7 +31,7 @@ CREATE TABLE IF NOT EXISTS consumable_items (
is_active TINYINT(1) DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY uq_name_maker (item_name, maker)
UNIQUE KEY uq_name_spec_maker (item_name, spec, maker)
);
-- 구매신청 (tkfb에서 CRUD) — item_id NULL 허용 + 직접입력/사진 컬럼 추가

View File

@@ -120,21 +120,4 @@ process.on('uncaughtException', (error) => {
}
})();
// 오래된 알림 정리 cron (매일 03:00 KST)
(function scheduleNotificationCleanup() {
const notificationModel = require('./models/notificationModel');
function runCleanup() {
const now = new Date();
const kstHour = (now.getUTCHours() + 9) % 24;
if (kstHour === 3 && now.getMinutes() < 1) {
notificationModel.deleteOld(30).then(count => {
if (count > 0) logger.info(`오래된 알림 ${count}건 정리 완료`);
}).catch(err => {
logger.error('알림 정리 실패:', { error: err.message });
});
}
}
setInterval(runCleanup, 60000); // 1분마다 확인
})();
module.exports = app;

View File

@@ -1,357 +1 @@
/**
* 통합 인증/인가 미들웨어
*
* JWT 토큰 검증 및 권한 체크를 위한 미들웨어 모음
*
* @author TK-FB-Project
* @since 2025-12-11
*/
const jwt = require('jsonwebtoken');
const { AuthenticationError, ForbiddenError } = require('../utils/errors');
const logger = require('../utils/logger');
/**
* 권한 레벨 계층 구조
* 숫자가 높을수록 상위 권한
*/
const ACCESS_LEVELS = {
worker: 1,
group_leader: 2,
support_team: 3,
admin: 4,
system: 5
};
/**
* JWT 토큰 검증 미들웨어
*
* Authorization 헤더에서 Bearer 토큰을 추출하고 검증합니다.
* 검증 성공 시 req.user에 디코딩된 사용자 정보를 저장합니다.
*
* @throws {AuthenticationError} 토큰이 없거나 유효하지 않을 때
*
* @example
* router.get('/profile', requireAuth, getProfile);
*/
const requireAuth = (req, res, next) => {
try {
const authHeader = req.headers['authorization'];
if (!authHeader) {
logger.warn('인증 실패: Authorization 헤더 없음', {
path: req.path,
method: req.method,
ip: req.ip
});
throw new AuthenticationError('Authorization 헤더가 필요합니다');
}
const token = authHeader.split(' ')[1];
if (!token) {
logger.warn('인증 실패: Bearer 토큰 누락', {
path: req.path,
method: req.method,
ip: req.ip
});
throw new AuthenticationError('Bearer 토큰이 필요합니다');
}
// JWT 검증 (SSO 공유 시크릿 - docker-compose에서 JWT_SECRET=SSO_JWT_SECRET로 설정)
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
logger.debug('인증 성공', {
user_id: decoded.user_id || decoded.id,
username: decoded.username,
role: decoded.role,
access_level: decoded.access_level
});
next();
} catch (err) {
if (err.name === 'JsonWebTokenError') {
logger.warn('인증 실패: 유효하지 않은 토큰', {
error: err.message,
path: req.path,
ip: req.ip
});
throw new AuthenticationError('유효하지 않은 토큰입니다');
} else if (err.name === 'TokenExpiredError') {
logger.warn('인증 실패: 만료된 토큰', {
error: err.message,
path: req.path,
ip: req.ip
});
throw new AuthenticationError('토큰이 만료되었습니다');
} else if (err instanceof AuthenticationError) {
// 이미 AuthenticationError인 경우 그대로 throw
throw err;
} else {
logger.error('인증 처리 중 예상치 못한 오류', {
error: err.message,
stack: err.stack
});
throw new AuthenticationError('인증 처리 중 오류가 발생했습니다');
}
}
};
/**
* 특정 역할(들) 권한 체크 미들웨어
*
* 사용자가 지정된 역할 중 하나를 가지고 있는지 확인합니다.
* requireAuth 미들웨어가 먼저 실행되어야 합니다.
*
* @param {...string} roles - 허용할 역할 목록
* @returns {Function} Express 미들웨어 함수
* @throws {AuthenticationError} 인증되지 않은 경우
* @throws {ForbiddenError} 권한이 없는 경우
*
* @example
* // 단일 역할
* router.post('/admin/users', requireAuth, requireRole('admin'), createUser);
*
* // 여러 역할
* router.get('/reports', requireAuth, requireRole('admin', 'support_team'), getReports);
*/
const requireRole = (...roles) => {
return (req, res, next) => {
try {
if (!req.user) {
logger.warn('권한 체크 실패: 인증되지 않은 요청', {
path: req.path,
method: req.method,
ip: req.ip
});
throw new AuthenticationError('인증이 필요합니다');
}
const userRole = req.user.role;
const userRoleLower = userRole ? userRole.toLowerCase() : '';
const rolesLower = roles.map(r => r.toLowerCase());
if (!rolesLower.includes(userRoleLower)) {
logger.warn('권한 체크 실패: 역할 불일치', {
user_id: req.user.user_id || req.user.id,
username: req.user.username,
current_role: userRole,
required_roles: roles,
path: req.path
});
throw new ForbiddenError(
`이 기능을 사용하려면 ${roles.join(' 또는 ')} 권한이 필요합니다`
);
}
logger.debug('역할 권한 확인 성공', {
user_id: req.user.user_id || req.user.id,
username: req.user.username,
role: userRole,
required_roles: roles
});
next();
} catch (err) {
next(err);
}
};
};
/**
* 최소 권한 레벨 체크 미들웨어 (계층적)
*
* 사용자가 요구되는 최소 권한 레벨 이상인지 확인합니다.
* worker(1) < group_leader(2) < support_team(3) < admin(4) < system(5)
* requireAuth 미들웨어가 먼저 실행되어야 합니다.
*
* @param {string} minLevel - 최소 권한 레벨 (worker, group_leader, support_team, admin, system)
* @returns {Function} Express 미들웨어 함수
* @throws {AuthenticationError} 인증되지 않은 경우
* @throws {ForbiddenError} 권한이 부족한 경우
*
* @example
* // admin 이상 필요 (admin, system만 허용)
* router.delete('/users/:id', requireAuth, requireMinLevel('admin'), deleteUser);
*
* // group_leader 이상 필요 (group_leader, support_team, admin, system 허용)
* router.get('/team-reports', requireAuth, requireMinLevel('group_leader'), getTeamReports);
*/
const requireMinLevel = (minLevel) => {
return (req, res, next) => {
try {
if (!req.user) {
logger.warn('권한 레벨 체크 실패: 인증되지 않은 요청', {
path: req.path,
method: req.method,
ip: req.ip
});
throw new AuthenticationError('인증이 필요합니다');
}
const userLevel = ACCESS_LEVELS[req.user.access_level] || 0;
const requiredLevel = ACCESS_LEVELS[minLevel] || 999;
if (userLevel < requiredLevel) {
logger.warn('권한 레벨 체크 실패: 권한 부족', {
user_id: req.user.user_id || req.user.id,
username: req.user.username,
current_level: req.user.access_level,
current_level_value: userLevel,
required_level: minLevel,
required_level_value: requiredLevel,
path: req.path
});
throw new ForbiddenError(
`이 기능을 사용하려면 ${minLevel} 이상의 권한이 필요합니다 (현재: ${req.user.access_level})`
);
}
logger.debug('권한 레벨 확인 성공', {
user_id: req.user.user_id || req.user.id,
username: req.user.username,
access_level: req.user.access_level,
required_level: minLevel
});
next();
} catch (err) {
next(err);
}
};
};
/**
* 리소스 소유자 또는 관리자 권한 체크 미들웨어
*
* 요청한 사용자가 리소스의 소유자이거나 관리자 권한이 있는지 확인합니다.
* requireAuth 미들웨어가 먼저 실행되어야 합니다.
*
* @param {Object} options - 옵션 객체
* @param {string} options.resourceField - 리소스 ID를 가져올 req 필드 (예: 'params.user_id', 'body.user_id')
* @param {string} options.userField - 사용자 ID 필드명 (기본값: 'user_id', 'id'도 자동 시도)
* @param {string[]} options.adminRoles - 관리자로 인정할 역할들 (기본값: ['admin', 'system'])
* @returns {Function} Express 미들웨어 함수
* @throws {AuthenticationError} 인증되지 않은 경우
* @throws {ForbiddenError} 소유자도 아니고 관리자도 아닌 경우
*
* @example
* // URL 파라미터의 user_id로 체크
* router.put('/users/:user_id', requireAuth, requireOwnerOrAdmin({
* resourceField: 'params.user_id'
* }), updateUser);
*
* // 요청 body의 user_id로 체크, support_team도 관리자로 인정
* router.delete('/reports/:id', requireAuth, requireOwnerOrAdmin({
* resourceField: 'body.user_id',
* adminRoles: ['admin', 'system', 'support_team']
* }), deleteReport);
*/
const requireOwnerOrAdmin = (options = {}) => {
const {
resourceField = 'params.id',
userField = 'user_id',
adminRoles = ['admin', 'system']
} = options;
return (req, res, next) => {
try {
if (!req.user) {
logger.warn('소유자/관리자 체크 실패: 인증되지 않은 요청', {
path: req.path,
method: req.method,
ip: req.ip
});
throw new AuthenticationError('인증이 필요합니다');
}
// 관리자 권한 체크
const userRole = req.user.role;
const isAdmin = adminRoles.includes(userRole);
if (isAdmin) {
logger.debug('관리자 권한으로 접근 허용', {
user_id: req.user.user_id || req.user.id,
username: req.user.username,
role: userRole,
path: req.path
});
return next();
}
// 리소스 ID 추출
const fieldParts = resourceField.split('.');
let resourceId = req;
for (const part of fieldParts) {
resourceId = resourceId[part];
if (resourceId === undefined) break;
}
// 사용자 ID (user_id 또는 id)
const userId = req.user[userField] || req.user.id || req.user.user_id;
// 소유자 체크
const isOwner = resourceId && String(resourceId) === String(userId);
if (!isOwner) {
logger.warn('소유자/관리자 체크 실패: 권한 부족', {
user_id: userId,
username: req.user.username,
role: userRole,
resource_id: resourceId,
resource_field: resourceField,
is_admin: isAdmin,
is_owner: isOwner,
path: req.path
});
throw new ForbiddenError('본인의 리소스이거나 관리자 권한이 필요합니다');
}
logger.debug('리소스 소유자로 접근 허용', {
user_id: userId,
username: req.user.username,
resource_id: resourceId,
path: req.path
});
next();
} catch (err) {
next(err);
}
};
};
/**
* 레거시 호환성을 위한 별칭
* @deprecated requireAuth를 사용하세요
*/
const verifyToken = requireAuth;
/**
* 레거시 호환성을 위한 별칭
* @deprecated requireRole('admin', 'system')을 사용하세요
*/
const requireAdmin = requireRole('admin', 'system');
/**
* 레거시 호환성을 위한 별칭
* @deprecated requireRole('system')을 사용하세요
*/
const requireSystem = requireRole('system');
module.exports = {
// 주요 미들웨어
requireAuth,
requireRole,
requireMinLevel,
requireOwnerOrAdmin,
// 레거시 호환성
verifyToken,
requireAdmin,
requireSystem,
// 상수
ACCESS_LEVELS
};
module.exports = require('../shared/middleware/auth');

View File

@@ -1,6 +1,6 @@
// models/equipmentModel.js
const { getDb } = require('../dbPool');
const notificationModel = require('./notificationModel');
const notifyHelper = require('../shared/utils/notifyHelper');
const EquipmentModel = {
// CREATE - 설비 생성
@@ -669,17 +669,16 @@ const EquipmentModel = {
['repair_needed', requestData.equipment_id]
);
try {
await notificationModel.createRepairNotification({
equipment_id: requestData.equipment_id,
equipment_name: requestData.equipment_name || '설비',
repair_type: requestData.repair_type || '일반 수리',
request_id: result.insertId,
created_by: requestData.reported_by
});
} catch (notifError) {
// 알림 생성 실패해도 수리 신청은 성공으로 처리
}
// fire-and-forget: 알림 실패가 수리 신청을 블로킹하면 안 됨
notifyHelper.send({
type: 'repair',
title: `수리 신청: ${requestData.equipment_name || '설비'}`,
message: `${requestData.repair_type || '일반 수리'} 수리가 신청되었습니다.`,
link_url: '/pages/admin/repair-management.html',
reference_type: 'work_issue_reports',
reference_id: result.insertId,
created_by: requestData.reported_by
}).catch(() => {});
return {
report_id: result.insertId,

View File

@@ -92,19 +92,15 @@ const PurchaseModel = {
} catch (err) {
console.error('[purchase] 설비 자동 등록 실패:', err.message);
// admin 알림 전송
try {
const notificationModel = require('./notificationModel');
await notificationModel.createTypedNotification({
type: 'equipment',
title: `설비 자동 등록 실패: ${purchaseData.item_name}`,
message: `구매 완료 후 설비 자동 등록에 실패했습니다. 수동으로 등록해주세요. 오류: ${err.message}`,
link_url: '/pages/admin/equipments.html',
created_by: purchaseData.purchaser_id
});
} catch (notifErr) {
console.error('[purchase] 설비 등록 실패 알림 전송 오류:', notifErr.message);
}
// fire-and-forget: admin 알림 전송
const notifyHelper = require('../shared/utils/notifyHelper');
notifyHelper.send({
type: 'equipment',
title: `설비 자동 등록 실패: ${purchaseData.item_name}`,
message: `구매 완료 후 설비 자동 등록 실패했습니다. 수동으로 등록해주세요. 오류: ${err.message}`,
link_url: '/pages/admin/equipments.html',
created_by: purchaseData.purchaser_id
}).catch(() => {});
return { success: false, error: err.message };
}

View File

@@ -39,8 +39,7 @@
"qrcode": "^1.5.4",
"redis": "^5.9.0",
"swagger-jsdoc": "^6.2.8",
"swagger-ui-express": "^5.0.1",
"web-push": "^3.6.7"
"swagger-ui-express": "^5.0.1"
},
"devDependencies": {
"@types/jest": "^29.5.12",

View File

@@ -1,186 +1 @@
/**
* 커스텀 에러 클래스
*
* 애플리케이션 전체에서 사용하는 표준화된 에러 클래스들
*
* @author TK-FB-Project
* @since 2025-12-11
*/
/**
* 기본 애플리케이션 에러 클래스
* 모든 커스텀 에러의 부모 클래스
*/
class AppError extends Error {
/**
* @param {string} message - 에러 메시지
* @param {number} statusCode - HTTP 상태 코드
* @param {string} code - 에러 코드 (예: 'VALIDATION_ERROR')
* @param {object} details - 추가 세부 정보
*/
constructor(message, statusCode = 500, code = 'INTERNAL_ERROR', details = null) {
super(message);
this.name = this.constructor.name;
this.statusCode = statusCode;
this.code = code;
this.details = details;
this.isOperational = true; // 운영 에러 (예상된 에러)
Error.captureStackTrace(this, this.constructor);
}
/**
* JSON 형태로 에러 정보 반환
*/
toJSON() {
return {
name: this.name,
message: this.message,
statusCode: this.statusCode,
code: this.code,
details: this.details
};
}
}
/**
* 검증 에러 (400 Bad Request)
* 입력값 검증 실패 시 사용
*/
class ValidationError extends AppError {
/**
* @param {string} message - 에러 메시지
* @param {object} details - 검증 실패 세부 정보
*/
constructor(message = '입력값이 올바르지 않습니다', details = null) {
super(message, 400, 'VALIDATION_ERROR', details);
}
}
/**
* 인증 에러 (401 Unauthorized)
* 인증이 필요하거나 인증 실패 시 사용
*/
class AuthenticationError extends AppError {
/**
* @param {string} message - 에러 메시지
*/
constructor(message = '인증이 필요합니다') {
super(message, 401, 'AUTHENTICATION_ERROR');
}
}
/**
* 권한 에러 (403 Forbidden)
* 권한이 부족할 때 사용
*/
class ForbiddenError extends AppError {
/**
* @param {string} message - 에러 메시지
*/
constructor(message = '권한이 없습니다') {
super(message, 403, 'FORBIDDEN');
}
}
/**
* 리소스 없음 에러 (404 Not Found)
* 요청한 리소스를 찾을 수 없을 때 사용
*/
class NotFoundError extends AppError {
/**
* @param {string} message - 에러 메시지
* @param {string} resource - 찾을 수 없는 리소스명
*/
constructor(message = '리소스를 찾을 수 없습니다', resource = null) {
super(message, 404, 'NOT_FOUND', resource ? { resource } : null);
}
}
/**
* 충돌 에러 (409 Conflict)
* 중복된 리소스 등 충돌 발생 시 사용
*/
class ConflictError extends AppError {
/**
* @param {string} message - 에러 메시지
* @param {object} details - 충돌 세부 정보
*/
constructor(message = '이미 존재하는 데이터입니다', details = null) {
super(message, 409, 'CONFLICT', details);
}
}
/**
* 서버 에러 (500 Internal Server Error)
* 예상하지 못한 서버 오류 시 사용
*/
class InternalServerError extends AppError {
/**
* @param {string} message - 에러 메시지
*/
constructor(message = '서버 오류가 발생했습니다') {
super(message, 500, 'INTERNAL_SERVER_ERROR');
}
}
/**
* 데이터베이스 에러 (500 Internal Server Error)
* DB 관련 오류 시 사용
*/
class DatabaseError extends AppError {
/**
* @param {string} message - 에러 메시지
* @param {Error} originalError - 원본 DB 에러
*/
constructor(message = '데이터베이스 오류가 발생했습니다', originalError = null) {
super(
message,
500,
'DATABASE_ERROR',
originalError ? { originalMessage: originalError.message } : null
);
this.originalError = originalError;
}
}
/**
* 외부 API 에러 (502 Bad Gateway)
* 외부 서비스 호출 실패 시 사용
*/
class ExternalApiError extends AppError {
/**
* @param {string} message - 에러 메시지
* @param {string} service - 외부 서비스명
*/
constructor(message = '외부 서비스 호출에 실패했습니다', service = null) {
super(message, 502, 'EXTERNAL_API_ERROR', service ? { service } : null);
}
}
/**
* 타임아웃 에러 (504 Gateway Timeout)
* 요청 처리 시간 초과 시 사용
*/
class TimeoutError extends AppError {
/**
* @param {string} message - 에러 메시지
* @param {number} timeout - 타임아웃 시간 (ms)
*/
constructor(message = '요청 처리 시간이 초과되었습니다', timeout = null) {
super(message, 504, 'TIMEOUT_ERROR', timeout ? { timeout } : null);
}
}
module.exports = {
AppError,
ValidationError,
AuthenticationError,
ForbiddenError,
NotFoundError,
ConflictError,
InternalServerError,
DatabaseError,
ExternalApiError,
TimeoutError
};
module.exports = require('../shared/utils/errors');

View File

@@ -1,197 +1 @@
/**
* 로깅 유틸리티
*
* 애플리케이션 전체에서 사용하는 통합 로거
*
* @author TK-FB-Project
* @since 2025-12-11
*/
const fs = require('fs');
const path = require('path');
/**
* 로그 레벨 정의
*/
const LogLevel = {
ERROR: 'ERROR',
WARN: 'WARN',
INFO: 'INFO',
DEBUG: 'DEBUG'
};
/**
* 로그 레벨별 이모지
*/
const LogEmoji = {
ERROR: '❌',
WARN: '⚠️',
INFO: '',
DEBUG: '🔍'
};
/**
* 로그 레벨별 색상 (콘솔)
*/
const LogColor = {
ERROR: '\x1b[31m', // Red
WARN: '\x1b[33m', // Yellow
INFO: '\x1b[36m', // Cyan
DEBUG: '\x1b[90m', // Gray
RESET: '\x1b[0m'
};
class Logger {
constructor() {
this.logDir = path.join(__dirname, '../logs');
this.logFile = path.join(this.logDir, 'app.log');
this.errorFile = path.join(this.logDir, 'error.log');
this.ensureLogDirectory();
}
/**
* 로그 디렉토리 생성
*/
ensureLogDirectory() {
if (!fs.existsSync(this.logDir)) {
fs.mkdirSync(this.logDir, { recursive: true });
}
}
/**
* 타임스탬프 생성
*/
getTimestamp() {
return new Date().toISOString();
}
/**
* 로그 포맷팅
*/
formatLog(level, message, context = {}) {
const timestamp = this.getTimestamp();
const emoji = LogEmoji[level] || '';
const contextStr = Object.keys(context).length > 0
? `\n Context: ${JSON.stringify(context, null, 2)}`
: '';
return `[${timestamp}] [${level}] ${emoji} ${message}${contextStr}`;
}
/**
* 콘솔에 컬러 로그 출력
*/
logToConsole(level, message, context = {}) {
const color = LogColor[level] || LogColor.RESET;
const formattedLog = this.formatLog(level, message, context);
if (level === LogLevel.ERROR) {
console.error(`${color}${formattedLog}${LogColor.RESET}`);
} else if (level === LogLevel.WARN) {
console.warn(`${color}${formattedLog}${LogColor.RESET}`);
} else {
console.log(`${color}${formattedLog}${LogColor.RESET}`);
}
}
/**
* 파일에 로그 기록
*/
logToFile(level, message, context = {}) {
const formattedLog = this.formatLog(level, message, context);
const logEntry = `${formattedLog}\n`;
try {
// 모든 로그를 app.log에 기록
fs.appendFileSync(this.logFile, logEntry, 'utf8');
// 에러는 error.log에도 기록
if (level === LogLevel.ERROR) {
fs.appendFileSync(this.errorFile, logEntry, 'utf8');
}
} catch (err) {
console.error('로그 파일 기록 실패:', err);
}
}
/**
* 로그 기록 메인 함수
*/
log(level, message, context = {}) {
// 개발 환경에서는 콘솔에 출력
if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV !== 'production') {
this.logToConsole(level, message, context);
}
// 프로덕션에서는 파일에만 기록
if (process.env.NODE_ENV === 'production') {
this.logToFile(level, message, context);
}
}
/**
* 에러 로그
*/
error(message, context = {}) {
this.log(LogLevel.ERROR, message, context);
}
/**
* 경고 로그
*/
warn(message, context = {}) {
this.log(LogLevel.WARN, message, context);
}
/**
* 정보 로그
*/
info(message, context = {}) {
this.log(LogLevel.INFO, message, context);
}
/**
* 디버그 로그
*/
debug(message, context = {}) {
// DEBUG 로그는 개발 환경에서만 출력
if (process.env.NODE_ENV === 'development') {
this.log(LogLevel.DEBUG, message, context);
}
}
/**
* HTTP 요청 로그
*/
http(method, url, statusCode, duration, user = 'anonymous') {
const level = statusCode >= 400 ? LogLevel.ERROR : LogLevel.INFO;
const message = `${method} ${url} - ${statusCode} (${duration}ms)`;
const context = {
method,
url,
statusCode,
duration,
user
};
this.log(level, message, context);
}
/**
* 데이터베이스 쿼리 로그
*/
query(sql, params = [], duration = 0) {
if (process.env.NODE_ENV === 'development') {
this.debug('DB Query', {
sql,
params,
duration: `${duration}ms`
});
}
}
}
// 싱글톤 인스턴스 생성 및 내보내기
const logger = new Logger();
module.exports = logger;
module.exports = require('../shared/utils/logger');

View File

@@ -1,41 +0,0 @@
// Push Notification Service Worker
// 캐싱 없음 — Push 수신 전용
self.addEventListener('push', function(event) {
var data = { title: '알림', body: '새 알림이 있습니다.', url: '/' };
if (event.data) {
try { data = Object.assign(data, event.data.json()); } catch(e) {}
}
event.waitUntil(
self.registration.showNotification(data.title, {
body: data.body,
icon: '/static/img/icon-192.png',
badge: '/static/img/badge-72.png',
data: { url: data.url || '/' },
tag: 'tk-notification-' + Date.now(),
renotify: true
})
);
// 메인 페이지에 뱃지 갱신 신호 전송
self.clients.matchAll({ type: 'window' }).then(function(clients) {
clients.forEach(function(client) {
client.postMessage({ type: 'NOTIFICATION_RECEIVED' });
});
});
});
self.addEventListener('notificationclick', function(event) {
event.notification.close();
var url = (event.notification.data && event.notification.data.url) || '/';
event.waitUntil(
self.clients.matchAll({ type: 'window' }).then(function(clients) {
for (var i = 0; i < clients.length; i++) {
if (clients[i].url.includes(self.location.origin)) {
clients[i].navigate(url);
return clients[i].focus();
}
}
return self.clients.openWindow(url);
})
);
});

View File

@@ -299,7 +299,7 @@ async function initAuth() {
/* ===== 알림 벨 ===== */
function _loadNotificationBell() {
const s = document.createElement('script');
s.src = (location.hostname.includes('technicalkorea.net') ? 'https://tkds.technicalkorea.net' : location.protocol + '//' + location.hostname + ':30000') + '/shared/notification-bell.js?v=3';
s.src = (location.hostname.includes('technicalkorea.net') ? 'https://tkds.technicalkorea.net' : location.protocol + '//' + location.hostname + ':30000') + '/shared/notification-bell.js?v=4';
document.head.appendChild(s);
}

View File

@@ -4,10 +4,13 @@ RUN apk add --no-cache imagemagick libheif imagemagick-heic imagemagick-jpeg
WORKDIR /usr/src/app
COPY package*.json ./
# shared 모듈 복사
COPY shared/ ./shared/
COPY system2-report/api/package*.json ./
RUN npm install --omit=dev
COPY . .
COPY system2-report/api/ ./
RUN mkdir -p logs uploads
RUN chown -R node:node /usr/src/app

View File

@@ -5,7 +5,7 @@
const workIssueModel = require('../models/workIssueModel');
const imageUploadService = require('../services/imageUploadService');
const mProjectService = require('../services/mProjectService');
const notify = require('../utils/notifyHelper');
const notify = require('../shared/utils/notifyHelper');
// ==================== 신고 카테고리 관리 ====================

View File

@@ -1,357 +1 @@
/**
* 통합 인증/인가 미들웨어
*
* JWT 토큰 검증 및 권한 체크를 위한 미들웨어 모음
*
* @author TK-FB-Project
* @since 2025-12-11
*/
const jwt = require('jsonwebtoken');
const { AuthenticationError, ForbiddenError } = require('../utils/errors');
const logger = require('../utils/logger');
/**
* 권한 레벨 계층 구조
* 숫자가 높을수록 상위 권한
*/
const ACCESS_LEVELS = {
worker: 1,
group_leader: 2,
support_team: 3,
admin: 4,
system: 5
};
/**
* JWT 토큰 검증 미들웨어
*
* Authorization 헤더에서 Bearer 토큰을 추출하고 검증합니다.
* 검증 성공 시 req.user에 디코딩된 사용자 정보를 저장합니다.
*
* @throws {AuthenticationError} 토큰이 없거나 유효하지 않을 때
*
* @example
* router.get('/profile', requireAuth, getProfile);
*/
const requireAuth = (req, res, next) => {
try {
const authHeader = req.headers['authorization'];
if (!authHeader) {
logger.warn('인증 실패: Authorization 헤더 없음', {
path: req.path,
method: req.method,
ip: req.ip
});
throw new AuthenticationError('Authorization 헤더가 필요합니다');
}
const token = authHeader.split(' ')[1];
if (!token) {
logger.warn('인증 실패: Bearer 토큰 누락', {
path: req.path,
method: req.method,
ip: req.ip
});
throw new AuthenticationError('Bearer 토큰이 필요합니다');
}
// JWT 검증
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
logger.debug('인증 성공', {
user_id: decoded.user_id || decoded.id,
username: decoded.username,
role: decoded.role,
access_level: decoded.access_level
});
next();
} catch (err) {
if (err.name === 'JsonWebTokenError') {
logger.warn('인증 실패: 유효하지 않은 토큰', {
error: err.message,
path: req.path,
ip: req.ip
});
throw new AuthenticationError('유효하지 않은 토큰입니다');
} else if (err.name === 'TokenExpiredError') {
logger.warn('인증 실패: 만료된 토큰', {
error: err.message,
path: req.path,
ip: req.ip
});
throw new AuthenticationError('토큰이 만료되었습니다');
} else if (err instanceof AuthenticationError) {
// 이미 AuthenticationError인 경우 그대로 throw
throw err;
} else {
logger.error('인증 처리 중 예상치 못한 오류', {
error: err.message,
stack: err.stack
});
throw new AuthenticationError('인증 처리 중 오류가 발생했습니다');
}
}
};
/**
* 특정 역할(들) 권한 체크 미들웨어
*
* 사용자가 지정된 역할 중 하나를 가지고 있는지 확인합니다.
* requireAuth 미들웨어가 먼저 실행되어야 합니다.
*
* @param {...string} roles - 허용할 역할 목록
* @returns {Function} Express 미들웨어 함수
* @throws {AuthenticationError} 인증되지 않은 경우
* @throws {ForbiddenError} 권한이 없는 경우
*
* @example
* // 단일 역할
* router.post('/admin/users', requireAuth, requireRole('admin'), createUser);
*
* // 여러 역할
* router.get('/reports', requireAuth, requireRole('admin', 'support_team'), getReports);
*/
const requireRole = (...roles) => {
return (req, res, next) => {
try {
if (!req.user) {
logger.warn('권한 체크 실패: 인증되지 않은 요청', {
path: req.path,
method: req.method,
ip: req.ip
});
throw new AuthenticationError('인증이 필요합니다');
}
const userRole = req.user.role;
const userRoleLower = userRole ? userRole.toLowerCase() : '';
const rolesLower = roles.map(r => r.toLowerCase());
if (!rolesLower.includes(userRoleLower)) {
logger.warn('권한 체크 실패: 역할 불일치', {
user_id: req.user.user_id || req.user.id,
username: req.user.username,
current_role: userRole,
required_roles: roles,
path: req.path
});
throw new ForbiddenError(
`이 기능을 사용하려면 ${roles.join(' 또는 ')} 권한이 필요합니다`
);
}
logger.debug('역할 권한 확인 성공', {
user_id: req.user.user_id || req.user.id,
username: req.user.username,
role: userRole,
required_roles: roles
});
next();
} catch (err) {
next(err);
}
};
};
/**
* 최소 권한 레벨 체크 미들웨어 (계층적)
*
* 사용자가 요구되는 최소 권한 레벨 이상인지 확인합니다.
* worker(1) < group_leader(2) < support_team(3) < admin(4) < system(5)
* requireAuth 미들웨어가 먼저 실행되어야 합니다.
*
* @param {string} minLevel - 최소 권한 레벨 (worker, group_leader, support_team, admin, system)
* @returns {Function} Express 미들웨어 함수
* @throws {AuthenticationError} 인증되지 않은 경우
* @throws {ForbiddenError} 권한이 부족한 경우
*
* @example
* // admin 이상 필요 (admin, system만 허용)
* router.delete('/users/:id', requireAuth, requireMinLevel('admin'), deleteUser);
*
* // group_leader 이상 필요 (group_leader, support_team, admin, system 허용)
* router.get('/team-reports', requireAuth, requireMinLevel('group_leader'), getTeamReports);
*/
const requireMinLevel = (minLevel) => {
return (req, res, next) => {
try {
if (!req.user) {
logger.warn('권한 레벨 체크 실패: 인증되지 않은 요청', {
path: req.path,
method: req.method,
ip: req.ip
});
throw new AuthenticationError('인증이 필요합니다');
}
const userLevel = ACCESS_LEVELS[req.user.access_level] || 0;
const requiredLevel = ACCESS_LEVELS[minLevel] || 999;
if (userLevel < requiredLevel) {
logger.warn('권한 레벨 체크 실패: 권한 부족', {
user_id: req.user.user_id || req.user.id,
username: req.user.username,
current_level: req.user.access_level,
current_level_value: userLevel,
required_level: minLevel,
required_level_value: requiredLevel,
path: req.path
});
throw new ForbiddenError(
`이 기능을 사용하려면 ${minLevel} 이상의 권한이 필요합니다 (현재: ${req.user.access_level})`
);
}
logger.debug('권한 레벨 확인 성공', {
user_id: req.user.user_id || req.user.id,
username: req.user.username,
access_level: req.user.access_level,
required_level: minLevel
});
next();
} catch (err) {
next(err);
}
};
};
/**
* 리소스 소유자 또는 관리자 권한 체크 미들웨어
*
* 요청한 사용자가 리소스의 소유자이거나 관리자 권한이 있는지 확인합니다.
* requireAuth 미들웨어가 먼저 실행되어야 합니다.
*
* @param {Object} options - 옵션 객체
* @param {string} options.resourceField - 리소스 ID를 가져올 req 필드 (예: 'params.user_id', 'body.worker_id')
* @param {string} options.userField - 사용자 ID 필드명 (기본값: 'user_id', 'id'도 자동 시도)
* @param {string[]} options.adminRoles - 관리자로 인정할 역할들 (기본값: ['admin', 'system'])
* @returns {Function} Express 미들웨어 함수
* @throws {AuthenticationError} 인증되지 않은 경우
* @throws {ForbiddenError} 소유자도 아니고 관리자도 아닌 경우
*
* @example
* // URL 파라미터의 user_id로 체크
* router.put('/users/:user_id', requireAuth, requireOwnerOrAdmin({
* resourceField: 'params.user_id'
* }), updateUser);
*
* // 요청 body의 worker_id로 체크, support_team도 관리자로 인정
* router.delete('/reports/:id', requireAuth, requireOwnerOrAdmin({
* resourceField: 'body.worker_id',
* adminRoles: ['admin', 'system', 'support_team']
* }), deleteReport);
*/
const requireOwnerOrAdmin = (options = {}) => {
const {
resourceField = 'params.id',
userField = 'user_id',
adminRoles = ['admin', 'system']
} = options;
return (req, res, next) => {
try {
if (!req.user) {
logger.warn('소유자/관리자 체크 실패: 인증되지 않은 요청', {
path: req.path,
method: req.method,
ip: req.ip
});
throw new AuthenticationError('인증이 필요합니다');
}
// 관리자 권한 체크
const userRole = req.user.role;
const isAdmin = adminRoles.includes(userRole);
if (isAdmin) {
logger.debug('관리자 권한으로 접근 허용', {
user_id: req.user.user_id || req.user.id,
username: req.user.username,
role: userRole,
path: req.path
});
return next();
}
// 리소스 ID 추출
const fieldParts = resourceField.split('.');
let resourceId = req;
for (const part of fieldParts) {
resourceId = resourceId[part];
if (resourceId === undefined) break;
}
// 사용자 ID (user_id 또는 id)
const userId = req.user[userField] || req.user.id || req.user.user_id;
// 소유자 체크
const isOwner = resourceId && String(resourceId) === String(userId);
if (!isOwner) {
logger.warn('소유자/관리자 체크 실패: 권한 부족', {
user_id: userId,
username: req.user.username,
role: userRole,
resource_id: resourceId,
resource_field: resourceField,
is_admin: isAdmin,
is_owner: isOwner,
path: req.path
});
throw new ForbiddenError('본인의 리소스이거나 관리자 권한이 필요합니다');
}
logger.debug('리소스 소유자로 접근 허용', {
user_id: userId,
username: req.user.username,
resource_id: resourceId,
path: req.path
});
next();
} catch (err) {
next(err);
}
};
};
/**
* 레거시 호환성을 위한 별칭
* @deprecated requireAuth를 사용하세요
*/
const verifyToken = requireAuth;
/**
* 레거시 호환성을 위한 별칭
* @deprecated requireRole('admin', 'system')을 사용하세요
*/
const requireAdmin = requireRole('admin', 'system');
/**
* 레거시 호환성을 위한 별칭
* @deprecated requireRole('system')을 사용하세요
*/
const requireSystem = requireRole('system');
module.exports = {
// 주요 미들웨어
requireAuth,
requireRole,
requireMinLevel,
requireOwnerOrAdmin,
// 레거시 호환성
verifyToken,
requireAdmin,
requireSystem,
// 상수
ACCESS_LEVELS
};
module.exports = require('../shared/middleware/auth');

View File

@@ -1,186 +1 @@
/**
* 커스텀 에러 클래스
*
* 애플리케이션 전체에서 사용하는 표준화된 에러 클래스들
*
* @author TK-FB-Project
* @since 2025-12-11
*/
/**
* 기본 애플리케이션 에러 클래스
* 모든 커스텀 에러의 부모 클래스
*/
class AppError extends Error {
/**
* @param {string} message - 에러 메시지
* @param {number} statusCode - HTTP 상태 코드
* @param {string} code - 에러 코드 (예: 'VALIDATION_ERROR')
* @param {object} details - 추가 세부 정보
*/
constructor(message, statusCode = 500, code = 'INTERNAL_ERROR', details = null) {
super(message);
this.name = this.constructor.name;
this.statusCode = statusCode;
this.code = code;
this.details = details;
this.isOperational = true; // 운영 에러 (예상된 에러)
Error.captureStackTrace(this, this.constructor);
}
/**
* JSON 형태로 에러 정보 반환
*/
toJSON() {
return {
name: this.name,
message: this.message,
statusCode: this.statusCode,
code: this.code,
details: this.details
};
}
}
/**
* 검증 에러 (400 Bad Request)
* 입력값 검증 실패 시 사용
*/
class ValidationError extends AppError {
/**
* @param {string} message - 에러 메시지
* @param {object} details - 검증 실패 세부 정보
*/
constructor(message = '입력값이 올바르지 않습니다', details = null) {
super(message, 400, 'VALIDATION_ERROR', details);
}
}
/**
* 인증 에러 (401 Unauthorized)
* 인증이 필요하거나 인증 실패 시 사용
*/
class AuthenticationError extends AppError {
/**
* @param {string} message - 에러 메시지
*/
constructor(message = '인증이 필요합니다') {
super(message, 401, 'AUTHENTICATION_ERROR');
}
}
/**
* 권한 에러 (403 Forbidden)
* 권한이 부족할 때 사용
*/
class ForbiddenError extends AppError {
/**
* @param {string} message - 에러 메시지
*/
constructor(message = '권한이 없습니다') {
super(message, 403, 'FORBIDDEN');
}
}
/**
* 리소스 없음 에러 (404 Not Found)
* 요청한 리소스를 찾을 수 없을 때 사용
*/
class NotFoundError extends AppError {
/**
* @param {string} message - 에러 메시지
* @param {string} resource - 찾을 수 없는 리소스명
*/
constructor(message = '리소스를 찾을 수 없습니다', resource = null) {
super(message, 404, 'NOT_FOUND', resource ? { resource } : null);
}
}
/**
* 충돌 에러 (409 Conflict)
* 중복된 리소스 등 충돌 발생 시 사용
*/
class ConflictError extends AppError {
/**
* @param {string} message - 에러 메시지
* @param {object} details - 충돌 세부 정보
*/
constructor(message = '이미 존재하는 데이터입니다', details = null) {
super(message, 409, 'CONFLICT', details);
}
}
/**
* 서버 에러 (500 Internal Server Error)
* 예상하지 못한 서버 오류 시 사용
*/
class InternalServerError extends AppError {
/**
* @param {string} message - 에러 메시지
*/
constructor(message = '서버 오류가 발생했습니다') {
super(message, 500, 'INTERNAL_SERVER_ERROR');
}
}
/**
* 데이터베이스 에러 (500 Internal Server Error)
* DB 관련 오류 시 사용
*/
class DatabaseError extends AppError {
/**
* @param {string} message - 에러 메시지
* @param {Error} originalError - 원본 DB 에러
*/
constructor(message = '데이터베이스 오류가 발생했습니다', originalError = null) {
super(
message,
500,
'DATABASE_ERROR',
originalError ? { originalMessage: originalError.message } : null
);
this.originalError = originalError;
}
}
/**
* 외부 API 에러 (502 Bad Gateway)
* 외부 서비스 호출 실패 시 사용
*/
class ExternalApiError extends AppError {
/**
* @param {string} message - 에러 메시지
* @param {string} service - 외부 서비스명
*/
constructor(message = '외부 서비스 호출에 실패했습니다', service = null) {
super(message, 502, 'EXTERNAL_API_ERROR', service ? { service } : null);
}
}
/**
* 타임아웃 에러 (504 Gateway Timeout)
* 요청 처리 시간 초과 시 사용
*/
class TimeoutError extends AppError {
/**
* @param {string} message - 에러 메시지
* @param {number} timeout - 타임아웃 시간 (ms)
*/
constructor(message = '요청 처리 시간이 초과되었습니다', timeout = null) {
super(message, 504, 'TIMEOUT_ERROR', timeout ? { timeout } : null);
}
}
module.exports = {
AppError,
ValidationError,
AuthenticationError,
ForbiddenError,
NotFoundError,
ConflictError,
InternalServerError,
DatabaseError,
ExternalApiError,
TimeoutError
};
module.exports = require('../shared/utils/errors');

View File

@@ -1,197 +1 @@
/**
* 로깅 유틸리티
*
* 애플리케이션 전체에서 사용하는 통합 로거
*
* @author TK-FB-Project
* @since 2025-12-11
*/
const fs = require('fs');
const path = require('path');
/**
* 로그 레벨 정의
*/
const LogLevel = {
ERROR: 'ERROR',
WARN: 'WARN',
INFO: 'INFO',
DEBUG: 'DEBUG'
};
/**
* 로그 레벨별 이모지
*/
const LogEmoji = {
ERROR: '❌',
WARN: '⚠️',
INFO: '',
DEBUG: '🔍'
};
/**
* 로그 레벨별 색상 (콘솔)
*/
const LogColor = {
ERROR: '\x1b[31m', // Red
WARN: '\x1b[33m', // Yellow
INFO: '\x1b[36m', // Cyan
DEBUG: '\x1b[90m', // Gray
RESET: '\x1b[0m'
};
class Logger {
constructor() {
this.logDir = path.join(__dirname, '../logs');
this.logFile = path.join(this.logDir, 'app.log');
this.errorFile = path.join(this.logDir, 'error.log');
this.ensureLogDirectory();
}
/**
* 로그 디렉토리 생성
*/
ensureLogDirectory() {
if (!fs.existsSync(this.logDir)) {
fs.mkdirSync(this.logDir, { recursive: true });
}
}
/**
* 타임스탬프 생성
*/
getTimestamp() {
return new Date().toISOString();
}
/**
* 로그 포맷팅
*/
formatLog(level, message, context = {}) {
const timestamp = this.getTimestamp();
const emoji = LogEmoji[level] || '';
const contextStr = Object.keys(context).length > 0
? `\n Context: ${JSON.stringify(context, null, 2)}`
: '';
return `[${timestamp}] [${level}] ${emoji} ${message}${contextStr}`;
}
/**
* 콘솔에 컬러 로그 출력
*/
logToConsole(level, message, context = {}) {
const color = LogColor[level] || LogColor.RESET;
const formattedLog = this.formatLog(level, message, context);
if (level === LogLevel.ERROR) {
console.error(`${color}${formattedLog}${LogColor.RESET}`);
} else if (level === LogLevel.WARN) {
console.warn(`${color}${formattedLog}${LogColor.RESET}`);
} else {
console.log(`${color}${formattedLog}${LogColor.RESET}`);
}
}
/**
* 파일에 로그 기록
*/
logToFile(level, message, context = {}) {
const formattedLog = this.formatLog(level, message, context);
const logEntry = `${formattedLog}\n`;
try {
// 모든 로그를 app.log에 기록
fs.appendFileSync(this.logFile, logEntry, 'utf8');
// 에러는 error.log에도 기록
if (level === LogLevel.ERROR) {
fs.appendFileSync(this.errorFile, logEntry, 'utf8');
}
} catch (err) {
console.error('로그 파일 기록 실패:', err);
}
}
/**
* 로그 기록 메인 함수
*/
log(level, message, context = {}) {
// 개발 환경에서는 콘솔에 출력
if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV !== 'production') {
this.logToConsole(level, message, context);
}
// 프로덕션에서는 파일에만 기록
if (process.env.NODE_ENV === 'production') {
this.logToFile(level, message, context);
}
}
/**
* 에러 로그
*/
error(message, context = {}) {
this.log(LogLevel.ERROR, message, context);
}
/**
* 경고 로그
*/
warn(message, context = {}) {
this.log(LogLevel.WARN, message, context);
}
/**
* 정보 로그
*/
info(message, context = {}) {
this.log(LogLevel.INFO, message, context);
}
/**
* 디버그 로그
*/
debug(message, context = {}) {
// DEBUG 로그는 개발 환경에서만 출력
if (process.env.NODE_ENV === 'development') {
this.log(LogLevel.DEBUG, message, context);
}
}
/**
* HTTP 요청 로그
*/
http(method, url, statusCode, duration, user = 'anonymous') {
const level = statusCode >= 400 ? LogLevel.ERROR : LogLevel.INFO;
const message = `${method} ${url} - ${statusCode} (${duration}ms)`;
const context = {
method,
url,
statusCode,
duration,
user
};
this.log(level, message, context);
}
/**
* 데이터베이스 쿼리 로그
*/
query(sql, params = [], duration = 0) {
if (process.env.NODE_ENV === 'development') {
this.debug('DB Query', {
sql,
params,
duration: `${duration}ms`
});
}
}
}
// 싱글톤 인스턴스 생성 및 내보내기
const logger = new Logger();
module.exports = logger;
module.exports = require('../shared/utils/logger');

View File

@@ -1,63 +0,0 @@
// utils/notifyHelper.js — 공용 알림 헬퍼
// system1-factory의 내부 알림 API를 통해 DB 저장 + Push 전송
const http = require('http');
const NOTIFY_URL = 'http://system1-api:3005/api/notifications/internal';
const SERVICE_KEY = process.env.INTERNAL_SERVICE_KEY || '';
const notifyHelper = {
/**
* 알림 전송
* @param {Object} opts
* @param {string} opts.type - 알림 유형 (safety, maintenance, repair, system)
* @param {string} opts.title - 알림 제목
* @param {string} [opts.message] - 알림 내용
* @param {string} [opts.link_url] - 클릭 시 이동 URL
* @param {string} [opts.reference_type] - 연관 테이블명
* @param {number} [opts.reference_id] - 연관 레코드 ID
* @param {number} [opts.created_by] - 생성자 user_id
*/
async send(opts) {
try {
const body = JSON.stringify(opts);
const url = new URL(NOTIFY_URL);
return new Promise((resolve) => {
const req = http.request({
hostname: url.hostname,
port: url.port,
path: url.pathname,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Internal-Service-Key': SERVICE_KEY,
'Content-Length': Buffer.byteLength(body)
},
timeout: 5000
}, (res) => {
res.resume(); // drain
resolve(true);
});
req.on('error', (err) => {
console.error('[notifyHelper] 알림 전송 실패:', err.message);
resolve(false);
});
req.on('timeout', () => {
req.destroy();
console.error('[notifyHelper] 알림 전송 타임아웃');
resolve(false);
});
req.write(body);
req.end();
});
} catch (err) {
console.error('[notifyHelper] 알림 전송 오류:', err.message);
return false;
}
}
};
module.exports = notifyHelper;

View File

@@ -153,7 +153,7 @@ if ('serviceWorker' in navigator) {
window._loadNotificationBell = function() {
var h = window.location.hostname;
var s = document.createElement('script');
s.src = (h.includes('technicalkorea.net') ? 'https://tkds.technicalkorea.net' : window.location.protocol + '//' + h + ':30000') + '/shared/notification-bell.js?v=3';
s.src = (h.includes('technicalkorea.net') ? 'https://tkds.technicalkorea.net' : window.location.protocol + '//' + h + ':30000') + '/shared/notification-bell.js?v=4';
document.head.appendChild(s);
};

View File

@@ -630,7 +630,7 @@ async function submitReport() {
linkDiv.className = 'summary-actions';
if (isNonconformity) {
linkDiv.innerHTML = `
<button class="btn-submit" onclick="window.location.href='https://tkqc.technicalkorea.net'">📋 TKQC 수신함</button>
<button class="btn-submit" onclick="window.location.href=(location.hostname.includes('technicalkorea.net') ? 'https://tkqc.technicalkorea.net' : location.protocol + '//' + location.hostname + ':30280')">📋 TKQC 수신함</button>
<button class="btn-edit" onclick="window.location.reload()"> 새 신고</button>
`;
} else {

View File

@@ -401,7 +401,7 @@ class App {
_loadNotificationBell() {
var h = window.location.hostname;
var s = document.createElement('script');
s.src = (h.includes('technicalkorea.net') ? 'https://tkds.technicalkorea.net' : window.location.protocol + '//' + h + ':30000') + '/shared/notification-bell.js?v=3';
s.src = (h.includes('technicalkorea.net') ? 'https://tkds.technicalkorea.net' : window.location.protocol + '//' + h + ':30000') + '/shared/notification-bell.js?v=4';
document.head.appendChild(s);
}

View File

@@ -94,7 +94,7 @@ class AuthManager {
if (hostname.includes('technicalkorea.net')) {
return window.location.protocol + '//tkds.technicalkorea.net/dashboard?redirect=' + encodeURIComponent(window.location.href);
}
return window.location.protocol + '//' + hostname + ':30780/dashboard?redirect=' + encodeURIComponent(window.location.href);
return window.location.protocol + '//' + hostname + ':30000/dashboard?redirect=' + encodeURIComponent(window.location.href);
}
/**

View File

@@ -52,7 +52,7 @@ function renderBottomNav(activePage) {
{ icon: 'fa-chart-line', label: '현황판', href: '/m/dashboard.html', page: 'dashboard' },
{ icon: 'fa-inbox', label: '수신함', href: '/m/inbox.html', page: 'inbox' },
{ icon: 'fa-tasks', label: '관리함', href: '/m/management.html', page: 'management' },
{ icon: 'fa-bullhorn', label: '신고', href: 'https://tkreport.technicalkorea.net', page: 'report', external: true, highlight: true }
{ icon: 'fa-bullhorn', label: '신고', href: (location.hostname.includes('technicalkorea.net') ? 'https://tkreport.technicalkorea.net' : location.protocol + '//' + location.hostname + ':30180'), page: 'report', external: true, highlight: true }
];
items.forEach(function (item) {
var a = document.createElement('a');

View File

@@ -1,11 +1,13 @@
FROM node:18-alpine
WORKDIR /usr/src/app
COPY package*.json ./
# shared 모듈 복사
COPY shared/ ./shared/
COPY tkpurchase/api/package*.json ./
RUN npm install --omit=dev
COPY . .
COPY tkpurchase/api/ ./
RUN chown -R node:node /usr/src/app
USER node

View File

@@ -1,6 +1,6 @@
const dayLaborModel = require('../models/dayLaborModel');
const { getPool } = require('../models/partnerModel');
const notify = require('../utils/notifyHelper');
const notify = require('../shared/utils/notifyHelper');
// 일용직 요청 목록
async function list(req, res) {

View File

@@ -1,7 +1,7 @@
const workReportModel = require('../models/workReportModel');
const checkinModel = require('../models/checkinModel');
const ExcelJS = require('exceljs');
const notify = require('../utils/notifyHelper');
const notify = require('../shared/utils/notifyHelper');
// 작업보고 목록
async function list(req, res) {

View File

@@ -1,25 +1,8 @@
const jwt = require('jsonwebtoken');
const mysql = require('mysql2/promise');
const { getPool } = require('../shared/config/database');
const JWT_SECRET = process.env.SSO_JWT_SECRET;
let pool;
function getPool() {
if (!pool) {
pool = mysql.createPool({
host: process.env.DB_HOST || 'mariadb',
port: parseInt(process.env.DB_PORT) || 3306,
user: process.env.DB_USER || 'hyungi_user',
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME || 'hyungi',
waitForConnections: true,
connectionLimit: 5,
queueLimit: 0
});
}
return pool;
}
function extractToken(req) {
const authHeader = req.headers['authorization'];
if (authHeader && authHeader.startsWith('Bearer ')) {

View File

@@ -1,21 +1,4 @@
const mysql = require('mysql2/promise');
let pool;
function getPool() {
if (!pool) {
pool = mysql.createPool({
host: process.env.DB_HOST || 'mariadb',
port: parseInt(process.env.DB_PORT) || 3306,
user: process.env.DB_USER || 'hyungi_user',
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME || 'hyungi',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
}
return pool;
}
const { getPool } = require('../shared/config/database');
// ===== 협력업체 =====

View File

@@ -1,63 +0,0 @@
// utils/notifyHelper.js — 공용 알림 헬퍼
// system1-factory의 내부 알림 API를 통해 DB 저장 + Push 전송
const http = require('http');
const NOTIFY_URL = 'http://system1-api:3005/api/notifications/internal';
const SERVICE_KEY = process.env.INTERNAL_SERVICE_KEY || '';
const notifyHelper = {
/**
* 알림 전송
* @param {Object} opts
* @param {string} opts.type - 알림 유형 (safety, maintenance, repair, system)
* @param {string} opts.title - 알림 제목
* @param {string} [opts.message] - 알림 내용
* @param {string} [opts.link_url] - 클릭 시 이동 URL
* @param {string} [opts.reference_type] - 연관 테이블명
* @param {number} [opts.reference_id] - 연관 레코드 ID
* @param {number} [opts.created_by] - 생성자 user_id
*/
async send(opts) {
try {
const body = JSON.stringify(opts);
const url = new URL(NOTIFY_URL);
return new Promise((resolve) => {
const req = http.request({
hostname: url.hostname,
port: url.port,
path: url.pathname,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Internal-Service-Key': SERVICE_KEY,
'Content-Length': Buffer.byteLength(body)
},
timeout: 5000
}, (res) => {
res.resume(); // drain
resolve(true);
});
req.on('error', (err) => {
console.error('[notifyHelper] 알림 전송 실패:', err.message);
resolve(false);
});
req.on('timeout', () => {
req.destroy();
console.error('[notifyHelper] 알림 전송 타임아웃');
resolve(false);
});
req.write(body);
req.end();
});
} catch (err) {
console.error('[notifyHelper] 알림 전송 오류:', err.message);
return false;
}
}
};
module.exports = notifyHelper;

View File

@@ -195,7 +195,7 @@ function initAuth() {
/* ===== 알림 벨 ===== */
function _loadNotificationBell() {
const s = document.createElement('script');
s.src = (location.hostname.includes('technicalkorea.net') ? 'https://tkds.technicalkorea.net' : location.protocol + '//' + location.hostname + ':30000') + '/shared/notification-bell.js?v=3';
s.src = (location.hostname.includes('technicalkorea.net') ? 'https://tkds.technicalkorea.net' : location.protocol + '//' + location.hostname + ':30000') + '/shared/notification-bell.js?v=4';
document.head.appendChild(s);
}

View File

@@ -1,11 +1,20 @@
FROM node:18-alpine
WORKDIR /usr/src/app
COPY package*.json ./
# shared 모듈 복사
COPY shared/ ./shared/
COPY tksafety/api/package*.json ./
RUN npm install --omit=dev
COPY . .
COPY tksafety/api/ ./
RUN chown -R node:node /usr/src/app
USER node
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s --start-period=20s --retries=3 \
CMD node -e "require('http').get('http://localhost:3000/health', (res) => { process.exit(res.statusCode === 200 ? 0 : 1); })"
CMD ["node", "index.js"]

View File

@@ -1,5 +1,5 @@
const visitRequestModel = require('../models/visitRequestModel');
const notify = require('../utils/notifyHelper');
const notify = require('../shared/utils/notifyHelper');
// ==================== 출입 신청 관리 ====================

View File

@@ -1,25 +1,8 @@
const jwt = require('jsonwebtoken');
const mysql = require('mysql2/promise');
const { getPool } = require('../shared/config/database');
const JWT_SECRET = process.env.SSO_JWT_SECRET;
let pool;
function getPool() {
if (!pool) {
pool = mysql.createPool({
host: process.env.DB_HOST || 'mariadb',
port: parseInt(process.env.DB_PORT) || 3306,
user: process.env.DB_USER || 'hyungi_user',
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME || 'hyungi',
waitForConnections: true,
connectionLimit: 5,
queueLimit: 0
});
}
return pool;
}
function extractToken(req) {
const authHeader = req.headers['authorization'];
if (authHeader && authHeader.startsWith('Bearer ')) {

View File

@@ -1,21 +1,4 @@
const mysql = require('mysql2/promise');
let pool;
function getPool() {
if (!pool) {
pool = mysql.createPool({
host: process.env.DB_HOST || 'mariadb',
port: parseInt(process.env.DB_PORT) || 3306,
user: process.env.DB_USER || 'hyungi_user',
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME || 'hyungi',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
}
return pool;
}
const { getPool } = require('../shared/config/database');
async function findToday() {
const db = getPool();

View File

@@ -173,7 +173,7 @@ function initAuth() {
/* ===== 알림 벨 ===== */
function _loadNotificationBell() {
const s = document.createElement('script');
s.src = (location.hostname.includes('technicalkorea.net') ? 'https://tkds.technicalkorea.net' : location.protocol + '//' + location.hostname + ':30000') + '/shared/notification-bell.js?v=3';
s.src = (location.hostname.includes('technicalkorea.net') ? 'https://tkds.technicalkorea.net' : location.protocol + '//' + location.hostname + ':30000') + '/shared/notification-bell.js?v=4';
document.head.appendChild(s);
}

View File

@@ -1,11 +1,20 @@
FROM node:18-alpine
WORKDIR /usr/src/app
COPY package*.json ./
# shared 모듈 복사
COPY shared/ ./shared/
COPY tksupport/api/package*.json ./
RUN npm install --omit=dev
COPY . .
COPY tksupport/api/ ./
RUN chown -R node:node /usr/src/app
USER node
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s --start-period=20s --retries=3 \
CMD node -e "require('http').get('http://localhost:3000/health', (res) => { process.exit(res.statusCode === 200 ? 0 : 1); })"
CMD ["node", "index.js"]

View File

@@ -1,25 +1,8 @@
const jwt = require('jsonwebtoken');
const mysql = require('mysql2/promise');
const { getPool } = require('../shared/config/database');
const JWT_SECRET = process.env.SSO_JWT_SECRET;
let pool;
function getPool() {
if (!pool) {
pool = mysql.createPool({
host: process.env.DB_HOST || 'mariadb',
port: parseInt(process.env.DB_PORT) || 3306,
user: process.env.DB_USER || 'hyungi_user',
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME || 'hyungi',
waitForConnections: true,
connectionLimit: 5,
queueLimit: 0
});
}
return pool;
}
function extractToken(req) {
const authHeader = req.headers['authorization'];
if (authHeader && authHeader.startsWith('Bearer ')) {

View File

@@ -164,7 +164,7 @@ function initAuth() {
/* ===== 알림 벨 ===== */
function _loadNotificationBell() {
const s = document.createElement('script');
s.src = (location.hostname.includes('technicalkorea.net') ? 'https://tkds.technicalkorea.net' : location.protocol + '//' + location.hostname + ':30000') + '/shared/notification-bell.js?v=3';
s.src = (location.hostname.includes('technicalkorea.net') ? 'https://tkds.technicalkorea.net' : location.protocol + '//' + location.hostname + ':30000') + '/shared/notification-bell.js?v=4';
document.head.appendChild(s);
}

View File

@@ -1,11 +1,13 @@
FROM node:18-alpine
WORKDIR /usr/src/app
COPY package*.json ./
# shared 모듈 복사
COPY shared/ ./shared/
COPY user-management/api/package*.json ./
RUN npm install --omit=dev
COPY . .
COPY user-management/api/ ./
RUN mkdir -p /usr/src/app/uploads/consumables && \
chown -R node:node /usr/src/app

View File

@@ -21,6 +21,8 @@ const partnerRoutes = require('./routes/partnerRoutes');
const vendorRoutes = require('./routes/vendorRoutes');
const consumableItemRoutes = require('./routes/consumableItemRoutes');
const notificationRecipientRoutes = require('./routes/notificationRecipientRoutes');
const notificationRoutes = require('./routes/notificationRoutes');
const pushSubscriptionRoutes = require('./routes/pushSubscriptionRoutes');
const app = express();
const PORT = process.env.PORT || 3000;
@@ -31,6 +33,8 @@ const allowedOrigins = [
'https://tkqc.technicalkorea.net',
'https://tkuser.technicalkorea.net',
'https://tkpurchase.technicalkorea.net',
'https://tksafety.technicalkorea.net',
'https://tksupport.technicalkorea.net',
];
if (process.env.NODE_ENV === 'development') {
allowedOrigins.push('http://localhost:30080', 'http://localhost:30180', 'http://localhost:30280');
@@ -64,6 +68,8 @@ app.use('/api/partners', partnerRoutes);
app.use('/api/vendors', vendorRoutes);
app.use('/api/consumable-items', consumableItemRoutes);
app.use('/api/notification-recipients', notificationRecipientRoutes);
app.use('/api/notifications', notificationRoutes);
app.use('/api/push', pushSubscriptionRoutes);
// 404
app.use((req, res) => {
@@ -83,4 +89,21 @@ app.listen(PORT, () => {
console.log(`tkuser-api running on port ${PORT}`);
});
// 오래된 알림 정리 cron (매일 03:00 KST)
(function scheduleNotificationCleanup() {
const notificationModel = require('./models/notificationModel');
function runCleanup() {
const now = new Date();
const kstHour = (now.getUTCHours() + 9) % 24;
if (kstHour === 3 && now.getMinutes() < 1) {
notificationModel.deleteOld(30).then(count => {
if (count > 0) console.log(`오래된 알림 ${count}건 정리 완료`);
}).catch(err => {
console.error('알림 정리 실패:', err.message);
});
}
}
setInterval(runCleanup, 60000);
})();
module.exports = app;

View File

@@ -76,4 +76,31 @@ function requireAdminOrPermission(pageName) {
};
}
module.exports = { extractToken, requireAuth, requireAdmin, requireAdminOrPermission };
/**
* 최소 권한 레벨 체크 미들웨어
* worker(1) < group_leader(2) < support_team(3) < admin(4) < system(5)
*/
const ACCESS_LEVELS = { worker: 1, group_leader: 2, support_team: 3, admin: 4, system: 5 };
function requireMinLevel(minLevel) {
return (req, res, next) => {
const token = extractToken(req);
if (!token) {
return res.status(401).json({ success: false, error: '인증이 필요합니다' });
}
try {
const decoded = jwt.verify(token, JWT_SECRET);
req.user = decoded;
const userLevel = ACCESS_LEVELS[decoded.access_level] || ACCESS_LEVELS[decoded.role] || 0;
const requiredLevel = ACCESS_LEVELS[minLevel] || 999;
if (userLevel < requiredLevel) {
return res.status(403).json({ success: false, error: `${minLevel} 이상의 권한이 필요합니다` });
}
next();
} catch {
return res.status(401).json({ success: false, error: '유효하지 않은 토큰입니다' });
}
};
}
module.exports = { extractToken, requireAuth, requireAdmin, requireAdminOrPermission, requireMinLevel };

View File

@@ -1,5 +1,5 @@
// models/notificationModel.js
const { getDb } = require('../dbPool');
const { getPool } = require('./userModel');
// Web Push (lazy init)
let webpush = null;
@@ -79,10 +79,9 @@ async function sendPushToUsers(userIds, payload) {
}
}
// 순환 참조를 피하기 위해 함수 내에서 require
async function getRecipientIds(notificationType) {
const db = await getDb();
const [rows] = await db.query(
const pool = getPool();
const [rows] = await pool.query(
`SELECT user_id FROM notification_recipients
WHERE notification_type = ? AND is_active = 1`,
[notificationType]
@@ -93,16 +92,15 @@ async function getRecipientIds(notificationType) {
const notificationModel = {
// 알림 생성
async create(notificationData) {
const db = await getDb();
const pool = getPool();
const { user_id, type, title, message, link_url, reference_type, reference_id, created_by } = notificationData;
const [result] = await db.query(
const [result] = await pool.query(
`INSERT INTO notifications (user_id, type, title, message, link_url, reference_type, reference_id, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
[user_id || null, type || 'system', title, message || null, link_url || null, reference_type || null, reference_id || null, created_by || null]
);
// Redis 캐시 무효화
this._invalidateCache(user_id);
return result.insertId;
@@ -110,8 +108,8 @@ const notificationModel = {
// 읽지 않은 알림 조회 (특정 사용자 또는 전체)
async getUnread(userId = null) {
const db = await getDb();
const [rows] = await db.query(
const pool = getPool();
const [rows] = await pool.query(
`SELECT * FROM notifications
WHERE is_read = 0
AND (user_id IS NULL OR user_id = ?)
@@ -124,10 +122,10 @@ const notificationModel = {
// 전체 알림 조회 (페이징)
async getAll(userId = null, page = 1, limit = 20) {
const db = await getDb();
const pool = getPool();
const offset = (page - 1) * limit;
const [rows] = await db.query(
const [rows] = await pool.query(
`SELECT * FROM notifications
WHERE (user_id IS NULL OR user_id = ?)
ORDER BY created_at DESC
@@ -135,7 +133,7 @@ const notificationModel = {
[userId || 0, limit, offset]
);
const [[{ total }]] = await db.query(
const [[{ total }]] = await pool.query(
`SELECT COUNT(*) as total FROM notifications
WHERE (user_id IS NULL OR user_id = ?)`,
[userId || 0]
@@ -146,10 +144,9 @@ const notificationModel = {
// 알림 읽음 처리
async markAsRead(notificationId) {
const db = await getDb();
// 읽음 처리 전 user_id 조회 (캐시 무효화용)
const [[row]] = await db.query('SELECT user_id FROM notifications WHERE notification_id = ?', [notificationId]);
const [result] = await db.query(
const pool = getPool();
const [[row]] = await pool.query('SELECT user_id FROM notifications WHERE notification_id = ?', [notificationId]);
const [result] = await pool.query(
`UPDATE notifications SET is_read = 1, read_at = NOW() WHERE notification_id = ?`,
[notificationId]
);
@@ -159,8 +156,8 @@ const notificationModel = {
// 모든 알림 읽음 처리
async markAllAsRead(userId = null) {
const db = await getDb();
const [result] = await db.query(
const pool = getPool();
const [result] = await pool.query(
`UPDATE notifications SET is_read = 1, read_at = NOW()
WHERE is_read = 0 AND (user_id IS NULL OR user_id = ?)`,
[userId || 0]
@@ -171,8 +168,8 @@ const notificationModel = {
// 알림 삭제
async delete(notificationId) {
const db = await getDb();
const [result] = await db.query(
const pool = getPool();
const [result] = await pool.query(
`DELETE FROM notifications WHERE notification_id = ?`,
[notificationId]
);
@@ -181,8 +178,8 @@ const notificationModel = {
// 오래된 알림 삭제 (30일 이상)
async deleteOld(days = 30) {
const db = await getDb();
const [result] = await db.query(
const pool = getPool();
const [result] = await pool.query(
`DELETE FROM notifications WHERE created_at < DATE_SUB(NOW(), INTERVAL ? DAY)`,
[days]
);
@@ -198,8 +195,8 @@ const notificationModel = {
if (cached !== null && cached !== undefined) return cached;
} catch (e) { /* 무시 */ }
const db = await getDb();
const [[{ count }]] = await db.query(
const pool = getPool();
const [[{ count }]] = await pool.query(
`SELECT COUNT(*) as count FROM notifications
WHERE is_read = 0 AND (user_id IS NULL OR user_id = ?)`,
[userId || 0]
@@ -207,7 +204,7 @@ const notificationModel = {
try {
const cache = require('../utils/cache');
await cache.set(cacheKey, count, 30); // TTL 30초
await cache.set(cacheKey, count, 30);
} catch (e) { /* 무시 */ }
return count;
@@ -226,11 +223,9 @@ const notificationModel = {
async createRepairNotification(repairData) {
const { equipment_id, equipment_name, repair_type, request_id, created_by } = repairData;
// 수리 알림 수신자 목록 가져오기
const recipientIds = await getRecipientIds('repair');
if (recipientIds.length === 0) {
// 수신자가 지정되지 않은 경우 전체 알림 (user_id = null)
const id = await this.create({
type: 'repair',
title: `수리 신청: ${equipment_name || '설비'}`,
@@ -240,7 +235,6 @@ const notificationModel = {
reference_id: request_id,
created_by
});
// Push (broadcast)
sendPushToUsers([], {
title: `수리 신청: ${equipment_name || '설비'}`,
body: `${repair_type} 수리가 신청되었습니다.`,
@@ -249,7 +243,6 @@ const notificationModel = {
return id;
}
// 지정된 수신자 각각에게 알림 생성
const results = [];
for (const userId of recipientIds) {
const notificationId = await this.create({
@@ -265,7 +258,6 @@ const notificationModel = {
results.push(notificationId);
}
// Push 전송
sendPushToUsers(recipientIds, {
title: `수리 신청: ${equipment_name || '설비'}`,
body: `${repair_type} 수리가 신청되었습니다.`,
@@ -279,11 +271,9 @@ const notificationModel = {
async createTypedNotification(notificationData) {
const { type, title, message, link_url, reference_type, reference_id, created_by } = notificationData;
// 해당 유형의 수신자 목록 가져오기
const recipientIds = await getRecipientIds(type);
if (recipientIds.length === 0) {
// 수신자가 지정되지 않은 경우 전체 알림
const id = await this.create({
type,
title,
@@ -293,12 +283,10 @@ const notificationModel = {
reference_id,
created_by
});
// Push (broadcast)
sendPushToUsers([], { title, body: message || '', url: link_url || '/' });
return id;
}
// 지정된 수신자 각각에게 알림 생성
const results = [];
for (const userId of recipientIds) {
const notificationId = await this.create({
@@ -314,7 +302,6 @@ const notificationModel = {
results.push(notificationId);
}
// Push 전송
sendPushToUsers(recipientIds, { title, body: message || '', url: link_url || '/' });
return results;

View File

@@ -1,11 +1,11 @@
// models/pushSubscriptionModel.js
const { getDb } = require('../dbPool');
const { getPool } = require('./userModel');
const pushSubscriptionModel = {
async subscribe(userId, subscription) {
const db = await getDb();
const pool = getPool();
const { endpoint, keys } = subscription;
await db.query(
await pool.query(
`INSERT INTO push_subscriptions (user_id, endpoint, p256dh, auth)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE user_id = VALUES(user_id), p256dh = VALUES(p256dh), auth = VALUES(auth)`,
@@ -14,13 +14,13 @@ const pushSubscriptionModel = {
},
async unsubscribe(endpoint) {
const db = await getDb();
await db.query('DELETE FROM push_subscriptions WHERE endpoint = ?', [endpoint]);
const pool = getPool();
await pool.query('DELETE FROM push_subscriptions WHERE endpoint = ?', [endpoint]);
},
async getByUserId(userId) {
const db = await getDb();
const [rows] = await db.query(
const pool = getPool();
const [rows] = await pool.query(
'SELECT * FROM push_subscriptions WHERE user_id = ?',
[userId]
);
@@ -29,8 +29,8 @@ const pushSubscriptionModel = {
async getByUserIds(userIds) {
if (!userIds || userIds.length === 0) return [];
const db = await getDb();
const [rows] = await db.query(
const pool = getPool();
const [rows] = await pool.query(
'SELECT * FROM push_subscriptions WHERE user_id IN (?)',
[userIds]
);
@@ -38,22 +38,22 @@ const pushSubscriptionModel = {
},
async getAll() {
const db = await getDb();
const [rows] = await db.query('SELECT * FROM push_subscriptions');
const pool = getPool();
const [rows] = await pool.query('SELECT * FROM push_subscriptions');
return rows;
},
async deleteByEndpoint(endpoint) {
const db = await getDb();
await db.query('DELETE FROM push_subscriptions WHERE endpoint = ?', [endpoint]);
const pool = getPool();
await pool.query('DELETE FROM push_subscriptions WHERE endpoint = ?', [endpoint]);
},
// === ntfy 구독 관련 ===
async getNtfyUserIds(userIds) {
if (!userIds || userIds.length === 0) return [];
const db = await getDb();
const [rows] = await db.query(
const pool = getPool();
const [rows] = await pool.query(
'SELECT user_id FROM ntfy_subscriptions WHERE user_id IN (?)',
[userIds]
);
@@ -61,27 +61,27 @@ const pushSubscriptionModel = {
},
async getAllNtfyUserIds() {
const db = await getDb();
const [rows] = await db.query('SELECT user_id FROM ntfy_subscriptions');
const pool = getPool();
const [rows] = await pool.query('SELECT user_id FROM ntfy_subscriptions');
return rows.map(r => r.user_id);
},
async ntfySubscribe(userId) {
const db = await getDb();
await db.query(
const pool = getPool();
await pool.query(
'INSERT IGNORE INTO ntfy_subscriptions (user_id) VALUES (?)',
[userId]
);
},
async ntfyUnsubscribe(userId) {
const db = await getDb();
await db.query('DELETE FROM ntfy_subscriptions WHERE user_id = ?', [userId]);
const pool = getPool();
await pool.query('DELETE FROM ntfy_subscriptions WHERE user_id = ?', [userId]);
},
async isNtfySubscribed(userId) {
const db = await getDb();
const [rows] = await db.query(
const pool = getPool();
const [rows] = await pool.query(
'SELECT 1 FROM ntfy_subscriptions WHERE user_id = ? LIMIT 1',
[userId]
);

View File

@@ -5,28 +5,10 @@
* sso-auth-service/models/userModel.js 기반
*/
const mysql = require('mysql2/promise');
const { getPool } = require('../shared/config/database');
const bcrypt = require('bcrypt');
const crypto = require('crypto');
let pool;
function getPool() {
if (!pool) {
pool = mysql.createPool({
host: process.env.DB_HOST || 'mariadb',
port: parseInt(process.env.DB_PORT) || 3306,
user: process.env.DB_USER || 'hyungi_user',
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME || 'hyungi',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
}
return pool;
}
/**
* pbkdf2_sha256 해시 검증 (passlib 호환)
*/

View File

@@ -13,6 +13,8 @@
"express": "^4.18.2",
"jsonwebtoken": "^9.0.0",
"multer": "^1.4.5-lts.1",
"mysql2": "^3.14.1"
"mysql2": "^3.14.1",
"node-cache": "^5.1.2",
"web-push": "^3.6.7"
}
}

View File

@@ -2,7 +2,7 @@
const express = require('express');
const router = express.Router();
const notificationController = require('../controllers/notificationController');
const { requireAuth, requireMinLevel } = require('../middlewares/auth');
const { requireAuth, requireMinLevel } = require('../middleware/auth');
// 내부 서비스용 알림 생성 (X-Internal-Service-Key 인증, JWT 불필요)
router.post('/internal', notificationController.createInternal);

View File

@@ -2,7 +2,7 @@
const express = require('express');
const router = express.Router();
const pushController = require('../controllers/pushSubscriptionController');
const { requireAuth } = require('../middlewares/auth');
const { requireAuth } = require('../middleware/auth');
// VAPID 공개키 (인증 불필요)
router.get('/vapid-public-key', pushController.getVapidPublicKey);

View File

@@ -0,0 +1,39 @@
// utils/cache.js - NodeCache 기반 간소화 캐시
const NodeCache = require('node-cache');
const memoryCache = new NodeCache({
stdTTL: 600,
checkperiod: 120,
useClones: false
});
const get = async (key) => {
try {
return memoryCache.get(key) || null;
} catch (error) {
console.warn(`캐시 조회 오류 (${key}):`, error.message);
return null;
}
};
const set = async (key, value, ttl = 600) => {
try {
memoryCache.set(key, value, ttl);
return true;
} catch (error) {
console.warn(`캐시 저장 오류 (${key}):`, error.message);
return false;
}
};
const del = async (key) => {
try {
memoryCache.del(key);
return true;
} catch (error) {
console.warn(`캐시 삭제 오류 (${key}):`, error.message);
return false;
}
};
module.exports = { get, set, del };

View File

@@ -211,7 +211,7 @@ async function init() {
/* ===== 알림 벨 ===== */
function _loadNotificationBell() {
const s = document.createElement('script');
s.src = (location.hostname.includes('technicalkorea.net') ? 'https://tkds.technicalkorea.net' : location.protocol + '//' + location.hostname + ':30000') + '/shared/notification-bell.js?v=3';
s.src = (location.hostname.includes('technicalkorea.net') ? 'https://tkds.technicalkorea.net' : location.protocol + '//' + location.hostname + ':30000') + '/shared/notification-bell.js?v=4';
document.head.appendChild(s);
}