From 510c063648e337da0069bac9801ddd67f8cddc10 Mon Sep 17 00:00:00 2001 From: Matheus Sanchez Date: Mon, 29 Jan 2024 16:19:03 -0300 Subject: [PATCH] Fixing unauthorized response --- src/controller/session/authUser.ts | 37 +++++++++++++++++------------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/src/controller/session/authUser.ts b/src/controller/session/authUser.ts index c96f5fd..5dcbca3 100644 --- a/src/controller/session/authUser.ts +++ b/src/controller/session/authUser.ts @@ -2,33 +2,38 @@ import { FastifyReply, FastifyRequest } from 'fastify' import { AuthUserUseCase } from '../../use-cases/authUserUseCase' import { z } from 'zod' import { PrismaUsersRepository } from '../../repositories/prisma/prisma-users-repository' +import { InvalidCredentialsError } from '../../use-cases/errors/InvalidCredentialsError' -export async function authUser( +export async function authUser( request: FastifyRequest, response: FastifyReply, ) { - const userRepository = new PrismaUsersRepository() const authUserUseCase = new AuthUserUseCase(userRepository) const AuthUserUseCaseSchema = z.object({ email: z.string().email(), - password: z.string() + password: z.string(), }) - const { email, password } = AuthUserUseCaseSchema.parse(request.body) + const { email, password } = AuthUserUseCaseSchema.parse(request.body) - const { user } = await authUserUseCase.execute({ email, password }) + try { + const { user } = await authUserUseCase.execute({ email, password }) - const token = await response.jwtSign( - {}, - { - sign: { - sub: user.id + const token = await response.jwtSign( + {}, + { + sign: { + sub: user.id, + }, }, - }, - ) - - - return response.status(200).send({ user, token }) -} \ No newline at end of file + ) + + return response.status(200).send({ user, token }) + } catch (e) { + if (e instanceof InvalidCredentialsError) { + return response.status(401).send() + } + } +}