blob: d388694165de93d2c469e8e26b2a1d896da260d1 (
plain)
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
|
import type { FastifyPluginAsync } from 'fastify';
import { ZodError } from 'zod';
import { loginSchema, registerSchema } from './auth.schema';
import * as authService from './auth.service';
const authRoutes: FastifyPluginAsync = async (fastify) => {
fastify.post('/auth/register', async (request, reply) => {
try {
const body = registerSchema.parse(request.body);
const user = await authService.registerUser(body);
const token = fastify.jwt.sign({ sub: user.id });
return reply.status(201).send({ data: { user, token } });
} catch (err: any) {
if (err instanceof ZodError) {
return reply.status(400).send({ error: 'Dados inválidos.', details: err.errors });
}
return reply.status(400).send({ error: err.message });
}
});
fastify.post('/auth/login', async (request, reply) => {
try {
const body = loginSchema.parse(request.body);
const user = await authService.loginUser(body);
const token = fastify.jwt.sign({ sub: user.id });
return reply.send({ data: { user, token } });
} catch (err: any) {
if (err instanceof ZodError) {
return reply.status(400).send({ error: 'Dados inválidos.', details: err.errors });
}
return reply.status(401).send({ error: err.message });
}
});
};
export default authRoutes;
|