Files
2026-06-13 14:21:20 +00:00

77 lines
2.0 KiB
JavaScript
Executable File

#!/usr/bin/env node
'use strict'
import p42apiConfig from './p42api.json' with { type: 'json' }
import mysql from 'mysql2/promise'
import http from 'http'
import express from 'express'
import session from 'express-session'
import connectMySQL from 'express-mysql-session'
import { corsResolver } from './corsMiddleware.js'
import { P42ApiEndpoints } from './p42ApiEndpoints.js'
const MySQLStore = connectMySQL(session)
const app = express();
app.set('trust proxy', 1) // trust first proxy (nginx), so we serve http to nginx, but we still behave as if we're in https
app.use(express.json())
app.use(corsResolver)
//TOTO: kick this
const mysqlCreds = {
// host: '127.0.0.1',
// port: 3306,
socketPath: '/var/run/mysqld/mysqld.sock',
user: process.env.user,
password: process.env.mysql_pass,
database: 'p42GUI',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
}
if(!mysqlCreds.user || !mysqlCreds.password) {
console.error('Missing MySQL credentials: set user and mysql_pass in environment')
process.exit(1)
}
const db = await mysql.createConnection(mysqlCreds)
const sessionStore = new MySQLStore({
createDatabaseTable: false,
clearExpired: true,
expiration: 1000 * 60 * 60,
schema: {
tableName: 'sessions',
columnNames: {
session_id: 'session_id',
expires: 'expires',
data: 'data'
}
}
}, db)
app.use(session({
name: 'p42.api.sid',
secret: 'qNhy555Y9vyxj?!3yaYA=aKfgk+Wy5eymNtP*?4i',
store: sessionStore,
resave: false,
saveUninitialized: false,
rolling: true, //Autorefresh
cookie: {
maxAge: 1000 * 60 * 60,
secure: true, //See trust proxy above
sameSite: 'lax',
},
}
))
let eps = new P42ApiEndpoints(app, db)
const server = http.createServer(app)
.listen(p42apiConfig.listenPort, p42apiConfig.listenHost, function (req, res) {
console.log("p42api now listening on %j:%j ", p42apiConfig.listenHost, p42apiConfig.listenPort);
});