Files
zen-kanji/server/server.js
Rene Kievits e1bf8f2032
All checks were successful
Release Build / build-docker (push) Successful in 43s
Release Build / build-android-and-release (push) Successful in 2m11s
small prod changes
2025-12-24 16:20:44 +01:00

79 lines
1.8 KiB
JavaScript

import Fastify from 'fastify';
import cors from '@fastify/cors';
import jwt from '@fastify/jwt';
import { PORT, JWT_SECRET } from './src/config/constants.js';
import { connectDB } from './src/config/db.js';
import routes from './src/routes/v1.js';
import { User } from './src/models/User.js';
const fastify = Fastify({ logger: true });
await connectDB();
const allowedOrigins = [
process.env.SERVER_EXT_ACCESS,
process.env.SERVER_INT_ACCESS,
'http://localhost',
'capacitor://localhost',
'https://10.0.2.2:5173',
'http://localhost:5173'
].filter(Boolean).map(uri => uri.replace(/\/$/, ''));
await fastify.register(cors, {
origin: (origin, cb) => {
if (!origin) return cb(null, true);
if (allowedOrigins.includes(origin)) {
return cb(null, true);
}
console.log(`CORS BLOCKED: Browser sent "${origin}". Allowed list:`, allowedOrigins);
cb(new Error("Not allowed by CORS"));
},
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
credentials: true
});
await fastify.register(jwt, {
secret: process.env.JWT_SECRET
});
fastify.decorate('authenticate', async function (req, reply) {
try {
const payload = await req.jwtVerify();
const user = await User.findById(payload.userId);
if (!user) {
reply.code(401).send({ message: 'User not found', code: 'INVALID_USER' });
return;
}
if (payload.version !== user.tokenVersion) {
reply.code(401).send({ message: 'Session invalid', code: 'INVALID_SESSION' });
return;
}
if (payload.version !== user.tokenVersion) {
throw new Error('Session invalid');
}
req.user = user;
} catch (err) {
reply.code(401).send(err);
}
});
await fastify.register(routes);
const start = async () => {
try {
await fastify.listen({ port: PORT, host: '0.0.0.0' });
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
start();