ca53d558894c5db16449d8534ebc0770307dbea7
1 import { type IncomingMessage
, Server
, type ServerResponse
} from
'node:http';
3 import type { WebSocket
} from
'ws';
7 type ChargingStationData
,
10 type ProtocolResponse
,
14 type UIServerConfiguration
,
16 import { type AbstractUIService
, UIServiceFactory
} from
'../internal';
18 export abstract class AbstractUIServer
{
19 public readonly chargingStations
: Map
<string, ChargingStationData
>;
20 protected readonly httpServer
: Server
;
21 protected readonly responseHandlers
: Map
<string, ServerResponse
| WebSocket
>;
22 protected readonly uiServices
: Map
<ProtocolVersion
, AbstractUIService
>;
24 public constructor(protected readonly uiServerConfiguration
: UIServerConfiguration
) {
25 this.chargingStations
= new Map
<string, ChargingStationData
>();
26 this.httpServer
= new Server();
27 this.responseHandlers
= new Map
<string, ServerResponse
| WebSocket
>();
28 this.uiServices
= new Map
<ProtocolVersion
, AbstractUIService
>();
31 public buildProtocolRequest(
33 procedureName
: ProcedureName
,
34 requestPayload
: RequestPayload
36 return [id
, procedureName
, requestPayload
];
39 public buildProtocolResponse(id
: string, responsePayload
: ResponsePayload
): ProtocolResponse
{
40 return [id
, responsePayload
];
44 this.chargingStations
.clear();
47 protected startHttpServer(): void {
48 if (this.httpServer
.listening
=== false) {
49 this.httpServer
.listen(this.uiServerConfiguration
.options
);
53 protected registerProtocolVersionUIService(version
: ProtocolVersion
): void {
54 if (this.uiServices
.has(version
) === false) {
55 this.uiServices
.set(version
, UIServiceFactory
.getUIServiceImplementation(version
, this));
59 protected authenticate(req
: IncomingMessage
, next
: (err
?: Error) => void): void {
60 if (this.isBasicAuthEnabled() === true) {
61 if (this.isValidBasicAuth(req
) === false) {
62 next(new Error('Unauthorized'));
69 private isBasicAuthEnabled(): boolean {
71 this.uiServerConfiguration
.authentication
?.enabled
=== true &&
72 this.uiServerConfiguration
.authentication
?.type === AuthenticationType
.BASIC_AUTH
76 private isValidBasicAuth(req
: IncomingMessage
): boolean {
77 const authorizationHeader
= req
.headers
.authorization
?? '';
78 const authorizationToken
= authorizationHeader
.split(/\s
+/).pop() ?? '';
79 const authentication
= Buffer
.from(authorizationToken
, 'base64').toString();
80 const authenticationParts
= authentication
.split(/:/);
81 const username
= authenticationParts
.shift();
82 const password
= authenticationParts
.join(':');
84 this.uiServerConfiguration
.authentication
?.username
=== username
&&
85 this.uiServerConfiguration
.authentication
?.password
=== password
89 public abstract start(): void;
90 public abstract sendRequest(request
: ProtocolRequest
): void;
91 public abstract sendResponse(response
: ProtocolResponse
): void;
92 public abstract logPrefix(