diff --git a/src/controllers/Routes.ts b/src/controllers/Routes.ts index 38cf6bd..e5da1b6 100644 --- a/src/controllers/Routes.ts +++ b/src/controllers/Routes.ts @@ -18,7 +18,7 @@ import { SurveyController } from "./SurveyController"; import { SettingsController } from "./SettingsController"; import { Request } from "express"; import * as ws from 'ws'; -import { UserWS } from "./UserWebSocketController"; +import { UserWebSocketController } from "./UserWebSocketController"; /** * Controllers routes @@ -45,7 +45,9 @@ export interface Route { export const Routes : Route[] = [ // Main user websocket - {type: RouteType.WS, path: "/ws", cb: () => {throw Error()}, wsCallback: UserWS }, + {path: "/ws/token", cb: (h) => UserWebSocketController.GetToken(h)}, + + {type: RouteType.WS, path: "/ws", cb: () => {throw Error()}, wsCallback: (r, w) => UserWebSocketController.UserWS(r, w) }, // Welcome controller {type: RouteType.GET, path: "/", cb: WelcomeController.HomeMessage, needLogin: false}, diff --git a/src/controllers/UserWebSocketController.ts b/src/controllers/UserWebSocketController.ts index 74675b1..6d08035 100644 --- a/src/controllers/UserWebSocketController.ts +++ b/src/controllers/UserWebSocketController.ts @@ -5,7 +5,67 @@ */ import * as ws from 'ws'; import { Request } from 'express'; +import { RequestHandler } from '../entities/RequestHandler'; +import { time } from '../utils/DateUtils'; +import { randomStr } from '../utils/CryptUtils'; + +interface PendingRequests { + time: number, + userID: number, + token: string +} + +// Tokens are valid only 10 seconds after they are generated +const TOKENS_DURATION = 10 + +export class UserWebSocketController { + + /** + * The list of pending connections + */ + static pending_list: PendingRequests[] = [] + + /** + * Clean the list of tokens + */ + private static CleanList() { + // Clean the list + this.pending_list = this.pending_list + .filter((l) => l.time + TOKENS_DURATION + 1 > time()) + } + + /** + * Get a websocket access token + * + * @param h Request handler + */ + public static async GetToken(h: RequestHandler) { + this.CleanList(); + + // Generate a temporary token + const token = randomStr(20); + + // Add the token to the list + this.pending_list.push({ + time: time(), + userID: h.getUserId(), + token: token + }); + + h.send({ + token: token + }); + } + + /** + * Handler user websocket request + * + * @param req Associated request + * @param ws The socket + */ + public static async UserWS(req: Request, ws: ws) { + this.CleanList(); + } + +} -export async function UserWS(req: Request, ws: ws) { - -} \ No newline at end of file