Back/index.js
seonkyu.kim 6a7fa38b96
All checks were successful
Stein_Back/pipeline/head This commit looks good
[] RT 서비스 연결 추가
2024-08-09 15:49:59 +09:00

140 lines
4.2 KiB
JavaScript
Executable File

import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import cors from 'cors';
import fetch from 'node-fetch';
import session from 'express-session'; // express-session 추가
import rtRoutes from './RT/app.js'; // ./RT/app.js에서 라우트를 가져옴
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const port = 7000;
// 세션 설정
app.use(session({
secret: 'your-secret-key', // 비밀 키
resave: false,
saveUninitialized: true,
cookie: { secure: false } // 개발 환경에서는 false, 프로덕션에서는 true
}));
app.use(cors());
app.use(express.json());
// app.use(express.urlencoded({ extended: true }));
// app.use(express.static(path.join(__dirname, 'public'))); // 정적 파일 제공 경로 설정
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, '..', 'front', 'login')));
let sessionId = ''; // 세션 ID를 저장할 변수
// ===== RT 설정 ===== //
app.use('/RT', rtRoutes);
// login
app.get('/login', (req, res) => {
res.sendFile(path.join(__dirname, '..', 'front', 'login', 'login.html'));
});
app.post('/login', async (req, res) => {
const { username, password } = req.body;
console.log('로그인 요청 수신:', { username, password });
const apiUrl = "https://admin.ipstein.myds.me/webapi/auth.cgi";
const params = new URLSearchParams({
api: 'SYNO.API.Auth',
version: '6',
method: 'login',
account: username,
passwd: password,
session: 'FileStation',
format: 'sid'
});
try {
const response = await fetch(`${apiUrl}?${params.toString()}`);
const text = await response.text();
console.log('API 응답 수신:', text);
const data = JSON.parse(text);
console.log('API 응답 데이터:', data);
if (data.success) {
req.session.isLoggedIn = true; // 로그인 성공 시 세션에 로그인 상태 저장
req.session.username = username; // 사용자의 이름을 세션에 저장
sessionId = data.data.sid; // 세션 ID 저장
res.json({ success: true });
} else {
console.error('로그인 실패:', data);
res.json({ success: false, error: data.error });
}
} catch (error) {
console.error('Error:', error);
res.status(500).json({ success: false });
}
});
// getGroups
app.get('/getGroups', async (req, res) => {
const { username } = req.query;
console.log('그룹 정보 요청 수신:', { username });
const apiUrl = "https://admin.ipstein.myds.me/webapi/entry.cgi";
const params = new URLSearchParams({
api: 'SYNO.Core.Group',
version: '1',
method: 'list',
additional: 'members',
_sid: sessionId // 세션 ID 추가
});
try {
const response = await fetch(`${apiUrl}?${params.toString()}`);
const text = await response.text();
console.log('그룹 API 응답 수신:', text);
const data = JSON.parse(text);
console.log('원본 그룹 데이터:', data); // 원본 데이터 로그 출력
if (data.success) {
res.json(data.data.groups); // 필터링 없이 원본 데이터를 반환
} else {
console.error('그룹 정보 조회 실패:', data);
res.json({ success: false, error: data.error });
}
} catch (error) {
console.error('Error:', error);
res.status(500).json({ success: false });
}
});
// 인증 미들웨어
function ensureAuthenticated(req, res, next) {
if (req.session.isLoggedIn) {
return next();
} else {
res.redirect('/'); // 로그인하지 않은 경우 루트 경로로 리다이렉트
}
}
// /admin 경로 보호
app.get('/admin', ensureAuthenticated, (req, res) => {
res.sendFile(path.join(__dirname, '..', 'front','admin.html'));
});
// 루트 경로로 접속했을 때 다른 도메인으로 리다이렉트
// 이렇게 해서 오버레이로 넘길 수 있게
app.get('/', (req, res) => {
res.redirect("https://ipstein.myds.me"); // 원하는 도메인으로 리다이렉트
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});