11import 'dotenv/config' ;
22import express from 'express' ;
3+ import session from 'express-session' ;
34import { fileURLToPath } from 'url' ;
45import { dirname , join } from 'path' ;
56import { getContainers , restartContainer , stopContainer , startContainer } from './services/docker.js' ;
67import { checkWebsites } from './services/http.js' ;
78
89const __dirname = dirname ( fileURLToPath ( import . meta. url ) ) ;
910
10- const PORT = process . env . PORT || 3000 ;
11- const BASE_URL = process . env . BASE_URL || `http://localhost:${ PORT } ` ;
11+ const PORT = process . env . PORT || 3000 ;
12+ const BASE_URL = process . env . BASE_URL || `http://localhost:${ PORT } ` ;
13+ const AUTH_USER = process . env . AUTH_USER || 'admin' ;
14+ const AUTH_PASS = process . env . AUTH_PASS || 'admin' ;
15+ const SESSION_SECRET = process . env . SESSION_SECRET || 'change-me' ;
1216
1317const app = express ( ) ;
1418
19+ app . use ( express . json ( ) ) ;
20+ app . use ( session ( {
21+ secret : SESSION_SECRET ,
22+ resave : false ,
23+ saveUninitialized : false ,
24+ cookie : { httpOnly : true , maxAge : 8 * 60 * 60 * 1000 } ,
25+ } ) ) ;
26+
27+ // --- Auth routes (publiques) ---
28+
29+ app . post ( '/auth/login' , ( req , res ) => {
30+ const { username, password } = req . body ;
31+ if ( username === AUTH_USER && password === AUTH_PASS ) {
32+ req . session . authenticated = true ;
33+ return res . json ( { ok : true } ) ;
34+ }
35+ res . status ( 401 ) . json ( { error : 'Identifiants incorrects' } ) ;
36+ } ) ;
37+
38+ app . post ( '/auth/logout' , ( req , res ) => {
39+ req . session . destroy ( ) ;
40+ res . json ( { ok : true } ) ;
41+ } ) ;
42+
43+ // --- Middleware auth ---
44+
45+ function requireAuth ( req , res , next ) {
46+ if ( req . session . authenticated ) return next ( ) ;
47+ if ( req . path . startsWith ( '/api/' ) ) return res . status ( 401 ) . json ( { error : 'Non authentifié' } ) ;
48+ res . redirect ( '/login.html' ) ;
49+ }
50+
51+ // Fichiers statiques publics (login.html, style.css)
1552app . use ( express . static ( join ( __dirname , '../public' ) ) ) ;
1653
17- app . get ( '/api/status' , async ( req , res ) => {
54+ // Toutes les routes suivantes sont protégées
55+ app . use ( requireAuth ) ;
56+
57+ // Redirige / vers index.html (déjà servi en statique, mais protégé via middleware)
58+ app . get ( '/' , ( _req , res ) => {
59+ res . sendFile ( join ( __dirname , '../public/index.html' ) ) ;
60+ } ) ;
61+
62+ // --- API ---
63+
64+ app . get ( '/api/status' , async ( _req , res ) => {
1865 try {
1966 const [ containers , websites ] = await Promise . all ( [
2067 getContainers ( ) ,
@@ -34,8 +81,6 @@ app.get('/api/status', async (req, res) => {
3481 }
3582} ) ;
3683
37- app . use ( express . json ( ) ) ;
38-
3984app . post ( '/api/container/restart' , async ( req , res ) => {
4085 const { name } = req . body ;
4186 if ( ! name ) return res . status ( 400 ) . json ( { error : 'name requis' } ) ;
0 commit comments