77 lines
1.7 KiB
JavaScript
77 lines
1.7 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 = [
|
|
'http://192.168.0.26:5169',
|
|
'http://192.168.0.26:5173',
|
|
'http://localhost:5173',
|
|
'http://localhost',
|
|
'https://localhost',
|
|
'capacitor://localhost',
|
|
'https://10.0.2.2:5173',
|
|
'https://zenkanji.crylia.de'
|
|
];
|
|
|
|
if (process.env.CORS_ORIGINS) {
|
|
const prodOrigins = process.env.CORS_ORIGINS.split(',');
|
|
allowedOrigins.push(...prodOrigins);
|
|
}
|
|
|
|
await fastify.register(cors, {
|
|
origin: allowedOrigins,
|
|
methods: ['GET', 'POST', 'PUT', 'DELETE'],
|
|
credentials: true
|
|
});
|
|
|
|
await fastify.register(jwt, {
|
|
secret: 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' });
|
|
console.log(`Server running at http://localhost:${PORT}`);
|
|
} catch (err) {
|
|
fastify.log.error(err);
|
|
process.exit(1);
|
|
}
|
|
};
|
|
start();
|