import { ConflictException, Injectable, UnauthorizedException } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { InjectRepository } from '@nestjs/typeorm'; import * as bcrypt from 'bcrypt'; import { Repository } from 'typeorm'; import { User } from './user.entity';
@Injectable() export class AuthService { constructor(@InjectRepository(User) private users: Repository<User>, private jwt: JwtService) {} async register(name: string, email: string, password: string) { if (await this.users.findOneBy({ email })) throw new ConflictException('Email sudah terdaftar'); const user = await this.users.save({ name, email, password: await bcrypt.hash(password, 12) }); return this.token(user); } async login(email: string, password: string) { const user = await this.users.findOneBy({ email }); if (!user || !(await bcrypt.compare(password, user.password))) throw new UnauthorizedException('Email atau kata sandi tidak sesuai'); return this.token(user); } private token(user: User) { return { accessToken: this.jwt.sign({ sub: user.id, role: user.role }), user: { id: user.id, name: user.name, email: user.email, role: user.role } }; } }

