All files / src/auth auth.service.ts

100% Statements 26/26
100% Branches 5/5
100% Functions 5/5
100% Lines 22/22

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 512x 2x 2x 2x     2x 7x     7x 7x       2x 2x   1x 1x   1x       3x 3x 2x 2x 1x 1x                       1x 1x       1x      
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { UserService } from '../user/user.service';
import * as bcrypt from 'bcryptjs';
import { JwtService } from '@nestjs/jwt';
 
@Injectable()
export class AuthService {
  private tokenBlacklist: Set<string> = new Set();
 
  constructor(
    private userService: UserService,
    private jwtService: JwtService,
  ) {}
 
  async validateUser(username: string, password: string) {
    const user = await this.userService.findByUsername(username);
    if (user && (await bcrypt.compare(password, user.password))) {
      // Remove password before returning
      const { password, ...result } = user;
      return result;
    }
    return null;
  }
 
  async login(username: string, password: string) {
    const user = await this.userService.findByUsername(username);
    if (!user) throw new UnauthorizedException('User not found');
    const valid = await bcrypt.compare(password, user.password);
    if (!valid) throw new UnauthorizedException('Invalid password');
    const payload = { sub: user.id, username: user.username, role: user.role };
    return {
      access_token: this.jwtService.sign(payload),
      user: {
        id: user.id,
        username: user.username,
        role: user.role,
        nama: user.nama,
      },
    };
  }
 
  logout(token: string) {
    this.tokenBlacklist.add(token);
    return { message: 'Logout success (token revoked)' };
  }
 
  isTokenBlacklisted(token: string): boolean {
    return this.tokenBlacklist.has(token);
  }
}