Aggiorna api_v1/server.js

This commit is contained in:
Fabio 2026-02-20 19:27:58 +08:00
parent 6f08bab103
commit 7ee081c77f

View file

@ -1,3 +1,5 @@
require('dotenv').config();
const fs = require('fs');
const bodyParser = require('body-parser');
const jsonServer = require('json-server');
@ -6,17 +8,31 @@ const bcrypt = require('bcrypt');
const path = require('path');
const scanPhoto = require('./scanphoto.js');
const SECRET_KEY = '123456789';
const expiresIn = '1h';
const SECRET_KEY = process.env.JWT_SECRET || '123456789';
const EXPIRES_IN = process.env.JWT_EXPIRES || '1h';
const PORT = process.env.SERVER_PORT || 4000;
const server = jsonServer.create();
// Serve static files
// -----------------------------------------------------
// STATIC FILES
// -----------------------------------------------------
server.use(jsonServer.defaults({
static: path.join(__dirname, '../public')
}));
// Router
// -----------------------------------------------------
// CONFIG ENDPOINT (PUBBLICO)
// -----------------------------------------------------
server.get('/config', (req, res) => {
res.json({
baseUrl: process.env.BASE_URL
});
});
// -----------------------------------------------------
// ROUTER DB
// -----------------------------------------------------
let router;
if (fs.existsSync('./api_v1/db.json')) {
router = jsonServer.router('./api_v1/db.json');
@ -26,14 +42,19 @@ if (fs.existsSync('./api_v1/db.json')) {
router = jsonServer.router('./api_v1/db.json');
}
// Users DB
// -----------------------------------------------------
// USERS DB
// -----------------------------------------------------
const userdb = JSON.parse(fs.readFileSync('./api_v1/users.json', 'UTF-8'));
server.use(bodyParser.urlencoded({ extended: true }));
server.use(bodyParser.json());
// -----------------------------------------------------
// JWT HELPERS
// -----------------------------------------------------
function createToken(payload) {
return jwt.sign(payload, SECRET_KEY, { expiresIn });
return jwt.sign(payload, SECRET_KEY, { expiresIn: EXPIRES_IN });
}
function verifyToken(token) {
@ -46,40 +67,51 @@ function isAuthenticated({ email, password }) {
) !== -1;
}
function azz() {
// -----------------------------------------------------
// RESET DB
// -----------------------------------------------------
function resetDB() {
const initialData = fs.readFileSync('api_v1/initialDB.json', 'utf8');
fs.writeFileSync('api_v1/db.json', initialData);
router.db.setState(JSON.parse(initialData));
console.log('DB resettato');
}
// Home → public/index.html
// -----------------------------------------------------
// HOME
// -----------------------------------------------------
server.get('/', (req, res) => {
res.sendFile(path.resolve("public/index.html"));
});
// Scan photos
// -----------------------------------------------------
// SCAN FOTO
// -----------------------------------------------------
server.get('/scan', async (req, res) => {
azz();
resetDB();
await scanPhoto('./public/photos/original');
console.log("Ricaricato");
res.send({ status: 'Ricaricato' });
});
// Serve files
// -----------------------------------------------------
// FILE STATICI
// -----------------------------------------------------
server.get('/files', (req, res) => {
res.sendFile(path.resolve("public/" + req.query.file));
});
// Reset DB
// -----------------------------------------------------
// RESET DB MANUALE
// -----------------------------------------------------
server.get('/initDB', (req, res) => {
const initialData = fs.readFileSync('api_v1/initialDB.json', 'utf8');
fs.writeFileSync('api_v1/db.json', initialData);
router.db.setState(JSON.parse(initialData));
resetDB();
res.send({ status: 'DB resettato' });
});
// Login
// -----------------------------------------------------
// LOGIN (PUBBLICO)
// -----------------------------------------------------
server.post('/auth/login', (req, res) => {
const { email, password } = req.body;
@ -87,11 +119,13 @@ server.post('/auth/login', (req, res) => {
return res.status(401).json({ status: 401, message: 'Incorrect email or password' });
}
const token = createToken({ email, password });
const token = createToken({ email });
res.status(200).json({ token });
});
// Auth middleware
// -----------------------------------------------------
// JWT MIDDLEWARE (TUTTO IL RESTO È PROTETTO)
// -----------------------------------------------------
server.use(/^(?!\/auth).*$/, (req, res, next) => {
if (!req.headers.authorization || req.headers.authorization.split(' ')[0] !== 'Bearer') {
return res.status(401).json({ status: 401, message: 'Bad authorization header' });
@ -105,11 +139,15 @@ server.use(/^(?!\/auth).*$/, (req, res, next) => {
}
});
// Mount router
// -----------------------------------------------------
// ROUTER JSON-SERVER
// -----------------------------------------------------
server.use(router);
// Start server on 4000
server.listen(4000, () => {
console.log('Auth API server running on port 4000 ...');
// -----------------------------------------------------
// START SERVER
// -----------------------------------------------------
server.listen(PORT, () => {
console.log(`Auth API server running on port ${PORT} ...`);
});