06db5a47109f2c11b77eb938021748d86968eaf5
[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 (UIServiceUtils.isProtocolSupported(protocol, version) === true) {
27 return fullProtocol;
28 }
29 }
30 logger.error(
31 `${Utils.logPrefix(
32 ' UI WebSocket Server |'
33 )} Unsupported protocol: ${protocol} or protocol version: ${version}`
34 );
35 return false;
36 };
37
38 public static isProtocolSupported = (protocol: Protocol, version: ProtocolVersion): boolean =>
39 Object.values(Protocol).includes(protocol) && Object.values(ProtocolVersion).includes(version);
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 }