From 2236b445d94753f66446abde073eef9b17a9dc13 Mon Sep 17 00:00:00 2001 From: Nisarg Jhaveri Date: Sun, 1 Sep 2024 23:46:38 +0530 Subject: [PATCH] Add extensible ServerConfiguration in server interface --- src/server/command.ts | 4 +++- src/server/server.ts | 22 +++++++++++++--------- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/src/server/command.ts b/src/server/command.ts index 915f3f2..5392011 100644 --- a/src/server/command.ts +++ b/src/server/command.ts @@ -61,6 +61,8 @@ export const commandServer = { const listenOptions = { port: args.port, host: args.host }; - new Server(listenOptions, httpsOptions, args.password).start(); + new Server(listenOptions, httpsOptions, { + password: args.password + }).start(); } } as CommandModule; diff --git a/src/server/server.ts b/src/server/server.ts index 499cf95..c057e58 100644 --- a/src/server/server.ts +++ b/src/server/server.ts @@ -18,27 +18,31 @@ declare module 'express-session' { } } +export type ServerConfiguration = { + password?: string; +} + export class Server { private listenOptions: net.ListenOptions; - private httpsOptions: https.ServerOptions; - private password: string|undefined; + private httpsOptions: https.ServerOptions|undefined; + private serverConfig: ServerConfiguration|undefined; private serverAddress: net.AddressInfo; private server: (http.Server|https.Server) & stoppable.WithStop; private wsKeepaliveInterval: NodeJS.Timer = undefined; - constructor(listenOptions: net.ListenOptions, httpsOptions?: https.ServerOptions, password?: string) { + constructor(listenOptions: net.ListenOptions, httpsOptions?: https.ServerOptions, serverConfig?: ServerConfiguration) { this.listenOptions = listenOptions; this.httpsOptions = httpsOptions; - this.password = password + this.serverConfig = serverConfig } private get loginSupported() { - return !!this.password; + return !!this.serverConfig?.password; } - private loginRequried(req: Request) { + private loginRequired(req: Request) { return this.loginSupported && !req.session.userId; } @@ -67,13 +71,13 @@ export class Server { res.json({ result: "OK", loginSupported: this.loginSupported, - loginRequired: this.loginRequried(req) + loginRequired: this.loginRequired(req) }); res.end(); }); app.post('/login', (req, res) => { - if (!this.loginSupported || req.body.password === this.password) { + if (!this.loginSupported || req.body.password === this.serverConfig.password) { req.session.regenerate(() => { req.session.userId = "user"; @@ -110,7 +114,7 @@ export class Server { server.on('upgrade', (request: any, socket: net.Socket, head) => { // This function is not defined on purpose. Implement it with your own logic. sessionParser(request, {} as any, () => { - if (this.loginRequried(request)) { + if (this.loginRequired(request)) { socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n'); socket.destroy(); return;