import { WebSocketGateway , SubscribeMessage , WsResponse , WebSocketServer , NestGateway } from '@nestjs/websockets' ; import * as cookie from 'cookie' ; import { Observable , of } from 'rxjs' ; import { map } from 'rxjs/operators' ; import { SecurityService } from '../../common/security/security.service' ; import { AuthCache } from '../auth.cache' ; @ WebSocketGateway ( { namespace : 'api/auth/gateway' , port : 8001 } ) export class AuthGateway implements NestGateway { requiredRolesForGateway = [ 'anon' , 'user' ] ; recentlyCreatedAnonEvent = 'recently-created-anon' ; constructor ( private readonly authCache , private readonly securityService ) { } @ WebSocketServer ( ) server ; async handleConnection ( client ) { const parsedCookies = cookie . parse ( client . request . headers . cookie ) ; const userCookie = parsedCookies [ 'SESSIONID' ] ; if ( ! userCookie ) { return client . disconnect ( ) ; } const user = await this . securityService . decodeJwt ( userCookie ) ; const canAccess = this . roleGuard ( user . roles , this . requiredRolesForGateway ) ; if ( ! canAccess ) { return client . disconnect ( ) ; } client . user = user ; } @ SubscribeMessage ( 'recently-created-anon' ) onRecentlyCreatedAnon ( client , data ) { return this . authCache . wsObservable . pipe ( map ( res => ( { event : this . recentlyCreatedAnonEvent , data : res } ) ) ) ; } private roleGuard ( roles , requiredRoles ) { return ! ! roles . find ( role => ! ! requiredRoles . find ( item => item === role ) ) ; } }