aboutsummaryrefslogtreecommitdiff
path: root/api/src/modules/auth/auth.routes.ts
diff options
context:
space:
mode:
Diffstat (limited to 'api/src/modules/auth/auth.routes.ts')
-rw-r--r--api/src/modules/auth/auth.routes.ts40
1 files changed, 40 insertions, 0 deletions
diff --git a/api/src/modules/auth/auth.routes.ts b/api/src/modules/auth/auth.routes.ts
new file mode 100644
index 0000000..d388694
--- /dev/null
+++ b/api/src/modules/auth/auth.routes.ts
@@ -0,0 +1,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;