Problem deleting password from Authentication Routes

Asked

Viewed 54 times

0

I’m having the following error The operand of a 'delete' Operator must be optional. when trying to delete the user password in the authentication routes, so that it does not go to the frontend. But typescript accuses this error. Looking for this I found information that would have to pass the operand '?' in the User interface that would solve, however the error persists, the interface is in another file separate from the Routes.

Follow the files.

Sessions.routes.ts

import { Router } from 'express';

import AuthenticateUserService from '../services/AuthenticateUserService';

const sessionsRouter = Router();

sessionsRouter.post('/', async (request, response) => {
  const { email_user, password_user } = request.body;

  const authenticateUser = new AuthenticateUserService();

  const { user, token } = await authenticateUser.execute({
    email_user,
    password_user,
  });

  delete user.password_user;

  return response.json({ user, token });
});

export default sessionsRouter;

Authenticateuserservice.ts

import { getRepository } from 'typeorm';
import { compare } from 'bcryptjs';
import { sign } from 'jsonwebtoken';
import authConfig from '../config/auth';

import AppError from '../errors/AppError';

import User from '../models/User';

interface Request {
  email_user: string;
  password_user?: string;
}

interface Response {
  user: User;
  token: string;
}

class AuthenticateUserService {
  public async execute({
    email_user,
    password_user,
  }: Request): Promise<Response> {
    const userRepository = getRepository(User);

    const user = await userRepository.findOne({ where: { email_user } });

    if (!user) {
      throw new AppError('Incorrect email/password combination.', 401);
    }

    if (!password_user) {
      throw new AppError('Incorrect email/password combination.', 401);
    }

    const passwordMatched = await compare(password_user, user.password_user);

    if (!passwordMatched) {
      throw new AppError('Incorrect email/password combination.', 401);
    }

    const { secret, expiresIn } = authConfig.jwt;

    const token = sign({}, secret, {
      subject: user.id_user,
      expiresIn,
    });

    return {
      user,
      token,
    };
  }
}

export default AuthenticateUserService;
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.