53 lines
1.7 KiB
TypeScript
53 lines
1.7 KiB
TypeScript
import jwt from "jsonwebtoken";
|
|
import BadRequestException from "../exceptions/badRequestException";
|
|
import InternalException from "../exceptions/internalException";
|
|
import UnauthorizedRequestException from "../exceptions/unauthorizedRequestException";
|
|
import { JWTHelper } from "../helpers/jwtHelper";
|
|
import { SocketMap } from "../storage/socketMap";
|
|
import { Socket } from "socket.io";
|
|
|
|
export default async function authenticateSocket(socket: Socket, next: Function) {
|
|
try {
|
|
const token = socket.handshake.auth.token;
|
|
|
|
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);
|
|
}
|
|
});
|
|
|
|
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,
|
|
firstname: decoded.firstname,
|
|
lastname: decoded.lastname,
|
|
isOwner: decoded.isOwner,
|
|
permissions: decoded.permissions,
|
|
isWebApiRequest: decoded?.sub == "webapi_access_token",
|
|
});
|
|
|
|
next();
|
|
} catch (err) {
|
|
next(err);
|
|
}
|
|
}
|