All files / src/auth auth.service.ts

93.54% Statements 29/31
66.66% Branches 2/3
100% Functions 5/5
92.85% Lines 26/28

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 776x             6x   6x 6x 6x     6x   6x 6x 6x           6x   6x 6x 2x     4x   4x 4x           4x             2x 2x     2x       2x 1x   1x       1x 1x                   2x      
import {
  Injectable,
  BadRequestException,
  ConflictException,
  UnauthorizedException,
  NotFoundException,
} from '@nestjs/common';
import { UserRepository } from '../user/user.repository';
import { RegisterUserDto } from './dto/register-user.dto';
import * as bcrypt from 'bcrypt';
import { JwtService } from '@nestjs/jwt';
import { ConfigService } from '@nestjs/config';
 
@Injectable()
export class AuthService {
  constructor(
    private readonly userRepository: UserRepository,
    private jwt: JwtService,
    private configService: ConfigService,
  ) {}
 
  async register(
    registerUserDto: RegisterUserDto,
  ): Promise<{ message: string }> {
    const { name, email, password } = registerUserDto;
 
    const existingUser = await this.userRepository.findByEmail(email);
    if (existingUser) {
      throw new ConflictException({ message: 'User already exists' });
    }
 
    const hashedPassword = await bcrypt.hash(password, 10);
 
    try {
      await this.userRepository.createUser({
        name,
        email,
        password: hashedPassword,
        avatarId: '',
      });
      return { message: 'User has been created' };
    } catch (error) {
      throw new BadRequestException('Body is missing params');
    }
  }
 
  async loginUser(email: string, password: string) {
    const user = await this.userRepository.findByEmail(email);
    Iif (!user) {
      throw new NotFoundException();
    }
    const passwordMatch = await this.checkValidPassword(
      password,
      user.password,
    );
    if (!passwordMatch) throw new UnauthorizedException();
    const token = await this.signToken(user.id);
 
    return { token };
  }
 
  async signToken(userId: string): Promise<string> {
    const payload = { userId: userId };
    return this.jwt.signAsync(payload, {
      expiresIn: '1h',
      secret: this.configService.get<string>('JWT_SECRET'),
    });
  }
 
  async checkValidPassword(
    password: string,
    hashedPassword: string,
  ): Promise<boolean> {
    return bcrypt.compare(password, hashedPassword);
  }
}