-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
163 lines (142 loc) · 5.39 KB
/
Copy pathserver.js
File metadata and controls
163 lines (142 loc) · 5.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import express from 'express';
import path from 'path';
import { fileURLToPath } from 'url';
import process from 'node:process';
import cors from 'cors';
import { PrismaClient } from '@prisma/client';
import * as jose from 'jose';
import bcrypt from 'bcryptjs';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const prisma = new PrismaClient();
const PORT = process.env.PORT || 8080;
const JWT_SECRET = new TextEncoder().encode(process.env.JWT_SECRET || 'gemini-cms-secret-key-2025');
app.use(cors());
app.use(express.json({ limit: '50mb' }));
// --- MIDDLEWARES ---
const authMiddleware = async (req, res, next) => {
const authHeader = req.headers.authorization;
if (!authHeader) return res.status(401).json({ error: 'Token não fornecido' });
const token = authHeader.split(' ')[1];
try {
const { payload } = await jose.jwtVerify(token, JWT_SECRET);
req.user = payload;
next();
} catch (err) {
return res.status(401).json({ error: 'Sessão expirada' });
}
};
// --- SERVICES ---
const ArticleService = {
async getAll() {
return prisma.article.findMany({
include: { author: { select: { name: true, avatarUrl: true, slug: true } }, category: true },
orderBy: { createdAt: 'desc' }
});
},
async getByIdentifier(idOrSlug) {
const isUuid = idOrSlug.length === 36 || idOrSlug.includes('-');
return prisma.article.findFirst({
where: {
OR: [
{ id: isUuid ? idOrSlug : undefined },
{ slug: idOrSlug },
{ exposedId: idOrSlug }
].filter(Boolean)
},
include: { author: true, category: true }
});
}
};
// --- CONTROLLERS ---
const DashboardController = {
async init(req, res) {
try {
const [articlesCount, authors, activities, votes] = await Promise.all([
prisma.article.count(),
prisma.author.findMany({ select: { id: true, name: true, avatarUrl: true } }),
prisma.activity.findMany({
include: { author: { select: { name: true, avatarUrl: true } } },
orderBy: { createdAt: 'desc' },
take: 10
}),
prisma.vote.findMany({ where: { userId: req.user.id } })
]);
res.json({
stats: { articles: articlesCount, authors: authors.length },
authors,
activities,
starredIds: votes.map(v => v.articleId)
});
} catch (e) {
res.status(500).json({ error: e.message });
}
}
};
// --- ROUTES ---
app.post('/api/auth/login', async (req, res) => {
const { email, pass } = req.body;
const user = await prisma.user.findUnique({ where: { email }, include: { author: true } });
if (!user || !(await bcrypt.compare(pass, user.password))) return res.status(401).json({ error: 'Credenciais inválidas' });
const token = await new jose.SignJWT({ id: user.id, authorId: user.author?.id, role: user.role })
.setProtectedHeader({ alg: 'HS256' }).setExpirationTime('24h').sign(JWT_SECRET);
const { password, ...safeUser } = user;
res.json({ user: safeUser, token });
});
app.get('/api/feed/init', authMiddleware, async (req, res) => {
const [articles, categories, votes] = await Promise.all([
ArticleService.getAll(),
prisma.category.findMany(),
prisma.vote.findMany({ where: { userId: req.user.id } })
]);
res.json({ articles, categories, starredIds: votes.map(v => v.articleId) });
});
app.get('/api/dashboard/init', authMiddleware, DashboardController.init);
// ROTA DE DETALHE CONSOLIDADO (Corrige o erro do frontend)
app.get('/api/articles/detail/:id/:userId', authMiddleware, async (req, res) => {
try {
const { id, userId } = req.params;
const art = await ArticleService.getByIdentifier(id);
if (!art) return res.status(404).json({ error: 'Matéria não encontrada' });
const authorIds = art.authorIds || (art.authorId ? [art.authorId] : []);
const [authors, votes] = await Promise.all([
prisma.author.findMany({ where: { id: { in: authorIds } } }),
prisma.vote.findMany({ where: { articleId: art.id } })
]);
res.json({
article: art,
authors,
voteCount: votes.length,
hasVoted: votes.some(v => v.userId === userId)
});
} catch (e) {
res.status(500).json({ error: e.message });
}
});
// ROTA PARA "LEIA MAIS"
app.get('/api/articles/published', authMiddleware, async (req, res) => {
try {
const articles = await prisma.article.findMany({
where: { status: 'PUBLISHED' },
take: 10,
orderBy: { createdAt: 'desc' },
include: { author: { select: { name: true } } }
});
res.json(articles);
} catch (e) {
res.status(500).json({ error: e.message });
}
});
app.get('/api/articles/:identifier', authMiddleware, async (req, res) => {
const art = await ArticleService.getByIdentifier(req.params.identifier);
art ? res.json(art) : res.status(404).json({ error: 'Matéria não encontrada' });
});
app.get('/api/categories', authMiddleware, async (req, res) => res.json(await prisma.category.findMany()));
app.patch('/api/articles/:id', authMiddleware, async (req, res) => {
const updated = await prisma.article.update({ where: { id: req.params.id }, data: req.body });
res.json(updated);
});
app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', (req, res) => res.sendFile(path.join(__dirname, 'dist', 'index.html')));
app.listen(PORT, () => console.log(`🚀 Redação Operacional em http://localhost:${PORT}`));