2020-04-05 14:31:49 +02:00
|
|
|
import Jwt from "jsonwebtoken";
|
2020-05-10 18:34:55 +02:00
|
|
|
import {SECRET_KEY, URL_ROOM_STARTED} from "../Enum/EnvironmentVariable"; //TODO fix import by "_Enum/..."
|
2020-04-10 12:54:05 +02:00
|
|
|
import { uuid } from 'uuidv4';
|
2020-09-28 18:52:54 +02:00
|
|
|
import {HttpRequest, HttpResponse, TemplatedApp} from "uWebSockets.js";
|
|
|
|
import {BaseController} from "./BaseController";
|
2020-04-04 17:22:02 +02:00
|
|
|
|
2020-06-09 23:07:19 +02:00
|
|
|
export interface TokenInterface {
|
|
|
|
name: string,
|
2020-09-18 13:57:38 +02:00
|
|
|
userUuid: string
|
2020-06-09 23:07:19 +02:00
|
|
|
}
|
|
|
|
|
2020-09-28 18:52:54 +02:00
|
|
|
export class AuthenticateController extends BaseController {
|
2020-04-04 17:22:02 +02:00
|
|
|
|
2020-09-28 18:52:54 +02:00
|
|
|
constructor(private App : TemplatedApp) {
|
|
|
|
super();
|
2020-04-04 17:22:02 +02:00
|
|
|
this.login();
|
|
|
|
}
|
|
|
|
|
2020-09-28 18:52:54 +02:00
|
|
|
onAbortedOrFinishedResponse(res: HttpResponse/*, readStream: any*/) {
|
|
|
|
|
|
|
|
console.log("ERROR! onAbortedOrFinishedResponse called!");
|
|
|
|
/*if (res.id == -1) {
|
|
|
|
console.log("ERROR! onAbortedOrFinishedResponse called twice for the same res!");
|
|
|
|
} else {
|
|
|
|
console.log('Stream was closed, openStreams: ' + --openStreams);
|
|
|
|
console.timeEnd(res.id);
|
|
|
|
readStream.destroy();
|
|
|
|
}*/
|
|
|
|
|
|
|
|
/* Mark this response already accounted for */
|
|
|
|
//res.id = -1;
|
|
|
|
}
|
|
|
|
|
2020-04-04 17:22:02 +02:00
|
|
|
//permit to login on application. Return token to connect on Websocket IO.
|
|
|
|
login(){
|
2020-09-28 18:52:54 +02:00
|
|
|
this.App.options("/login", (res: HttpResponse, req: HttpRequest) => {
|
|
|
|
this.addCorsHeaders(res);
|
|
|
|
|
|
|
|
res.end();
|
|
|
|
});
|
|
|
|
|
2020-09-29 16:12:17 +02:00
|
|
|
this.App.post("/login", (res: HttpResponse, req: HttpRequest) => {
|
|
|
|
(async () => {
|
|
|
|
this.addCorsHeaders(res);
|
|
|
|
|
|
|
|
res.onAborted(() => {
|
|
|
|
console.warn('Login request was aborted');
|
|
|
|
})
|
|
|
|
const param = await res.json();
|
|
|
|
const userUuid = uuid();
|
|
|
|
const token = Jwt.sign({name: param.name, userUuid: userUuid} as TokenInterface, SECRET_KEY, {expiresIn: '24h'});
|
|
|
|
res.writeStatus("200 OK").end(JSON.stringify({
|
|
|
|
token: token,
|
|
|
|
mapUrlStart: URL_ROOM_STARTED,
|
|
|
|
userId: userUuid,
|
|
|
|
}));
|
|
|
|
})();
|
2020-05-23 14:00:36 +02:00
|
|
|
});
|
2020-04-04 17:22:02 +02:00
|
|
|
}
|
2020-05-14 23:19:48 +02:00
|
|
|
}
|