0

Estou com uma autenticação JWT que quando eu testo no insomnia não funciona de jeito nenhum

Esse é a implementação do Repository

import { dojoModel } from '../../../../database/models/dojosModel';
import { AppError } from '../../../erros/Error';
import { Dojo } from '../../models/Dojo';
import { IDojoRepository } from '../IDojoRepository';
import { Op } from 'sequelize';

class DojoRepository implements IDojoRepository {
  private static instance: DojoRepository;

  public static getInstance(): DojoRepository {
    if (!DojoRepository.instance) {
      DojoRepository.instance = new DojoRepository();
    }

    return DojoRepository.instance;
  }

  async create({
    id_dojo,
    dojo,
    password,
    address_line1,
    address_line2,
    city,
    state,
    country,
    phone,
    email,
    paid_out,
  }: ICreateDojoDTO): Promise<Dojo> {
    const obj: any = await dojoModel.create({
      id_dojo,
      dojo,
      password,
      address_line1,
      address_line2,
      city,
      state,
      country,
      phone,
      email,
      paid_out,
    });

    return obj.toJSON() as Dojo;
  }

  async update({
    id_dojo,
    dojo,
    address_line1,
    address_line2,
    city,
    state,
    country,
    phone,
    email,
    paid_out,
  }: ICreateDojoDTO): Promise<Dojo> {
    // const obj: any = await dojoModel.update(
    //   {
    //     id_dojo,
    //     dojo,
    //     address_line1,
    //     address_line2,
    //     city,
    //     state,
    //     country,
    //     phone,
    //     email,
    //     paid_out,
    //   },
    //   { where: { id_dojo: id_dojo } }
    // );

    const [rowsAffected] = await dojoModel.update(
      {
        dojo,
        address_line1,
        address_line2,
        city,
        state,
        country,
        phone,
        email,
        paid_out,
      },
      {
        where: { id_dojo: id_dojo },
      }
    );

    if (rowsAffected === 0) {
      throw new AppError('Dojo not found.', 404);
    }

    const updatedDojo = await dojoModel.findOne({
      where: { id_dojo: id_dojo },
    });

    return updatedDojo?.toJSON() as Dojo;
  }

  async findById(id_dojo: string): Promise<Dojo> {
    const obj: any = await dojoModel.findOne({ where: { id_dojo: id_dojo } });

    return obj;
  }

  async findByEmail(email: string): Promise<Dojo> {
    const dojo: any = await dojoModel.findOne({ where: { email } });
    return dojo;
  }

  async list(): Promise<Dojo[]> {
    const dojos: any = await dojoModel.findAll({});
    return dojos;
  }

  async delete(id_dojo: string): Promise<void> {
    const rowsAffected = await dojoModel.destroy({
      where: { id_dojo },
    });

    if (rowsAffected === 0) {
      throw new AppError('Dojo not found.', 404);
    }
  }

  async search(searchTerm: string): Promise<Dojo[]> {
    const dojos = await dojoModel.findAll({
      where: {
        [Op.or]: [
          { dojo: { [Op.iLike]: `%${searchTerm}%` } },
          { city: { [Op.iLike]: `%${searchTerm}%` } },
          { state: { [Op.iLike]: `%${searchTerm}%` } },
        ],
      },
    });

    return dojos.map((dojo) => dojo.toJSON() as Dojo);
  }
}

export { DojoRepository };

Esse é o UseCase:

import { AppError } from '../../../erros/Error';
import { compare } from 'bcrypt';
import { sign } from 'jsonwebtoken';
import { IDojoRepository } from '../../repositories/IDojoRepository';

interface IRequest {
  email: string;
  password: string;
}

interface IResponse {
  dojo: {
    id_dojo: string;
    dojo: string;
    email: string;
  };
  token: string;
}

class AuthenticateUseCase {
  constructor(private dojoRepository: IDojoRepository) {}

  async execute({ email, password }: IRequest): Promise<IResponse> {
    try {
      const dojo = await this.dojoRepository.findByEmail(email);

      if (!dojo) throw new Error('E-mail ou senha incorretos!');

      if (
        typeof dojo.id_dojo !== 'string' ||
        typeof dojo.dojo !== 'string' ||
        typeof dojo.email !== 'string'
      ) {
        throw new Error('Objeto Dojo inválido!');
      }

      const passwordMatch = await compare(
        password,
        dojo.password ? dojo.password : ''
      );

      if (!passwordMatch) throw new Error('E-mail ou senha incorretos!');

      const token = sign({}, 'ferrazdojos', {
        subject: dojo.id_dojo,
        expiresIn: '7d',
      });

      const tokenReturn: IResponse = {
        token,
        dojo: {
          id_dojo: dojo.id_dojo,
          dojo: dojo.dojo,
          email: dojo.email,
        },
      };

      return tokenReturn;
    } catch (error) {
      throw new AppError(`Não foi possível autenticar o Dojo: ${error}`);
    }
  }
}

export { AuthenticateUseCase };

Esse é o Controller:

import { AppError } from '../../../erros/Error';
import { Request, Response } from 'express';
import { AuthenticateUseCase } from './AuthenticateUseCase';
import { z } from 'zod';

class AuthenticateController {
  constructor(private authenticateUseCase: AuthenticateUseCase) {}

  async handle(request: Request, response: Response): Promise<Response> {
    const getDojoBodySchema = z.object({
      email: z.string(),
      password: z.string(),
    });

    try {
      const { email, password } = getDojoBodySchema.parse(request.body);

      const tokens = await this.authenticateUseCase.execute({
        email,
        password,
      });

      return response.status(200).json(tokens);
    } catch (error: any) {
      console.error(`Error to authenticate dojo: ${error}`);

      if (error instanceof AppError) {
        return response.status(error.statusCode).json({ error: error.message });
      }

      return response.status(400).json({ error: error.error });
    }
  }
}

export { AuthenticateController };

E esse é o middleware que verifica a autenticação:

import { AuthenticateUseCase } from '../modules/dojo/useCases/authenticate/AuthenticateUseCase';
import { NextFunction, Request, Response } from 'express';
import jwt from 'jsonwebtoken';
import { AppError } from '../modules/erros/Error';
import { DojoRepository } from '../modules/dojo/repositories/implementations/DojoRepository';

interface TokenPayload {
  sub: string;
  iat: number;
  exp: number;
}

export async function ensureAuthenticated(
  authenticateUseCase: AuthenticateUseCase
) {
  return async function (
    request: Request,
    response: Response,
    next: NextFunction
  ) {
    const authHeader = request.headers.authorization;

    if (!authHeader) {
      throw new AppError('JWT token is missing', 401);
    }

    const [, token] = authHeader.split(' ');

    try {
      const { sub: id_dojo } = jwt.verify(token, 'ferrazdojos') as TokenPayload;

      const dojoRepository = new DojoRepository();
      const dojo = await dojoRepository.findById(id_dojo);

      if (!dojo) {
        throw new AppError('Dojo not found', 401);
      }

      // request.dojo = {
      //   id_dojo: dojo.id_dojo,
      //   dojo: dojo.dojo,
      //   email: dojo.email,
      // };

      return next();
    } catch (error) {
      throw new AppError('Invalid JWT token', 401);
    }
  };
}

2

0

Você deve fazer log-in para responder a esta pergunta.

Pesquise outras perguntas com a tag .