bcrypt.compare 에러 질문 있습니다.
536
작성한 질문수 12
이런 에러가 발생합니다.
일단 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랑 같이 쓰고 계신 것 같은데 둘 중 하나만 쓰세요.
강의자료는 어디서 다운받나요?
0
141
4
질문 있습니다.
0
315
3
코드 편집기 확장 프로그램
0
220
2
(질문)비밀 저장소에 접근하기 위한 인증 정보는 로컬 .env에 저장하는지?
0
161
2
(질문)외부 저장소를 통한 환경변수 불러오기 비동기 질문
0
177
3
로그인을 해도 LoggedInGuard쪽에서 false값이 나옵니다.
0
161
2
로그인방법이 고민됩니다.
0
197
2
yarn seed 명령어 실행 시 데이터 삽입 안됨
0
304
4
yarn run db:create 시에 발생하는 데코레이터 오류
0
247
2
npm run db:create 시에 발생하는 decorating 오류
0
245
2
RxJS 디버깅 질문 있습니다.
0
198
3
CacheManager에 대해 질문 있습니다.
0
184
2
로깅은 어떻게 하는게 효율적일까요?
0
236
1
CORS 질문 있습니다.
0
425
2
쿠키 옵션에 대해서 질문 있습니다.
0
188
2
로그아웃 요청이 403 forbidden 에러가 나는데 왜그런걸까요??
0
458
1
401 unauthorized문제
0
303
1
가드의 장점에 대해서 질문이 있습니다.
0
231
1
로그 관리에 대해 질문 있습니다.
0
254
2
CORS 에러 질문 있습니다.
0
328
2
배포 환경 DB 연결 질문 있습니다.
0
417
2
socket io 미 연결 문제 (nest & flutter)
1
1164
3
no elements in sequence 에러 관해서 질문이 있습니다.
0
462
1
start:dev-backup으로 돌리면 핫 리로딩이 되요 정상인가요?
0
323
1





