mirror of
https://gitlab.com/comunic/comunicapiv2
synced 2024-11-22 05:19:22 +00:00
Generate access tokens
This commit is contained in:
parent
70a5c910d2
commit
eaa0e704bb
@ -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},
|
||||
|
@ -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) {
|
||||
|
||||
}
|
Loading…
Reference in New Issue
Block a user