• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    미해결

user 세션 serialize 문제 질문

21.09.28 22:47 작성 조회수 265

0

[Nest] 25160  - 2021. 09. 28. 오후 10:32:34   ERROR [ExceptionsHandler] Failed to serialize user into session

강의보는 도중에 나왔던 동일한 에러가 나와서 동일한 방법으로, auth.service.ts 파일에 validateUser() 에서 select에 'id'를 추가 하였습니다.


그렇게 했는데도 동일한 에러가 발생해서 user 값을 제대로 받아오는지 확인 하기 위해 console.log를 통해 확인해본 결과 정상적으로 select 한 값들(id, email, password, nickname)을 받아온 것을 확인하였습니다.

그래서 serializer가 제대로 등록되지 않았나 확인하기 위해
github에 있는 sleact를 다운받아

auth 폴더의
< auth.module.ts, auth.service.ts, local-auth.guard.ts, localserializer.ts, local.strategy.ts>

app.modules.ts
app.service.ts
main.ts 
등을 확인하고 serialize가 들어 가는 내용을 검색해 보았으나 모두 동일하게 등록되어 있음을 확인하였습니다.

이 상황에서 제가 어느 부분을 중점적으로 살펴 보아야 할지 감이 오지 않아 여쭤보게되었습니다.
에러 문구 : 

[Nest] 25160  - 2021. 09. 28. 오후 10:32:34   ERROR [ExceptionsHandler] Failed to serialize user into session

Error: Failed to serialize user into session

    at pass (D:\Slack\nest\dist\main.js:14933:19)

    at Authenticator.serializeUser (D:\Slack\nest\dist\main.js:14951:5)

    at SessionManager.logIn (D:\Slack\nest\dist\main.js:15239:8)      

    at IncomingMessage.req.login.req.logIn (D:\Slack\nest\node_modules\passport\lib\http\request.js:50:33)

    at D:\Slack\nest\dist\main.js:13559:64

    at new Promise (<anonymous>)

    at LocalAuthGuard.<anonymous> (D:\Slack\nest\dist\main.js:13559:23)

    at Generator.next (<anonymous>)

    at D:\Slack\nest\dist\main.js:13516:71

    at new Promise (<anonymous>)[Nest] 25160  - 2021. 09. 28. 오후 10:32:34   ERROR [ExceptionsHandler] Failed to serialize user into session

Error: Failed to serialize user into session

    at pass (D:\Slack\nest\dist\main.js:14933:19)

    at Authenticator.serializeUser (D:\Slack\nest\dist\main.js:14951:5)

    at SessionManager.logIn (D:\Slack\nest\dist\main.js:15239:8)      

    at IncomingMessage.req.login.req.logIn (D:\Slack\nest\node_modules\passport\lib\http\request.js:50:33)

    at D:\Slack\nest\dist\main.js:13559:64

    at new Promise (<anonymous>)

    at LocalAuthGuard.<anonymous> (D:\Slack\nest\dist\main.js:13559:23)

    at Generator.next (<anonymous>)

    at D:\Slack\nest\dist\main.js:13516:71

    at new Promise (<anonymous>)

-----------D:\Slack\nest\dist\main.js:14933:19)-------

