cf89b0c60598c2625b691288b144819c9e52c209
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / ui-services / UIServiceUtils.ts
1 import { IncomingMessage } from 'http';
2
3 import { Protocol, ProtocolVersion } from '../../../types/UIProtocol';
4 import logger from '../../../utils/Logger';
5 import Utils from '../../../utils/Utils';
6
7 export class UIServiceUtils {
8 private constructor() {
9 // This is intentional
10 }
11
12 public static handleProtocols = (
13 protocols: Set<string>,
14 request: IncomingMessage
15 ): string | false => {
16 let protocolIndex: number;
17 let protocol: Protocol;
18 let version: ProtocolVersion;
19 for (const fullProtocol of protocols) {
20 protocolIndex = fullProtocol.indexOf(Protocol.UI);
21 protocol = fullProtocol.substring(
22 protocolIndex,
23 protocolIndex + Protocol.UI.length
24 ) as Protocol;
25 version = fullProtocol.substring(protocolIndex + Protocol.UI.length) as ProtocolVersion;
26 if (
27 Object.values(Protocol).includes(protocol) &&
28 Object.values(ProtocolVersion).includes(version)
29 ) {
30 return fullProtocol;
31 }
32 }
33 logger.error(
34 `${Utils.logPrefix(
35 ' UI WebSocket Server |'
36 )} Unsupported protocol: ${protocol} or protocol version: ${version}`
37 );
38 return false;
39 };
40
41 public static isLoopback(address: string): boolean {
42 const isLoopbackRegExp = new RegExp(
43 // eslint-disable-next-line no-useless-escape
44 /^localhost$|^127(?:\.\d+){0,2}\.\d+$|^(?:0*\:)*?:?0*1$/,
45 'i'
46 );
47 return isLoopbackRegExp.test(address);
48 }
49 }