diff --git a/src/websocket/middleware/authenticateSocket.ts b/src/websocket/middleware/authenticateSocket.ts index adf4441..2899914 100644 --- a/src/websocket/middleware/authenticateSocket.ts +++ b/src/websocket/middleware/authenticateSocket.ts @@ -7,42 +7,46 @@ import { Socket } from "socket.io"; import { SocketMap } from "../../storage/socketMap"; export default async function authenticateSocket(socket: Socket, next: Function) { - const token = socket.handshake.auth.token; + try { + const token = socket.handshake.auth.token; - if (!token) { - throw new BadRequestException("Provide valid Authorization Header"); - } + if (!token) { + throw new BadRequestException("Provide valid Authorization Header"); + } - let decoded: string | jwt.JwtPayload; - await JWTHelper.validate(token) - .then((result) => { - decoded = result; - }) - .catch((err) => { - if (err == "jwt expired") { - throw new UnauthorizedRequestException("Token expired", err); - } else { - throw new BadRequestException("Failed Authorization Header decoding", err); - } + let decoded: string | jwt.JwtPayload; + await JWTHelper.validate(token) + .then((result) => { + decoded = result; + }) + .catch((err) => { + if (err == "jwt expired") { + throw new UnauthorizedRequestException("Token expired", err); + } else { + throw new BadRequestException("Failed Authorization Header decoding", err); + } + }); + + if (typeof decoded == "string" || !decoded) { + throw new InternalException("process failed"); + } + + if (decoded?.sub == "api_token_retrieve") { + throw new BadRequestException("This token is only authorized to get temporary access tokens via GET /api/webapi"); + } + + SocketMap.write(socket.id, { + socketId: socket.id, + userId: decoded.userId, + username: decoded.username, + isOwner: decoded.isOwner, + permissions: decoded.permissions, + isWebApiRequest: decoded?.sub == "webapi_access_token", }); + socket.join("home"); - if (typeof decoded == "string" || !decoded) { - throw new InternalException("process failed"); + next(); + } catch (err) { + next(err); } - - if (decoded?.sub == "api_token_retrieve") { - throw new BadRequestException("This token is only authorized to get temporary access tokens via GET /api/webapi"); - } - - SocketMap.write(socket.id, { - socketId: socket.id, - userId: decoded.userId, - username: decoded.username, - isOwner: decoded.isOwner, - permissions: decoded.permissions, - isWebApiRequest: decoded?.sub == "webapi_access_token", - }); - socket.join("home"); - - next(); }