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 | 9x 9x 9x 9x 9x 9x 9x 9x 9x 7x 7x 7x 2x 5x 5x 5x 3x 3x 1x 2x 2x 1x 1x 63x 63x 2x | import {
Injectable,
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);
await this.userRepository.createUser({
name,
email,
password: hashedPassword,
avatarId: '0',
});
return { message: 'User has been created' };
}
async loginUser(email: string, password: string) {
const user = await this.userRepository.findByEmail(email);
if (!user) {
throw new NotFoundException('User not found');
}
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: '1d',
secret: this.configService.get<string>('JWT_SECRET'),
});
}
async checkValidPassword(
password: string,
hashedPassword: string,
): Promise<boolean> {
return bcrypt.compare(password, hashedPassword);
}
}
|