1
0
mirror of https://gitlab.com/comunic/comunicapiv2 synced 2024-11-22 05:19:22 +00:00

Generate access tokens

This commit is contained in:
Pierre HUBERT 2020-03-29 18:22:54 +02:00
parent 70a5c910d2
commit eaa0e704bb
2 changed files with 67 additions and 5 deletions

View File

@ -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},

View File

@ -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) {
}