import { CanActivate , ExecutionContext , Injectable } from '@nestjs/common' ; import { Observable , of } from 'rxjs' ; import { map , switchMap } from 'rxjs/operators' ; import { AuthService } from '../auth/auth.service' ; import { ReqWithUser } from '../interfaces/req-with-user.interface' ; @ Injectable ( ) export class CookieGuard implements CanActivate { constructor ( private readonly authService ) { } canActivate ( context ) { const req = context . switchToHttp ( ) . getRequest < ReqWithUser > ( ) ; const { 'session.id' : cookie = '' , 'session.refresh' : refresh = '' , } = req . cookies ; let refreshed = false ; return this . authService . getUserByCookie ( cookie ) . pipe ( switchMap ( ( user ) => { if ( user ) { return of ( user ) ; } refreshed = true ; return this . authService . getUserByCookie ( refresh ) ; } ) , switchMap ( ( user ) => { if ( ! user ) { return of ( false ) ; } const { password , ... reqUser } = user ; req . user = reqUser ; if ( refreshed ) { return this . authService . refreshSession ( req , user ) ; } return of ( user ) ; } ) , map ( ( user ) => { if ( ! user ) { return false ; } return true ; } ) ) ; } }