import * as ip from 'ip' ; import { Request , Response , NextFunction } from 'express' ; import { ErrorWithStatus } from './errors' ; const defualtOption = { whiteList : [ ] } ; const checkIpInList = ( list , addr ) : boolean => { let entry ; for ( const value of list ) { entry = value ; if ( ip . isV4Format ( entry ) ) { entry += '/32' ; } try { entry = ip . cidrSubnet ( entry ) ; if ( entry . contains ( addr ) ) { return true ; } } catch ( err ) { console . error ( 'CheckIpInList:' , err . toString ( ) ) ; } } return false ; } ; export const whiteListMiddleware = ( { whiteList , } = defualtOption ) => ( req , _res , next ) : void => { if ( whiteList . length === 0 || checkIpInList ( whiteList , req . ip ) ) { next ( ) ; return ; } next ( new ErrorWithStatus ( 'Access Denied' , 401 ) ) ; } ;