add basic socketio to server
This commit is contained in:
parent
45ec6b856a
commit
b29cdae088
8 changed files with 252 additions and 1 deletions
54
src/middleware/authenticateSocket.ts
Normal file
54
src/middleware/authenticateSocket.ts
Normal file
|
@ -0,0 +1,54 @@
|
|||
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",
|
||||
});
|
||||
socket.join("home");
|
||||
|
||||
next();
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
}
|
11
src/middleware/checkSocketExists.ts
Normal file
11
src/middleware/checkSocketExists.ts
Normal file
|
@ -0,0 +1,11 @@
|
|||
import { Event, Socket } from "socket.io";
|
||||
import UnauthorizedRequestException from "../exceptions/unauthorizedRequestException";
|
||||
import { SocketMap } from "../storage/socketMap";
|
||||
|
||||
export default async (socket: Socket, [event, ...args]: Event, next: any) => {
|
||||
if (SocketMap.exists(socket.id)) {
|
||||
next();
|
||||
} else {
|
||||
next(new UnauthorizedRequestException("not authorized for connection"));
|
||||
}
|
||||
};
|
Loading…
Add table
Add a link
Reference in a new issue