| 1 | import type { IncomingMessage, Server } from 'http'; |
| 2 | |
| 3 | import type { ChargingStationData } from '../../types/ChargingStationWorker'; |
| 4 | import type { UIServerConfiguration } from '../../types/ConfigurationData'; |
| 5 | import { |
| 6 | AuthenticationType, |
| 7 | ProcedureName, |
| 8 | ProtocolRequest, |
| 9 | ProtocolResponse, |
| 10 | ProtocolVersion, |
| 11 | RequestPayload, |
| 12 | ResponsePayload, |
| 13 | } from '../../types/UIProtocol'; |
| 14 | import type AbstractUIService from './ui-services/AbstractUIService'; |
| 15 | |
| 16 | export abstract class AbstractUIServer { |
| 17 | public readonly chargingStations: Map<string, ChargingStationData>; |
| 18 | protected httpServer: Server; |
| 19 | protected readonly uiServices: Map<ProtocolVersion, AbstractUIService>; |
| 20 | |
| 21 | public constructor(protected readonly uiServerConfiguration: UIServerConfiguration) { |
| 22 | this.chargingStations = new Map<string, ChargingStationData>(); |
| 23 | this.uiServices = new Map<ProtocolVersion, AbstractUIService>(); |
| 24 | } |
| 25 | |
| 26 | public buildProtocolRequest( |
| 27 | id: string, |
| 28 | procedureName: ProcedureName, |
| 29 | requestPayload: RequestPayload |
| 30 | ): ProtocolRequest { |
| 31 | return [id, procedureName, requestPayload]; |
| 32 | } |
| 33 | |
| 34 | public buildProtocolResponse(id: string, responsePayload: ResponsePayload): ProtocolResponse { |
| 35 | return [id, responsePayload]; |
| 36 | } |
| 37 | |
| 38 | protected isBasicAuthEnabled(): boolean { |
| 39 | return ( |
| 40 | this.uiServerConfiguration.authentication?.enabled === true && |
| 41 | this.uiServerConfiguration.authentication?.type === AuthenticationType.BASIC_AUTH |
| 42 | ); |
| 43 | } |
| 44 | |
| 45 | protected isValidBasicAuth(req: IncomingMessage): boolean { |
| 46 | const authorizationHeader = req.headers.authorization ?? ''; |
| 47 | const authorizationToken = authorizationHeader.split(/\s+/).pop() ?? ''; |
| 48 | const authentication = Buffer.from(authorizationToken, 'base64').toString(); |
| 49 | const authenticationParts = authentication.split(/:/); |
| 50 | const username = authenticationParts.shift(); |
| 51 | const password = authenticationParts.join(':'); |
| 52 | return ( |
| 53 | this.uiServerConfiguration.authentication?.username === username && |
| 54 | this.uiServerConfiguration.authentication?.password === password |
| 55 | ); |
| 56 | } |
| 57 | |
| 58 | public abstract start(): void; |
| 59 | public abstract stop(): void; |
| 60 | public abstract sendRequest(request: ProtocolRequest): void; |
| 61 | public abstract sendResponse(response: ProtocolResponse): void; |
| 62 | public abstract logPrefix( |
| 63 | moduleName?: string, |
| 64 | methodName?: string, |
| 65 | prefixSuffix?: string |
| 66 | ): string; |
| 67 | } |