Commit cd77dcf4 authored by Diego Iván's avatar Diego Iván
Browse files

agregando user auth service con login y signin

parent 86ad9828
Loading
Loading
Loading
Loading
+56 −0
Original line number Diff line number Diff line
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { EncryptionService } from '../encryption/encryption.service';
import { JwtConstants } from 'src/constants/jwt.constants';
import { UserSigninResDto } from './dto/user-signin-res.dto';
import { User } from 'src/user/entities/user.entity';
import { UserService } from 'src/user/user.service';
import { CreateUserDto } from 'src/user/dto/create-user.dto';
import { LoginUserDto } from './dto/login-user.dto';

@Injectable()
export class AuthUserService {
  constructor(
    private userService: UserService,
    private jwtService: JwtService,
    private encryptionService: EncryptionService,
  ) {}

  async signUp(createAdminDto: CreateUserDto): Promise<string> {
    const loginAdminDto: LoginUserDto = {
      email: createAdminDto.email,
      password: createAdminDto.password,
    };
    const hashedPwd = await this.encryptionService.hashPassword(
      createAdminDto.password,
    );
    createAdminDto.password = hashedPwd;
    await this.userService.create(createAdminDto);

    const adminSigninResDto: UserSigninResDto =
      await this.signIn(loginAdminDto);
    return adminSigninResDto.token;
  }

  async signIn(logInAdmin: LoginUserDto): Promise<UserSigninResDto> {
    const user: User = await this.userService.findOne(logInAdmin.email);
    const validPwd: boolean = await this.encryptionService.comparePassword(
      logInAdmin.password,
      user.password,
    );
    if (!validPwd) {
      throw new HttpException('Invalid credentials', HttpStatus.UNAUTHORIZED);
    }
    const accessToken = await this.jwtService.sign(
      { email: user.email, name: user.name, lastName: user.lastName },
      { secret: JwtConstants.SECRET },
    );
    const userSigninResDto: UserSigninResDto = {
      email: user.email,
      name: user.name,
      lastName: user.lastName,
      token: accessToken,
    };
    return userSigninResDto;
  }
}