feat: migrate to postgres and dockerize app

This commit is contained in:
VPS 4 Builder
2026-05-24 04:57:33 +02:00
commit c38184653a
47 changed files with 13401 additions and 0 deletions
+116
View File
@@ -0,0 +1,116 @@
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
const db = require('./database');
const JWT_SECRET = process.env.JWT_SECRET || 'sua-chave-secreta-alterar-em-producao';
const JWT_EXPIRES_IN = '7d';
// ================================================================
// MIDDLEWARE DE AUTENTICAÇÃO
// ================================================================
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN
// Se não tem token, verifica se está tentando acessar uma página
if (!token) {
const isApiRoute = req.path.startsWith('/api');
const isLoginRoute = req.path.startsWith('/login') || req.path === '/auth/login.html';
if (isLoginRoute || req.path === '/status') {
return next();
}
if (isApiRoute) {
return res.status(401).json({ error: 'Token não fornecido' });
}
return res.redirect('/login');
}
// Verificar token
jwt.verify(token, JWT_SECRET, (err, user) => {
if (err) {
if (req.path.startsWith('/api')) {
return res.status(403).json({ error: 'Token inválido' });
}
return res.redirect('/login');
}
req.user = user;
next();
});
}
// ================================================================
// HASH DE SENHA
// ================================================================
async function hashPassword(password) {
const saltRounds = 10;
return await bcrypt.hash(password, saltRounds);
}
async function verifyPassword(password, hash) {
return await bcrypt.compare(password, hash);
}
// ================================================================
// GERAR TOKEN JWT
// ================================================================
function generateToken(user) {
return jwt.sign(
{
id: user.id,
username: user.username
},
JWT_SECRET,
{ expiresIn: JWT_EXPIRES_IN }
);
}
// ================================================================
// CRIAR USUÁRIO INICIAL
// ================================================================
async function createInitialUser() {
try {
// Verificar se usuário já existe
const existingUser = await db.get('SELECT * FROM users WHERE username = ?', ['rcesar']);
if (existingUser) {
console.log('👤 Usuário admin já existe:', existingUser.username);
return;
}
// Criar hash da senha
const passwordHash = await hashPassword('Rc362514');
// Inserir usuário
await db.run(
`INSERT INTO users (username, email, password_hash, created_at)
VALUES (?, ?, ?, NOW())`,
['rcesar', 'rcesar@rcesar.com', passwordHash]
);
console.log('✅ Usuário admin criado: rcesar / Rc362514');
} catch (error) {
// Ignorar se tabela não existe ainda
if (error.message.includes('no such table')) {
console.log('⚠️ Tabela users não existe. Será criada pelo database.js');
} else {
console.error('❌ Erro ao criar usuário inicial:', error);
}
}
}
module.exports = {
authenticateToken,
hashPassword,
verifyPassword,
generateToken,
createInitialUser,
JWT_SECRET
};