Authenticator.prototype.serializeUser = function(fn, req, done) {
  if (typeof fn === 'function'{
    return this._serializers.push(fn);
  }
  
  // private implementation that traverses the chain of serializers, attempting
  // to serialize a user
  var user = fn;

  // For backwards compatibility
  if (typeof req === 'function'{
    done = req;
    req = undefined;
  }
  
  var stack = this._serializers;
  (function pass(i, err, obj) {
    // serializers use 'pass' as an error to skip processing
    if ('pass' === err{
      err = undefined;
    }
    // an error or serialized object was obtained, done
    if (err || obj || obj === 0{ return done(err, obj); }
    
    var layer = stack[i];
    if (!layer{
      return done(new Error('Failed to serialize user into session'));
    }
    
    
    function serialized(e, o) {
      pass(i + 1, e, o);
    }
    
    try {
      var arity = layer.length;
      if (arity == 3{
        layer(req, user, serialized);
      } else {
        layer(user, serialized);
      }
    } catch(e{
      return done(e);
    }
  })(0);
};

---------------------auth.service.ts -------------------

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


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

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

답변 2

·

답변을 작성해보세요.

0

nak512님의 프로필

nak512

질문자

2021.09.29

안녕하세요, 제로초님.
답변 주셨는데도 불구하고 늦게 응답해서 죄송합니다.

말씀해주신, 
https://github.com/ZeroCho/sleact/blob/master/nest-typeorm/src/auth/local.serializer.ts#L18

위치에 있는console.log(user) 자체가 실행이 되지 않습니다.


---------------- auth.service.ts async validateUser 소스코드와 console.log ----------------------

 

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

 

query: SELECT `Users`.`id` AS `Users_id`, `Users`.`email` AS `Users_email`, `Users`.`nickname` AS `Users_nickname`, `Users`.`password` AS `Users_password` FROM `users` `Users` WHERE ( `Users`.`email` = ? ) AND ( `Users`.`deletedAt` IS NULL ) LIMIT 1 -- PARAMETERS: ["test5@naver.com"]

Users {

  id: 5,

  email: 'test5@naver.com',

  nickname: '테스트1',

  password: '$2a$12$RXFoHQTpSF05vaQ.USsP7e2M15C7Mi/HhY.eHhy.x/gHQx.J6WHTu'

}

true ---> user.password와 로그인을 위해 입력 받은 비밀번호 비교 값이 동일한지 비교한 결과 값(result)

---------------- local.strategy.ts ----------------- async validate
소스코드와 console.log 부분

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

validate user { id: 5, email: 'test5@naver.com', nickname: '테스트1' }

------------- local-auth.guard.ts ------------- 소스코드와 console.log 부분

@Injectable()
export class LocalAuthGuard extends AuthGuard('local'){
    async canActivate(context: ExecutionContext): 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;
    }
}

login for cookie

위와 같이 출력됩니다.
위의 내용을 편집 없이 로그만 출력하면 아래와 같습니다.
--------------------- 시작 ---------------

query: SELECT `Users`.`id` AS `Users_id`, `Users`.`email` AS `Users_email`, `Users`.`nickname` AS `Users_nickname`, `Users`.`password` AS `Users_password` FROM `users` `Users` WHERE ( `Users`.`email` = ? ) AND ( `Users`.`deletedAt` IS NULL ) LIMIT 1 -- PARAMETERS: ["test5@naver.com"]

Users {

  id: 5,

  email: 'test5@naver.com',

  nickname: '테스트1',

  password: '$2a$12$RXFoHQTpSF05vaQ.USsP7e2M15C7Mi/HhY.eHhy.x/gHQx.J6WHTu'

}

true

validate user { id: 5, email: 'test5@naver.com', nickname: '테스트1' }

login for cookie

[Nest] 29836  - 2021. 09. 29. 오후 9:06:02   ERROR [ExceptionsHandler] Failed to serialize user into session

Error: Failed to serialize user into session

    at pass (D:\Slack\nest\dist\main.js:14934:19)

    at Authenticator.serializeUser (D:\Slack\nest\dist\main.js:14952:5)

    at SessionManager.logIn (D:\Slack\nest\dist\main.js:15240:8)

    at IncomingMessage.req.login.req.logIn (D:\Slack\nest\node_modules\passport\lib\http\request.js:50:33)

    at D:\Slack\nest\dist\main.js:13559:64

    at new Promise (<anonymous>)

    at LocalAuthGuard.<anonymous> (D:\Slack\nest\dist\main.js:13559:23)

    at Generator.next (<anonymous>)

    at D:\Slack\nest\dist\main.js:13516:71

  at new Promise (<anonymous>)

--------------------- 끝 ---------------
서버 구동 후 POSTMAN으로 로그인 을 시도하고 있는 상황입니다.

nak512님의 프로필

nak512

질문자

2021.09.29

안녕하세요, 제로초님. 결국 해결하였습니다.
아무리 들여다 봐도 코드상에는 이상이 없어서, 관련 모듈들 모두 재설치를 진행하였습니다.
그랬더니 문제가 해결되었어요. 감사합니다.

0

https://github.com/ZeroCho/sleact/blob/master/nest-typeorm/src/auth/local.serializer.ts#L18

여기에 console.log 찍은 건 어떻게 뜨시나요?