feat: แกไขสวน backend ใหเขากบ frontend
This commit is contained in:
@@ -2,60 +2,57 @@
|
||||
// -------------------
|
||||
// Node >= 18, Express 4/5 compatible
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import express from 'express';
|
||||
import cookieParser from 'cookie-parser';
|
||||
import cors from 'cors';
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import express from "express";
|
||||
import cookieParser from "cookie-parser";
|
||||
import cors from "cors";
|
||||
|
||||
import sql from './db/index.js';
|
||||
import healthRouter from './routes/health.js';
|
||||
import { authJwt } from './middleware/authJwt.js';
|
||||
import { loadPrincipalMw } from './middleware/loadPrincipal.js';
|
||||
import sql from "./db/index.js";
|
||||
import healthRouter from "./routes/health.js";
|
||||
import { authJwt } from "./middleware/authJwt.js";
|
||||
import { loadPrincipalMw } from "./middleware/loadPrincipal.js";
|
||||
|
||||
// ROUTES
|
||||
import authRoutes from './routes/auth.js';
|
||||
import lookupRoutes from './routes/lookup.js';
|
||||
import organizationsRoutes from './routes/organizations.js';
|
||||
import projectsRoutes from './routes/projects.js';
|
||||
import correspondencesRoutes from './routes/correspondences.js';
|
||||
import rfasRoutes from './routes/rfas.js';
|
||||
import drawingsRoutes from './routes/drawings.js';
|
||||
import transmittalsRoutes from './routes/transmittals.js';
|
||||
import contractsRoutes from './routes/contracts.js';
|
||||
import contractDwgRoutes from './routes/contract_dwg.js';
|
||||
import categoriesRoutes from './routes/categories.js';
|
||||
import volumesRoutes from './routes/volumes.js';
|
||||
import uploadsRoutes from './routes/uploads.js';
|
||||
import usersRoutes from './routes/users.js';
|
||||
import permissionsRoutes from './routes/permissions.js';
|
||||
|
||||
// import { requireAuth } from './middleware/requireAuth.js';
|
||||
import authRoutes from "./routes/auth.js";
|
||||
import lookupRoutes from "./routes/lookup.js";
|
||||
import organizationsRoutes from "./routes/organizations.js";
|
||||
import projectsRoutes from "./routes/projects.js";
|
||||
import correspondencesRoutes from "./routes/correspondences.js";
|
||||
import rfasRoutes from "./routes/rfas.js";
|
||||
import drawingsRoutes from "./routes/drawings.js";
|
||||
import transmittalsRoutes from "./routes/transmittals.js";
|
||||
import contractsRoutes from "./routes/contracts.js";
|
||||
import contractDwgRoutes from "./routes/contract_dwg.js";
|
||||
import categoriesRoutes from "./routes/categories.js";
|
||||
import volumesRoutes from "./routes/volumes.js";
|
||||
import uploadsRoutes from "./routes/uploads.js";
|
||||
import usersRoutes from "./routes/users.js";
|
||||
import permissionsRoutes from "./routes/permissions.js";
|
||||
|
||||
/* ==========================
|
||||
* CONFIG (ปรับค่านี้ได้)
|
||||
* CONFIG
|
||||
* ========================== */
|
||||
// const PORT = Number(process.env.PORT || 7001);
|
||||
const PORT = Number(process.env.PORT || 3001);
|
||||
const NODE_ENV = process.env.NODE_ENV || 'production';
|
||||
const NODE_ENV = process.env.NODE_ENV || "production";
|
||||
|
||||
// Origin ของ Frontend (ถ้ามี Nginx ด้านหน้า ให้ใช้โดเมน/พอร์ตของ Frontend)
|
||||
// Origin ของ Frontend (ตั้งผ่าน ENV ในแต่ละสภาพแวดล้อม; dev ใช้ localhost)
|
||||
const FRONTEND_ORIGIN = process.env.FRONTEND_ORIGIN || 'https://lcbp3.mycloudnas.com';
|
||||
// Origin ของ Frontend (ตั้งผ่าน ENV ต่อ environment; dev ใช้ localhost)
|
||||
const FRONTEND_ORIGIN =
|
||||
process.env.FRONTEND_ORIGIN || "https://lcbp3.np-dms.work";
|
||||
const ALLOW_ORIGINS = [
|
||||
'http://localhost:3000',
|
||||
'http://127.0.0.1:3000',
|
||||
"http://localhost:3000",
|
||||
"http://127.0.0.1:3000",
|
||||
FRONTEND_ORIGIN,
|
||||
].filter(Boolean);
|
||||
|
||||
// ที่เก็บ log ภายใน container ถูก bind ไปที่ /share/Container/dms/logs/backend
|
||||
const LOG_DIR = process.env.BACKEND_LOG_DIR || '/app/logs';
|
||||
const LOG_DIR = process.env.BACKEND_LOG_DIR || "/app/logs";
|
||||
|
||||
// สร้างโฟลเดอร์ log ถ้ายังไม่มี (แก้ปัญหา Permission denied ล่วงหน้า: ให้ host map เป็น 775 และ uid=100)
|
||||
// สร้างโฟลเดอร์ log ถ้ายังไม่มี
|
||||
try {
|
||||
if (!fs.existsSync(LOG_DIR)) fs.mkdirSync(LOG_DIR, { recursive: true });
|
||||
} catch (e) {
|
||||
console.warn('[WARN] Cannot ensure LOG_DIR:', LOG_DIR, e?.message);
|
||||
console.warn("[WARN] Cannot ensure LOG_DIR:", LOG_DIR, e?.message);
|
||||
}
|
||||
|
||||
/* ==========================
|
||||
@@ -63,34 +60,41 @@ try {
|
||||
* ========================== */
|
||||
const app = express();
|
||||
|
||||
// CORS แบบกำหนด origin ตามรายการที่อนุญาต + อนุญาต credentials
|
||||
app.use(cors({
|
||||
origin(origin, cb) {
|
||||
// อนุญาต server-to-server / curl ที่ไม่มี Origin
|
||||
if (!origin) return cb(null, true);
|
||||
return cb(null, ALLOW_ORIGINS.includes(origin));
|
||||
},
|
||||
credentials: true,
|
||||
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
|
||||
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
|
||||
exposedHeaders: ['Content-Disposition', 'Content-Length'],
|
||||
}));
|
||||
// จัดการ preflight ให้ครบ
|
||||
app.options('*', cors({
|
||||
origin(origin, cb) {
|
||||
if (!origin) return cb(null, true);
|
||||
return cb(null, ALLOW_ORIGINS.includes(origin));
|
||||
},
|
||||
credentials: true,
|
||||
}));
|
||||
// ✅ อยู่หลัง NPM/Reverse proxy → ให้ trust proxy เพื่อให้ cookie secure / proto ทำงานถูก
|
||||
app.set("trust proxy", 1);
|
||||
|
||||
// CORS แบบกำหนด origin ตามรายการที่อนุญาต + อนุญาต credentials (จำเป็นสำหรับ cookie)
|
||||
app.use(
|
||||
cors({
|
||||
origin(origin, cb) {
|
||||
if (!origin) return cb(null, true); // server-to-server / curl
|
||||
return cb(null, ALLOW_ORIGINS.includes(origin));
|
||||
},
|
||||
credentials: true,
|
||||
methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
|
||||
allowedHeaders: ["Content-Type", "Authorization", "X-Requested-With"],
|
||||
exposedHeaders: ["Content-Disposition", "Content-Length"],
|
||||
})
|
||||
);
|
||||
// preflight
|
||||
app.options(
|
||||
"*",
|
||||
cors({
|
||||
origin(origin, cb) {
|
||||
if (!origin) return cb(null, true);
|
||||
return cb(null, ALLOW_ORIGINS.includes(origin));
|
||||
},
|
||||
credentials: true,
|
||||
})
|
||||
);
|
||||
|
||||
app.use(cookieParser());
|
||||
|
||||
// Payload limits
|
||||
app.use(express.json({ limit: '10mb' }));
|
||||
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
|
||||
app.use(express.json({ limit: "10mb" }));
|
||||
app.use(express.urlencoded({ extended: true, limit: "10mb" }));
|
||||
|
||||
// Access log (ขั้นต่ำ): พิมพ์ลง stdout ให้ Docker เก็บ; ถ้าต้องการเขียนไฟล์ ให้เปลี่ยนเป็น fs.appendFileSync
|
||||
// Access log (ขั้นต่ำ)
|
||||
app.use((req, _res, next) => {
|
||||
console.log(`[REQ] ${req.method} ${req.originalUrl}`);
|
||||
next();
|
||||
@@ -99,75 +103,78 @@ app.use((req, _res, next) => {
|
||||
/* ==========================
|
||||
* HEALTH / READY / INFO
|
||||
* ========================== */
|
||||
app.get('/health', async (req, res) => {
|
||||
app.get("/health", async (req, res) => {
|
||||
try {
|
||||
const [[{ now }]] = await sql.query('SELECT NOW() AS now');
|
||||
return res.json({ status: 'ok', db: 'ok', now });
|
||||
const [[{ now }]] = await sql.query("SELECT NOW() AS now");
|
||||
return res.json({ status: "ok", db: "ok", now });
|
||||
} catch (e) {
|
||||
return res.status(500).json({ status: 'degraded', db: 'fail', error: e?.message });
|
||||
return res
|
||||
.status(500)
|
||||
.json({ status: "degraded", db: "fail", error: e?.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Kubernetes-style endpoints (ถ้าใช้)
|
||||
app.get('/livez', (req, res) => res.send('ok'));
|
||||
app.get('/readyz', async (req, res) => {
|
||||
app.get("/livez", (req, res) => res.send("ok"));
|
||||
app.get("/readyz", async (req, res) => {
|
||||
try {
|
||||
await sql.query('SELECT 1');
|
||||
res.send('ready');
|
||||
await sql.query("SELECT 1");
|
||||
res.send("ready");
|
||||
} catch {
|
||||
res.status(500).send('not-ready');
|
||||
res.status(500).send("not-ready");
|
||||
}
|
||||
});
|
||||
|
||||
// เวอร์ชัน/บิลด์ (เติมจาก ENV ถ้าต้องการ)
|
||||
app.get('/info', (req, res) => {
|
||||
app.get("/info", (req, res) => {
|
||||
res.json({
|
||||
name: 'dms-backend',
|
||||
name: "dms-backend",
|
||||
env: NODE_ENV,
|
||||
version: process.env.APP_VERSION || '0.5.0',
|
||||
version: process.env.APP_VERSION || "0.5.0",
|
||||
commit: process.env.GIT_COMMIT || undefined,
|
||||
});
|
||||
});
|
||||
|
||||
/* ==========================
|
||||
* PROTECTED API
|
||||
* ROUTES
|
||||
* ========================== */
|
||||
// ต้อง auth + principal ก่อนเข้าทุก /api/*
|
||||
app.use('/api', healthRouter);
|
||||
app.use('/api/auth', authRoutes); // login/refresh/logout (ไม่ต้องผ่าน authJwt ทั้งกลุ่ม)
|
||||
app.use('/api', authJwt(), loadPrincipalMw()); // จากนี้ต้องมี JWT + principal
|
||||
// /api/health (ถอดจาก healthRouter)
|
||||
app.use("/api", healthRouter);
|
||||
|
||||
app.use('/api/lookup', lookupRoutes);
|
||||
// โมดูลหลัก
|
||||
app.use('/api/organizations', organizationsRoutes);
|
||||
app.use('/api/projects', projectsRoutes);
|
||||
app.use('/api/correspondences', correspondencesRoutes);
|
||||
app.use('/api/rfas', rfasRoutes);
|
||||
app.use('/api/drawings', drawingsRoutes);
|
||||
app.use('/api/transmittals', transmittalsRoutes);
|
||||
app.use('/api/contracts', contractsRoutes);
|
||||
app.use('/api/contract-dwg', contractDwgRoutes);
|
||||
app.use('/api/categories', categoriesRoutes);
|
||||
app.use('/api/volumes', volumesRoutes);
|
||||
app.use('/api/uploads', uploadsRoutes);
|
||||
app.use('/api/users', usersRoutes);
|
||||
app.use('/api/permissions', permissionsRoutes);
|
||||
// ✅ auth กลุ่มนี้ "ไม่ต้อง" ผ่าน authJwt
|
||||
app.use("/api/auth", authRoutes);
|
||||
|
||||
// จากนี้ไป ทุก /api/* ต้องผ่าน JWT + principal
|
||||
app.use("/api", authJwt(), loadPrincipalMw());
|
||||
|
||||
app.use("/api/lookup", lookupRoutes);
|
||||
app.use("/api/organizations", organizationsRoutes);
|
||||
app.use("/api/projects", projectsRoutes);
|
||||
app.use("/api/correspondences", correspondencesRoutes);
|
||||
app.use("/api/rfas", rfasRoutes);
|
||||
app.use("/api/drawings", drawingsRoutes);
|
||||
app.use("/api/transmittals", transmittalsRoutes);
|
||||
app.use("/api/contracts", contractsRoutes);
|
||||
app.use("/api/contract-dwg", contractDwgRoutes);
|
||||
app.use("/api/categories", categoriesRoutes);
|
||||
app.use("/api/volumes", volumesRoutes);
|
||||
app.use("/api/uploads", uploadsRoutes);
|
||||
app.use("/api/users", usersRoutes);
|
||||
app.use("/api/permissions", permissionsRoutes);
|
||||
|
||||
/* ==========================
|
||||
* NOT FOUND & ERROR HANDLERS
|
||||
* ========================== */
|
||||
app.use((req, res) => {
|
||||
res.status(404).json({ error: 'NOT_FOUND', path: req.originalUrl });
|
||||
res.status(404).json({ error: "NOT_FOUND", path: req.originalUrl });
|
||||
});
|
||||
|
||||
// ต้องมี 4 พารามิเตอร์เพื่อเป็น error handler ใน Express
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
app.use((err, req, res, _next) => {
|
||||
console.error('[UNHANDLED ERROR]', err);
|
||||
console.error("[UNHANDLED ERROR]", err);
|
||||
const status = err?.status || 500;
|
||||
res.status(status).json({
|
||||
error: 'SERVER_ERROR',
|
||||
message: NODE_ENV === 'production' ? undefined : err?.message,
|
||||
error: "SERVER_ERROR",
|
||||
message: NODE_ENV === "production" ? undefined : err?.message,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -184,17 +191,18 @@ const server = app.listen(PORT, () => {
|
||||
async function shutdown(signal) {
|
||||
try {
|
||||
console.log(`[SHUTDOWN] ${signal} received`);
|
||||
await new Promise(resolve => server.close(resolve));
|
||||
try { await sql.end(); } catch {}
|
||||
console.log('[SHUTDOWN] complete');
|
||||
await new Promise((resolve) => server.close(resolve));
|
||||
try {
|
||||
await sql.end();
|
||||
} catch {}
|
||||
console.log("[SHUTDOWN] complete");
|
||||
process.exit(0);
|
||||
} catch (e) {
|
||||
console.error('[SHUTDOWN] error', e);
|
||||
console.error("[SHUTDOWN] error", e);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
||||
process.on('SIGINT', () => shutdown('SIGINT'));
|
||||
process.on("SIGTERM", () => shutdown("SIGTERM"));
|
||||
process.on("SIGINT", () => shutdown("SIGINT"));
|
||||
|
||||
export default app;
|
||||
|
||||
@@ -1,27 +1,30 @@
|
||||
// src/routes/admin.js
|
||||
import { Router } from 'express';
|
||||
import sequelize from '../db/index.js';
|
||||
import { requireAuth } from '../middleware/auth.js';
|
||||
import { requirePermission } from '../middleware/perm.js';
|
||||
|
||||
const router = Router();
|
||||
// src/routes/admin.js
|
||||
import { Router } from 'express';
|
||||
import os from 'node:os';
|
||||
import sql from '../db/index.js';
|
||||
import { requirePerm } from '../middleware/requirePerm.js';
|
||||
import PERM from '../config/permissions.js';
|
||||
import { Router } from "express";
|
||||
import os from "node:os";
|
||||
import { dbReady, sequelize, Role, Permission } from "../db/sequelize.js";
|
||||
import { requirePerm } from "../middleware/requirePerm.js";
|
||||
import PERM from "../config/permissions.js";
|
||||
|
||||
const r = Router();
|
||||
|
||||
// GET /api/admin/sysinfo → ต้องมี admin.read
|
||||
r.get('/sysinfo',
|
||||
requirePerm(PERM.admin.read, { scope: 'global' }),
|
||||
async (req, res) => {
|
||||
// แนะนำ: ensure DB connection once (กันเผลอเรียกก่อน DB พร้อม)
|
||||
await dbReady().catch((e) => {
|
||||
console.error("[admin] DB not ready:", e?.message);
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /api/admin/sysinfo
|
||||
* perm: admin.read (global)
|
||||
*/
|
||||
r.get(
|
||||
"/sysinfo",
|
||||
requirePerm(PERM.admin.read, { scope: "global" }),
|
||||
async (_req, res) => {
|
||||
try {
|
||||
const [[{ now }]] = await sql.query('SELECT NOW() AS now');
|
||||
// ping DB เบา ๆ
|
||||
await sequelize.query("SELECT 1");
|
||||
res.json({
|
||||
now,
|
||||
now: new Date().toISOString(),
|
||||
node: process.version,
|
||||
platform: os.platform(),
|
||||
arch: os.arch(),
|
||||
@@ -29,80 +32,97 @@ r.get('/sysinfo',
|
||||
uptime_sec: os.uptime(),
|
||||
loadavg: os.loadavg(),
|
||||
memory: { total: os.totalmem(), free: os.freemem() },
|
||||
env: { NODE_ENV: process.env.NODE_ENV, APP_VERSION: process.env.APP_VERSION },
|
||||
env: {
|
||||
NODE_ENV: process.env.NODE_ENV,
|
||||
APP_VERSION: process.env.APP_VERSION,
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
res.status(500).json({ error: 'SYSINFO_FAIL', message: e?.message });
|
||||
res.status(500).json({ error: "SYSINFO_FAIL", message: e?.message });
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// POST /api/admin/maintenance/reindex → ต้องมี admin.maintain
|
||||
r.post('/maintenance/reindex',
|
||||
requirePerm(PERM.admin.maintain, { scope: 'global' }),
|
||||
async (_req, res) => {
|
||||
// ตัวอย่าง: ANALYZE/OPTIMIZE ตารางสำคัญ (ปรับตามจริง)
|
||||
try {
|
||||
await sql.query('ANALYZE TABLE correspondences, rfas, drawings');
|
||||
res.json({ ok: 1 });
|
||||
} catch (e) {
|
||||
res.status(500).json({ error: 'MAINT_FAIL', message: e?.message });
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
export default r;
|
||||
|
||||
/**
|
||||
* GET /api/admin/perm-matrix
|
||||
* query:
|
||||
* format=md|json (default: md)
|
||||
*
|
||||
* ต้องมีสิทธิ์ ADMIN หรืออย่างน้อย CDWG_ADMIN/ALL (เปลี่ยนเป็นอะไรก็ได้ตามนโยบายคุณ)
|
||||
* POST /api/admin/maintenance/reindex
|
||||
* perm: admin.maintain (global)
|
||||
* หมายเหตุ: ปรับรายชื่อตารางตามโปรเจ็คจริงของคุณ
|
||||
*/
|
||||
router.get('/perm-matrix',
|
||||
requireAuth,
|
||||
// ใช้ ANY จากชุดสิทธิ์ด้านล่าง (คุณปรับให้เป็น ['ALL'] อย่างเดียวก็ได้)
|
||||
requirePermission(['ALL', 'CDWG_ADMIN'], { mode: 'any' }),
|
||||
r.post(
|
||||
"/maintenance/reindex",
|
||||
requirePerm(PERM.admin.maintain, { scope: "global" }),
|
||||
async (_req, res) => {
|
||||
try {
|
||||
// ตัวอย่าง ใช้ RAW ก็ได้เมื่อเหมาะสม
|
||||
await sequelize.query("ANALYZE TABLE correspondences, rfas, drawings");
|
||||
res.json({ ok: 1 });
|
||||
} catch (e) {
|
||||
res.status(500).json({ error: "MAINT_FAIL", message: e?.message });
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* GET /api/admin/perm-matrix?format=md|json
|
||||
* perm: admin.read (global)
|
||||
* ดึง Role -> Permissions ด้วย association ของ Sequelize
|
||||
*/
|
||||
r.get(
|
||||
"/perm-matrix",
|
||||
requirePerm(PERM.admin.read, { scope: "global" }),
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
const format = (req.query.format || 'md').toLowerCase();
|
||||
const format = String(req.query.format || "md").toLowerCase();
|
||||
|
||||
// ดึง Role → Permissions (global)
|
||||
const [rows] = await sequelize.query(`
|
||||
SELECT
|
||||
r.role_id,
|
||||
r.role_code,
|
||||
r.role_name,
|
||||
GROUP_CONCAT(DISTINCT p.perm_code ORDER BY p.perm_code SEPARATOR ', ') AS perm_codes
|
||||
FROM roles r
|
||||
LEFT JOIN role_permissions rp ON rp.role_id = r.role_id
|
||||
LEFT JOIN permissions p ON p.perm_id = rp.perm_id
|
||||
GROUP BY r.role_id, r.role_code, r.role_name
|
||||
ORDER BY r.role_code
|
||||
`);
|
||||
const roles = await Role.findAll({
|
||||
attributes: ["role_id", "role_code", "role_name"],
|
||||
include: [
|
||||
{
|
||||
model: Permission,
|
||||
attributes: ["perm_code"],
|
||||
through: { attributes: [] }, // ไม่ต้องข้อมูลตาราง join
|
||||
required: false,
|
||||
},
|
||||
],
|
||||
order: [["role_code", "ASC"]],
|
||||
logging: false,
|
||||
});
|
||||
|
||||
if (format === 'json') {
|
||||
return res.json({ roles: rows });
|
||||
if (format === "json") {
|
||||
const data = roles.map((r) => ({
|
||||
role_id: r.role_id,
|
||||
role_code: r.role_code,
|
||||
role_name: r.role_name,
|
||||
perm_codes: (r.Permissions || []).map((p) => p.perm_code).sort(),
|
||||
}));
|
||||
return res.json({ roles: data });
|
||||
}
|
||||
|
||||
// สร้าง Markdown
|
||||
// สร้าง Markdown table
|
||||
const lines = [];
|
||||
lines.push(`# Permission Matrix (Role → Permissions)`);
|
||||
lines.push(`_Generated at: ${new Date().toISOString()}_\n`);
|
||||
lines.push(`| # | Role Code | Role Name | Permissions |`);
|
||||
lines.push(`|---:|:---------|:----------|:------------|`);
|
||||
rows.forEach((r, idx) => {
|
||||
lines.push(`| ${idx + 1} | \`${r.role_code}\` | ${r.role_name || ''} | ${r.perm_codes || ''} |`);
|
||||
|
||||
roles.forEach((r, idx) => {
|
||||
const perms = (r.Permissions || [])
|
||||
.map((p) => p.perm_code)
|
||||
.sort()
|
||||
.join(", ");
|
||||
lines.push(
|
||||
`| ${idx + 1} | \`${r.role_code}\` | ${
|
||||
r.role_name || ""
|
||||
} | ${perms} |`
|
||||
);
|
||||
});
|
||||
|
||||
const md = lines.join('\n');
|
||||
res.setHeader('Content-Type', 'text/markdown; charset=utf-8');
|
||||
return res.send(md);
|
||||
res.setHeader("Content-Type", "text/markdown; charset=utf-8");
|
||||
return res.send(lines.join("\n"));
|
||||
} catch (e) {
|
||||
next(e);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
export default router;
|
||||
export default r;
|
||||
|
||||
@@ -1,114 +1,127 @@
|
||||
// src/routes/auth.js (ESM)
|
||||
import { Router } from 'express';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import sql from '../db/index.js';
|
||||
// src/routes/auth.js
|
||||
import { Router } from "express";
|
||||
import jwt from "jsonwebtoken";
|
||||
import sql from "../db/index.js";
|
||||
import crypto from "node:crypto"; // ถ้าต้องการ timingSafeEqual
|
||||
import bcrypt from "bcryptjs"; // ถ้า password_hash เป็น bcrypt (แนะนำ)
|
||||
|
||||
const r = Router();
|
||||
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'dev-access-secret';
|
||||
const REFRESH_SECRET = process.env.REFRESH_SECRET || 'dev-refresh-secret';
|
||||
const ACCESS_TTL = process.env.ACCESS_TTL || '30m'; // 30 นาที
|
||||
const REFRESH_TTL = process.env.REFRESH_TTL || '30d'; // 30 วัน
|
||||
// ตั้งค่า JWT (อย่าใช้ .env ในโปรดักชันของคุณ → ใส่ผ่าน docker-compose)
|
||||
const JWT_ACCESS_SECRET = process.env.JWT_ACCESS_SECRET || "dev-access-secret";
|
||||
const JWT_REFRESH_SECRET =
|
||||
process.env.JWT_REFRESH_SECRET || "dev-refresh-secret";
|
||||
const ACCESS_TTL_MS = 30 * 60 * 1000; // 30 นาที
|
||||
const REFRESH_TTL_MS = 30 * 24 * 60 * 60 * 1000; // 30 วัน
|
||||
|
||||
function cookieOpts(maxAge) {
|
||||
return {
|
||||
httpOnly: true,
|
||||
secure: true, // ใช้งานจริงหลัง HTTPS
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
maxAge,
|
||||
// domain: ".np-dms.work", // ถ้าต้องการใช้ข้าม subdomain ให้เปิด
|
||||
};
|
||||
}
|
||||
|
||||
function signAccessToken(user) {
|
||||
return jwt.sign(
|
||||
{ user_id: user.user_id, username: user.username },
|
||||
JWT_SECRET,
|
||||
{ expiresIn: ACCESS_TTL, issuer: 'dms-backend' }
|
||||
JWT_ACCESS_SECRET,
|
||||
{ expiresIn: "30m", issuer: "dms-backend" }
|
||||
);
|
||||
}
|
||||
|
||||
function signRefreshToken(user) {
|
||||
return jwt.sign(
|
||||
{ user_id: user.user_id, username: user.username, t: 'refresh' },
|
||||
REFRESH_SECRET,
|
||||
{ expiresIn: REFRESH_TTL, issuer: 'dms-backend' }
|
||||
);
|
||||
return jwt.sign({ user_id: user.user_id }, JWT_REFRESH_SECRET, {
|
||||
expiresIn: "30d",
|
||||
issuer: "dms-backend",
|
||||
});
|
||||
}
|
||||
|
||||
async function findUserByUsername(username) {
|
||||
const [[u]] = await sql.query(
|
||||
'SELECT user_id, username, password_hash, email, first_name, last_name FROM users WHERE username=?',
|
||||
const [rows] = await sql.query(
|
||||
"SELECT user_id, username, email, password_hash FROM users WHERE username=? LIMIT 1",
|
||||
[username]
|
||||
);
|
||||
return u || null;
|
||||
return rows?.[0] || null;
|
||||
}
|
||||
|
||||
// POST /api/auth/login
|
||||
r.post('/login', async (req, res) => {
|
||||
async function verifyPassword(plain, hash) {
|
||||
// ถ้าใช้ bcrypt:
|
||||
try {
|
||||
return await bcrypt.compare(plain, hash);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
// ถ้าระบบคุณใช้ hash แบบอื่น ให้สลับมาใช้วิธีที่ตรงกับของจริง
|
||||
}
|
||||
|
||||
r.post("/login", async (req, res) => {
|
||||
const { username, password } = req.body || {};
|
||||
if (!username || !password) {
|
||||
return res.status(400).json({ error: 'username and password required' });
|
||||
return res.status(400).json({ error: "USERNAME_PASSWORD_REQUIRED" });
|
||||
}
|
||||
|
||||
const user = await findUserByUsername(username);
|
||||
if (!user) return res.status(401).json({ error: 'INVALID_CREDENTIALS' });
|
||||
if (!user) return res.status(401).json({ error: "INVALID_CREDENTIALS" });
|
||||
|
||||
const ok = await bcrypt.compare(password, user.password_hash || '');
|
||||
if (!ok) return res.status(401).json({ error: 'INVALID_CREDENTIALS' });
|
||||
const ok = await verifyPassword(password, user.password_hash);
|
||||
if (!ok) return res.status(401).json({ error: "INVALID_CREDENTIALS" });
|
||||
|
||||
const access_token = signAccessToken(user);
|
||||
const refresh_token = signRefreshToken(user);
|
||||
res.json({
|
||||
token: access_token,
|
||||
refresh_token,
|
||||
const access = signAccessToken(user);
|
||||
const refresh = signRefreshToken(user);
|
||||
|
||||
res.cookie("access_token", access, cookieOpts(ACCESS_TTL_MS));
|
||||
res.cookie("refresh_token", refresh, cookieOpts(REFRESH_TTL_MS));
|
||||
|
||||
return res.json({
|
||||
ok: true,
|
||||
user: {
|
||||
user_id: user.user_id,
|
||||
username: user.username,
|
||||
email: user.email,
|
||||
first_name: user.first_name,
|
||||
last_name: user.last_name,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
// POST /api/auth/refresh
|
||||
r.post('/refresh', async (req, res) => {
|
||||
const { refresh_token } = req.body || {};
|
||||
if (!refresh_token) return res.status(400).json({ error: 'refresh_token required' });
|
||||
r.post("/refresh", async (req, res) => {
|
||||
const refresh = req.cookies?.refresh_token || req.body?.refresh_token;
|
||||
if (!refresh)
|
||||
return res.status(400).json({ error: "REFRESH_TOKEN_REQUIRED" });
|
||||
|
||||
try {
|
||||
const payload = jwt.verify(refresh_token, REFRESH_SECRET, { issuer: 'dms-backend' });
|
||||
if (payload.t !== 'refresh') throw new Error('bad token');
|
||||
const payload = jwt.verify(refresh, JWT_REFRESH_SECRET, {
|
||||
issuer: "dms-backend",
|
||||
});
|
||||
// TODO: (ถ้ามี) ตรวจ blacklist/rotation store ของ refresh token
|
||||
|
||||
// ยืนยันผู้ใช้ยังอยู่ในระบบ
|
||||
const [[user]] = await sql.query(
|
||||
'SELECT user_id, username FROM users WHERE user_id=?',
|
||||
// คืน user จากฐานข้อมูลจริงตาม payload.user_id
|
||||
const [rows] = await sql.query(
|
||||
"SELECT user_id, username, email FROM users WHERE user_id=? LIMIT 1",
|
||||
[payload.user_id]
|
||||
);
|
||||
if (!user) return res.status(401).json({ error: 'USER_NOT_FOUND' });
|
||||
const user = rows?.[0];
|
||||
if (!user) return res.status(401).json({ error: "USER_NOT_FOUND" });
|
||||
|
||||
const token = signAccessToken(user);
|
||||
const new_refresh = signRefreshToken(user); // rotation
|
||||
res.json({ token, refresh_token: new_refresh });
|
||||
// rotation: ออก access+refresh ใหม่
|
||||
const access = signAccessToken(user);
|
||||
const newRef = signRefreshToken(user);
|
||||
|
||||
res.cookie("access_token", access, cookieOpts(ACCESS_TTL_MS));
|
||||
res.cookie("refresh_token", newRef, cookieOpts(REFRESH_TTL_MS));
|
||||
return res.json({ ok: true });
|
||||
} catch (e) {
|
||||
return res.status(401).json({ error: 'INVALID_REFRESH', message: e?.message });
|
||||
return res.status(401).json({ error: "INVALID_REFRESH_TOKEN" });
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/auth/logout (stateless)
|
||||
r.post('/logout', (req, res) => {
|
||||
// หากต้องการ blacklist/whitelist refresh token ให้เพิ่มตารางและบันทึกที่นี่
|
||||
res.json({ ok: 1 });
|
||||
});
|
||||
|
||||
// POST /api/auth/change-password
|
||||
r.post('/change-password', async (req, res) => {
|
||||
const { username, old_password, new_password } = req.body || {};
|
||||
if (!username || !old_password || !new_password) {
|
||||
return res.status(400).json({ error: 'username, old_password, new_password required' });
|
||||
}
|
||||
const user = await findUserByUsername(username);
|
||||
if (!user) return res.status(404).json({ error: 'USER_NOT_FOUND' });
|
||||
|
||||
const ok = await bcrypt.compare(old_password, user.password_hash || '');
|
||||
if (!ok) return res.status(401).json({ error: 'INVALID_CREDENTIALS' });
|
||||
|
||||
const salt = await bcrypt.genSalt(10);
|
||||
const hash = await bcrypt.hash(new_password, salt);
|
||||
await sql.query('UPDATE users SET password_hash=? WHERE user_id=?', [hash, user.user_id]);
|
||||
res.json({ ok: 1 });
|
||||
r.post("/logout", (req, res) => {
|
||||
res.clearCookie("access_token", { path: "/" });
|
||||
res.clearCookie("refresh_token", { path: "/" });
|
||||
return res.json({ ok: true });
|
||||
});
|
||||
|
||||
export default r;
|
||||
// หมายเหตุ: คุณอาจเพิ่ม /register, /forgot-password, /reset-password ตามต้องการ
|
||||
// แต่ในโปรเจกต์นี้จะให้แอดมินสร้างบัญชีผู้ใช้ผ่าน /api/users แทน
|
||||
|
||||
@@ -1,19 +1,43 @@
|
||||
import { Router } from 'express';
|
||||
import { requireAuth, enrichRoles } from '../middleware/auth.js';
|
||||
// src/routes/auth_extras.js
|
||||
import jwt from "jsonwebtoken";
|
||||
|
||||
const r = Router();
|
||||
const JWT_ACCESS_SECRET = process.env.JWT_ACCESS_SECRET || "dev-access-secret";
|
||||
|
||||
r.get('/auth/me', requireAuth, enrichRoles, async (req, res) => {
|
||||
res.json({
|
||||
user_id: req.user?.user_id,
|
||||
username: req.user?.username,
|
||||
roles: req.user?.roles || []
|
||||
});
|
||||
});
|
||||
/**
|
||||
* ตรวจสอบ access_token จาก httpOnly cookie
|
||||
* ใช้เป็น middleware กับเส้นทางที่ต้องการป้องกันฝั่ง API (ซ้ำกับ authJwt เดิมได้ แต่ตัวนี้อ่านคุกกี้ตรง ๆ)
|
||||
*/
|
||||
export function requireAuth(req, res, next) {
|
||||
const token = req.cookies?.access_token;
|
||||
if (!token) return res.status(401).json({ error: "Unauthenticated" });
|
||||
|
||||
// Placeholder: client can simply drop tokens; provided for symmetry/logging hook
|
||||
r.post('/auth/logout', requireAuth, async (_req, res) => {
|
||||
res.json({ ok: true });
|
||||
});
|
||||
try {
|
||||
const payload = jwt.verify(token, JWT_ACCESS_SECRET, {
|
||||
issuer: "dms-backend",
|
||||
});
|
||||
req.user = {
|
||||
user_id: payload.user_id,
|
||||
username: payload.username,
|
||||
};
|
||||
return next();
|
||||
} catch (e) {
|
||||
return res.status(401).json({ error: "INVALID_TOKEN" });
|
||||
}
|
||||
}
|
||||
|
||||
export default r;
|
||||
/**
|
||||
* เฉพาะกรณีในอนาคต: ตรวจบทบาท/สิทธิ์ง่าย ๆ
|
||||
* ใช้หลัง requireAuth เช่น app.get('/api/admin/xxx', requireAuth, requireRole('Admin'), handler)
|
||||
*/
|
||||
export function requireRole(roleName) {
|
||||
return function (req, res, next) {
|
||||
// สมมติว่ามี req.principal.roles จาก middleware อื่น (เช่น loadPrincipalMw)
|
||||
const roles = req.principal?.roles || req.user?.roles || [];
|
||||
if (!Array.isArray(roles) || !roles.includes(roleName)) {
|
||||
return res.status(403).json({ error: "FORBIDDEN" });
|
||||
}
|
||||
next();
|
||||
};
|
||||
}
|
||||
// หมายเหตุ: ในโปรเจกต์นี้ เราใช้ requirePerm จาก src/middleware/requirePerm.js แทน
|
||||
// เพราะมีความยืดหยุ่นกว่า (ตรวจสิทธิ์เป็นรายรายการ และมี scope ด้วย)
|
||||
|
||||
33
frontend/app/(auth)/layout.jsx
Normal file
33
frontend/app/(auth)/layout.jsx
Normal file
@@ -0,0 +1,33 @@
|
||||
// frontend/app/(auth)/layout.jsx
|
||||
|
||||
export const metadata = {
|
||||
title: "Authentication | DMS",
|
||||
description:
|
||||
"Login and user authentication pages for Document Management System",
|
||||
};
|
||||
|
||||
export default function AuthLayout({ children }) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<body className="min-h-screen flex items-center justify-center bg-gradient-to-br from-sky-50 to-sky-100">
|
||||
<div className="w-full max-w-md rounded-2xl shadow-lg bg-white p-6">
|
||||
{/* Header */}
|
||||
<div className="mb-6 text-center">
|
||||
<h1 className="text-2xl font-bold text-sky-800">
|
||||
Document Management System
|
||||
</h1>
|
||||
<p className="text-sm text-sky-600">LCBP3 Project</p>
|
||||
</div>
|
||||
|
||||
{/* Main content (children = page.jsx ของ login/register) */}
|
||||
<main>{children}</main>
|
||||
|
||||
{/* Footer */}
|
||||
<div className="mt-6 text-center text-xs text-gray-500">
|
||||
© {new Date().getFullYear()} np-dms.work
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -1,89 +1,341 @@
|
||||
// frontend/app/(auth)/login/page.jsx
|
||||
"use client";
|
||||
import { useState } from "react";
|
||||
import { API_BASE } from "@/lib/api";
|
||||
|
||||
import { useMemo, useState } from "react";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
CardDescription,
|
||||
CardContent,
|
||||
CardFooter,
|
||||
} from "@/components/ui/card";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
|
||||
const IS_DEV = process.env.NODE_ENV !== "production";
|
||||
|
||||
// URL builder กันเคสซ้ำ /api
|
||||
function buildLoginUrl() {
|
||||
const base = (process.env.NEXT_PUBLIC_API_BASE || "").replace(/\/+$/, "");
|
||||
if (base.endsWith("/api")) return `${base}/auth/login`;
|
||||
return `${base}/api/auth/login`;
|
||||
}
|
||||
|
||||
// helper: parse response body เป็น json หรือ text
|
||||
async function parseBody(res) {
|
||||
const text = await res.text();
|
||||
try {
|
||||
return { raw: text, json: JSON.parse(text) };
|
||||
} catch {
|
||||
return { raw: text, json: null };
|
||||
}
|
||||
}
|
||||
|
||||
// สร้างข้อความ debug ที่พร้อม copy
|
||||
function stringifyDebug(debugInfo) {
|
||||
try {
|
||||
return JSON.stringify(debugInfo, null, 2);
|
||||
} catch {
|
||||
return String(debugInfo);
|
||||
}
|
||||
}
|
||||
|
||||
export default function LoginPage() {
|
||||
const router = useRouter();
|
||||
const search = useSearchParams();
|
||||
const redirectTo = search.get("from") || "/dashboard";
|
||||
|
||||
const [username, setUsername] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [err, setErr] = useState("");
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
// สำหรับ debug panel
|
||||
const [debugInfo, setDebugInfo] = useState(null);
|
||||
const [copyState, setCopyState] = useState({ copied: false, error: "" });
|
||||
|
||||
const loginUrl = useMemo(buildLoginUrl, [process.env.NEXT_PUBLIC_API_BASE]);
|
||||
|
||||
async function onSubmit(e) {
|
||||
e.preventDefault();
|
||||
setErr("");
|
||||
setIsLoading(true);
|
||||
setSubmitting(true);
|
||||
setError("");
|
||||
if (IS_DEV) {
|
||||
setDebugInfo(null);
|
||||
setCopyState({ copied: false, error: "" });
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/auth/login`, {
|
||||
const res = await fetch(loginUrl, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
credentials: "include",
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
if (!res.ok) {
|
||||
setErr(data.error || "เข้าสู่ระบบไม่สำเร็จ");
|
||||
return;
|
||||
const body = await parseBody(res);
|
||||
|
||||
const apiErr = {
|
||||
name: "ApiError",
|
||||
status: res.status,
|
||||
statusText: res.statusText,
|
||||
body: body.json ?? body.raw,
|
||||
message: (() => {
|
||||
const msgFromJson =
|
||||
(body.json && (body.json.error || body.json.message)) || null;
|
||||
|
||||
if (res.status === 400)
|
||||
return `Bad request: ${msgFromJson ?? res.statusText}`;
|
||||
if (res.status === 401)
|
||||
return `Unauthenticated: ${msgFromJson ?? "Invalid credentials"}`;
|
||||
if (res.status === 403)
|
||||
return `Forbidden: ${msgFromJson ?? res.statusText}`;
|
||||
if (res.status === 404)
|
||||
return `Not found: ${msgFromJson ?? res.statusText}`;
|
||||
if (res.status >= 500)
|
||||
return `Server error (${res.status}): ${
|
||||
msgFromJson ?? res.statusText
|
||||
}`;
|
||||
return `${res.status} ${res.statusText}: ${
|
||||
msgFromJson ?? "Request failed"
|
||||
}`;
|
||||
})(),
|
||||
};
|
||||
|
||||
if (IS_DEV) {
|
||||
setDebugInfo({
|
||||
kind: "api",
|
||||
request: {
|
||||
url: loginUrl,
|
||||
method: "POST",
|
||||
payload: { username: "(masked)", password: "(masked)" },
|
||||
},
|
||||
response: {
|
||||
status: res.status,
|
||||
statusText: res.statusText,
|
||||
body: apiErr.body,
|
||||
},
|
||||
env: {
|
||||
NEXT_PUBLIC_API_BASE:
|
||||
process.env.NEXT_PUBLIC_API_BASE || "(unset)",
|
||||
NODE_ENV: process.env.NODE_ENV,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
throw apiErr;
|
||||
}
|
||||
|
||||
if (data.token) {
|
||||
localStorage.setItem("token", data.token);
|
||||
localStorage.setItem("refresh_token", data.refresh_token);
|
||||
if (data.user) {
|
||||
localStorage.setItem("user", JSON.stringify(data.user));
|
||||
}
|
||||
location.href = "/dashboard";
|
||||
} else {
|
||||
setErr("ไม่ได้รับ Token");
|
||||
// ✅ สำเร็จ
|
||||
if (IS_DEV) {
|
||||
setDebugInfo({
|
||||
kind: "success",
|
||||
request: { url: loginUrl, method: "POST" },
|
||||
note: "Login success. Redirecting…",
|
||||
});
|
||||
}
|
||||
router.push(redirectTo);
|
||||
} catch (err) {
|
||||
if (err?.name === "ApiError") {
|
||||
setError(err.message);
|
||||
} else if (err instanceof TypeError && /fetch/i.test(err.message)) {
|
||||
setError(
|
||||
"Network error: ไม่สามารถเชื่อมต่อเซิร์ฟเวอร์ได้ (ตรวจสอบ proxy/NPM/SSL)"
|
||||
);
|
||||
if (IS_DEV) {
|
||||
setDebugInfo({
|
||||
kind: "network",
|
||||
request: { url: loginUrl, method: "POST" },
|
||||
error: { message: err.message },
|
||||
hint: "เช็คว่า NPM ชี้ proxy /api ไปที่ backend ถูก network/port, และ TLS chain ถูกต้อง",
|
||||
});
|
||||
}
|
||||
} else {
|
||||
setError(err?.message || "Unexpected error");
|
||||
if (IS_DEV) {
|
||||
setDebugInfo({
|
||||
kind: "unknown",
|
||||
request: { url: loginUrl, method: "POST" },
|
||||
error: { message: String(err) },
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Login failed:", error);
|
||||
setErr("เกิดข้อผิดพลาดในการเชื่อมต่อ");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCopyDebug() {
|
||||
if (!debugInfo) return;
|
||||
const text = stringifyDebug(debugInfo);
|
||||
try {
|
||||
if (navigator.clipboard?.writeText) {
|
||||
await navigator.clipboard.writeText(text);
|
||||
} else {
|
||||
// Fallback
|
||||
const ta = document.createElement("textarea");
|
||||
ta.value = text;
|
||||
ta.style.position = "fixed";
|
||||
ta.style.left = "-9999px";
|
||||
document.body.appendChild(ta);
|
||||
ta.focus();
|
||||
ta.select();
|
||||
document.execCommand("copy");
|
||||
document.body.removeChild(ta);
|
||||
}
|
||||
setCopyState({ copied: true, error: "" });
|
||||
setTimeout(() => setCopyState({ copied: false, error: "" }), 1500);
|
||||
} catch (e) {
|
||||
setCopyState({
|
||||
copied: false,
|
||||
error: "คัดลอกไม่สำเร็จ (permission ของ clipboard?)",
|
||||
});
|
||||
setTimeout(() => setCopyState({ copied: false, error: "" }), 2500);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className="grid min-h-screen place-items-center"
|
||||
style={{
|
||||
background: "linear-gradient(to bottom right, #00c6ff, #0072ff)",
|
||||
}}
|
||||
>
|
||||
<form
|
||||
onSubmit={onSubmit}
|
||||
className="w-full max-w-sm p-8 space-y-4 shadow-lg bg-white/20 backdrop-blur-md rounded-3xl"
|
||||
>
|
||||
<div className="text-2xl font-bold text-center text-white">
|
||||
เข้าสู่ระบบ
|
||||
</div>
|
||||
<input
|
||||
disabled={isLoading}
|
||||
className="w-full p-3 text-white placeholder-gray-200 border bg-white/30 border-white/30 rounded-xl focus:outline-none focus:ring-2 focus:ring-white/50 disabled:opacity-50"
|
||||
placeholder="ชื่อผู้ใช้"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
/>
|
||||
<input
|
||||
type="password"
|
||||
disabled={isLoading}
|
||||
className="w-full p-3 text-white placeholder-gray-200 border bg-white/30 border-white/30 rounded-xl focus:outline-none focus:ring-2 focus:ring-white/50 disabled:opacity-50"
|
||||
placeholder="รหัสผ่าน"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
/>
|
||||
{err && (
|
||||
<div className="text-sm text-center text-yellow-300">{err}</div>
|
||||
<Card className="mx-auto w-full max-w-md shadow-lg">
|
||||
<CardHeader className="space-y-1">
|
||||
<CardTitle className="text-2xl text-sky-800">Sign in</CardTitle>
|
||||
<CardDescription>
|
||||
Enter your credentials to access the DMS
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="space-y-4">
|
||||
{error ? (
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
) : null}
|
||||
|
||||
<form onSubmit={onSubmit} className="space-y-4">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="username">Username</Label>
|
||||
<Input
|
||||
id="username"
|
||||
autoComplete="username"
|
||||
placeholder="superadmin"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="password">Password</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
placeholder="••••••••"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Button type="submit" className="w-full" disabled={submitting}>
|
||||
{submitting ? "Signing in..." : "Sign in"}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{IS_DEV && (
|
||||
<div className="mt-4 rounded-xl border border-sky-200 bg-sky-50 p-3">
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<div className="text-sm font-semibold text-sky-900">
|
||||
Debug (dev mode only)
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
onClick={handleCopyDebug}
|
||||
disabled={!debugInfo}
|
||||
aria-label="Copy debug info"
|
||||
>
|
||||
{copyState.copied ? "Copied!" : "Copy debug"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<Separator className="my-2" />
|
||||
<div className="space-y-2 text-xs text-sky-900">
|
||||
<div>
|
||||
<span className="font-medium">Request URL:</span>{" "}
|
||||
<code className="break-all">{loginUrl}</code>
|
||||
</div>
|
||||
|
||||
{debugInfo?.request?.method && (
|
||||
<div>
|
||||
<span className="font-medium">Method:</span>{" "}
|
||||
<code>{debugInfo.request.method}</code>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{debugInfo?.response && (
|
||||
<>
|
||||
<div>
|
||||
<span className="font-medium">Status:</span>{" "}
|
||||
<code>
|
||||
{debugInfo.response.status}{" "}
|
||||
{debugInfo.response.statusText}
|
||||
</code>
|
||||
</div>
|
||||
<div className="font-medium">Response body:</div>
|
||||
<pre className="max-h-48 overflow-auto rounded bg-white p-2">
|
||||
{typeof debugInfo.response.body === "string"
|
||||
? debugInfo.response.body
|
||||
: JSON.stringify(debugInfo.response.body, null, 2)}
|
||||
</pre>
|
||||
</>
|
||||
)}
|
||||
|
||||
{debugInfo?.error && (
|
||||
<>
|
||||
<div className="font-medium">Error:</div>
|
||||
<pre className="max-h-48 overflow-auto rounded bg-white p-2">
|
||||
{JSON.stringify(debugInfo.error, null, 2)}
|
||||
</pre>
|
||||
</>
|
||||
)}
|
||||
|
||||
{debugInfo?.env && (
|
||||
<>
|
||||
<div className="font-medium">Env:</div>
|
||||
<pre className="max-h-40 overflow-auto rounded bg-white p-2">
|
||||
{JSON.stringify(debugInfo.env, null, 2)}
|
||||
</pre>
|
||||
</>
|
||||
)}
|
||||
|
||||
{debugInfo?.note && (
|
||||
<div className="italic text-sky-700">{debugInfo.note}</div>
|
||||
)}
|
||||
{debugInfo?.hint && (
|
||||
<div className="italic text-sky-700">
|
||||
Hint: {debugInfo.hint}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{copyState.error && (
|
||||
<div className="text-red-600">{copyState.error}</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading}
|
||||
className="w-full p-3 font-bold text-white transition-colors duration-300 bg-blue-500 rounded-xl hover:bg-blue-600 disabled:bg-blue-400 disabled:cursor-not-allowed"
|
||||
>
|
||||
{isLoading ? "กำลังเข้าสู่ระบบ..." : "เข้าสู่ระบบ"}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</CardContent>
|
||||
|
||||
<CardFooter className="justify-center text-xs text-gray-500">
|
||||
© {new Date().getFullYear()} np-dms.work
|
||||
</CardFooter>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,24 +1,34 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import type { NextRequest } from "next/server";
|
||||
|
||||
// ชื่อคุกกี้ให้ตรงกับ backend
|
||||
const COOKIE_NAME = "access_token";
|
||||
|
||||
export function middleware(req: NextRequest) {
|
||||
const protectedPaths = [
|
||||
"/dashboard","/drawings","/rfas","/transmittals","/correspondences",
|
||||
"/contracts-volumes","/users","/reports","/workflow","/health","/admin"
|
||||
];
|
||||
const { pathname } = req.nextUrl;
|
||||
const isProtected = protectedPaths.some(p => pathname.startsWith(p));
|
||||
if (!isProtected) return NextResponse.next();
|
||||
const hasToken = req.cookies.get("access_token");
|
||||
// ตรวจคุกกี้
|
||||
const hastoken = req.cookies.get(COOKIE_NAME)?.value;
|
||||
if (!hasToken) {
|
||||
const url = req.nextUrl.clone();
|
||||
url.pathname = "/login";
|
||||
return NextResponse.redirect(url);
|
||||
const loginUrl = new URL("/login", req.url);
|
||||
// จำเส้นทางเดิมไว้เพื่อเด้งกลับหลังล็อกอิน
|
||||
loginUrl.searchParams.set("from", pathname);
|
||||
return NextResponse.redirect(loginUrl);
|
||||
}
|
||||
return NextResponse.next();
|
||||
}
|
||||
|
||||
export const config = { matcher: [
|
||||
"/dashboard/:path*","/drawings/:path*","/rfas/:path*","/transmittals/:path*","/correspondences/:path*",
|
||||
"/contracts-volumes/:path*","/users/:path*","/reports/:path*","/workflow/:path*","/health/:path*","/admin/:path*"
|
||||
] };
|
||||
export const config = {
|
||||
matcher: [
|
||||
"/dashboard/:path*",
|
||||
"/drawings/:path*",
|
||||
"/rfas/:path*",
|
||||
"/transmittals/:path*",
|
||||
"/correspondences/:path*",
|
||||
"/contracts-volumes/:path*",
|
||||
"/users/:path*",
|
||||
"/reports/:path*",
|
||||
"/workflow/:path*",
|
||||
"/admin/:path*",
|
||||
],
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user