• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

bcrypt.compare 에러 질문 있습니다.

22.03.07 01:13 작성 조회수 361

0

 

 

이런 에러가 발생합니다. 

일단 users 테이블에 컬럼은 id, username, password, createdAt, updatedAt이 있습니다.

아무리 찾아봐도 저는 못찾겠습니다. 문제가 뭘까요..? undefined가 나오는 것 같아서 여기저기 찍어봐도 어디서 나오는지도 모르겠습니다.

 

auth.service.ts

import { Injectable } from '@nestjs/common';
import bcrypt from 'bcrypt';
import { InjectRepository } from "@nestjs/typeorm";
import { Users } from "../entities/Users";
import { Repository } from "typeorm";

@Injectable()
export class AuthService {
constructor(
@InjectRepository(Users) private usersRepository: Repository<Users>
) {}

async validateUser(username: string, password: string) {
const user = await this.usersRepository.findOne({
where: {username},
select: ['id', 'username', 'password' ]
});
console.log(username, password, user);
if (!user) {
return null;
}
console.log(password, user.password);
const result = await bcrypt.compare(user.password, password);
if (result) {
const { password, ...userWithoutPassword } = user;
return userWithoutPassword;
}
return null;
}
}

 

local.serializer.ts

import { Injectable } from "@nestjs/common";
import { PassportSerializer } from "@nestjs/passport";
import { AuthService } from "./auth.service";
import { InjectRepository } from "@nestjs/typeorm";
import { Users } from "../entities/Users";
import { Repository } from "typeorm";

@Injectable()
export class LocalSerializer extends PassportSerializer {
constructor(
private readonly authService: AuthService,
@InjectRepository(Users) private usersRepository: Repository<Users>,
) {
super();
}

serializeUser(user: Users, done: CallableFunction) {
console.log(user);
done(null, user.id);
}

async deserializeUser(userId: string, done: CallableFunction) {
return await this.usersRepository
.findOneOrFail(
{
id: +userId,
},
{
select: ['id', 'username']
},
)
.then((user) => {
console.log('user', user);
done(null, user);
})
.catch((error) => done(error));
}
}

 

local.strategy.ts

import { Injectable, UnauthorizedException } from "@nestjs/common";
import {Strategy} from "passport-local";
import { PassportStrategy } from "@nestjs/passport";
import { AuthService } from "./auth.service";

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super({ usernameField: 'username', passwordField: 'password' });
}

async validate(username: string, password: string, done: CallableFunction) {
const user = await this.authService.validateUser(username, password);
if (!user) {
throw new UnauthorizedException();
}
return done(null, user);
}
}

 

local-auth.guard.ts

import { Injectable } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";

@Injectable()
export class LocalAuthGuard extends AuthGuard('local') {
async canActivate(context): Promise<boolean> {
const can = await super.canActivate(context);
if (can) {
const request = context.switchToHttp().getRequest();
console.log('login for cookie');
await super.logIn(request);
}
return true;
}
}

 

users.service.ts

import { Injectable } from '@nestjs/common';
import { InjectRepository } from "@nestjs/typeorm";
import { Users } from "../entities/Users";
import { Repository } from "typeorm";
import * as bcrypt from 'bcryptjs';

@Injectable()
export class UsersService {
constructor(
@InjectRepository(Users) private usersRepository: Repository<Users>,
) { }

async findByUserName(username: string) {
return this.usersRepository.findOne({
where: { username },
select: ["id", 'username', 'password'],
});
}

async signUp(username: string, password: string) {
console.log("@@ = ", password);
const salt = await bcrypt.genSalt();
const hashedPassword = await bcrypt.hash(password, salt);

const user = await this.usersRepository.findOne({ where: { username } });
if(user) {
throw new Error('이미 존재하는 사용자입니다');
}
const returned = await this.usersRepository.save({
username,
password: hashedPassword,
});
console.log("successed = ", returned);
return true;
}
}

 

users.controller.ts

import {
Body,
Controller,
ForbiddenException,
NotFoundException,
Post,
UseGuards,
UseInterceptors
} from "@nestjs/common";
import { UsersService } from "./users.service";
import { ApiOperation, ApiTags } from "@nestjs/swagger";
import { JoinRequestDto } from "./dto/join.request.dto";
import { User } from "../common/decorator/user.decorator";
import { LocalAuthGuard } from "../auth/local-auth.guard";
import { UndefinedToNullInterceptor } from "../interceptors/undefinedToNull.interceptor";

@ApiTags('USERS')
@UseInterceptors(UndefinedToNullInterceptor)
@Controller('api/users')
export class UsersController {
constructor(private usersService: UsersService) {}

@ApiOperation({ summary: '로그인' })
@UseGuards(LocalAuthGuard)
@Post('login')
login(@User() user) {
return user;
}

@ApiOperation({ summary: '회원가입' })
@Post('signup')
async join(@Body() data: JoinRequestDto) {
const user = this.usersService.findByUserName(data.username);
if (!user) {
throw new NotFoundException();
}
const result = await this.usersService.signUp(
data.username,
data.password,
);
if(result) {
return 'ok';
} else {
throw new ForbiddenException();
}
}
}

답변 1

답변을 작성해보세요.

0

bcrypt가 undefined인 겁니다. import * as bcrypt from 'bcrypt' 하세요.

bcryptjs랑 같이 쓰고 계신 것 같은데 둘 중 하나만 쓰세요.