UI Protocol: add Authorize command support
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / ui-services / UIServiceUtils.ts
index 974d6fc4fb0ac16be896e62f4a43fbd06685437e..c019982854c22d73bcc446ca3a2ecc56caa1aca1 100644 (file)
@@ -1,8 +1,8 @@
-import { Protocol, ProtocolVersion } from '../../../types/UIProtocol';
+import type { IncomingMessage } from 'http';
 
-import { IncomingMessage } from 'http';
-import Utils from '../../../utils/Utils';
+import { Protocol, ProtocolVersion } from '../../../types/UIProtocol';
 import logger from '../../../utils/Logger';
+import Utils from '../../../utils/Utils';
 
 export class UIServiceUtils {
   private constructor() {
@@ -13,31 +13,41 @@ export class UIServiceUtils {
     protocols: Set<string>,
     request: IncomingMessage
   ): string | false => {
-    let protocolIndex: number;
     let protocol: Protocol;
     let version: ProtocolVersion;
+    if (protocols.size === 0) {
+      return false;
+    }
     for (const fullProtocol of protocols) {
-      protocolIndex = fullProtocol.indexOf(Protocol.UI);
-      protocol = fullProtocol.substring(
-        protocolIndex,
-        protocolIndex + Protocol.UI.length
-      ) as Protocol;
-      version = fullProtocol.substring(protocolIndex + Protocol.UI.length) as ProtocolVersion;
-      if (
-        Object.values(Protocol).includes(protocol) &&
-        Object.values(ProtocolVersion).includes(version)
-      ) {
+      [protocol, version] = UIServiceUtils.getProtocolAndVersion(fullProtocol);
+      if (UIServiceUtils.isProtocolAndVersionSupported(protocol, version) === true) {
         return fullProtocol;
       }
     }
     logger.error(
       `${Utils.logPrefix(
-        ' UI WebSocket Server:'
+        ' UI WebSocket Server |'
       )} Unsupported protocol: ${protocol} or protocol version: ${version}`
     );
     return false;
   };
 
+  public static isProtocolAndVersionSupported = (
+    protocol: Protocol,
+    version: ProtocolVersion
+  ): boolean =>
+    Object.values(Protocol).includes(protocol) && Object.values(ProtocolVersion).includes(version);
+
+  public static getProtocolAndVersion = (protocolStr: string): [Protocol, ProtocolVersion] => {
+    const protocolIndex = protocolStr.indexOf(Protocol.UI);
+    const protocol = protocolStr.substring(
+      protocolIndex,
+      protocolIndex + Protocol.UI.length
+    ) as Protocol;
+    const version = protocolStr.substring(protocolIndex + Protocol.UI.length) as ProtocolVersion;
+    return [protocol, version];
+  };
+
   public static isLoopback(address: string): boolean {
     const isLoopbackRegExp = new RegExp(
       // eslint-disable-next-line no-useless-escape