Skip to content

Instantly share code, notes, and snippets.

@mmontes11
Last active March 20, 2020 19:07
Show Gist options
  • Save mmontes11/7352d144c26f1ae75c8d388821bbf025 to your computer and use it in GitHub Desktop.
Save mmontes11/7352d144c26f1ae75c8d388821bbf025 to your computer and use it in GitHub Desktop.
Backend Socket.io middleware
import SocketIO from "socket.io";
import jwt from "jsonwebtoken";
import _ from "underscore";
import { logError } from "../utils/log";
import { ThingModel } from "../models/thing";
export const setupSocketIO = server => {
const io = new SocketIO(server);
io.use(async (socket, next) => {
const {
handshake: {
query: { token, thing: thingName, type },
},
} = socket;
if (_.isUndefined(token)) {
const tokenError = new Error("No token provided");
logError(tokenError);
return next(tokenError);
}
try {
if (jwt.verify(token, process.env.BACK_JWT_SECRET)) {
if (_.isUndefined(thingName)) {
const thingError = new Error("No thing provided");
logError(thingError);
return next(thingError);
}
const thing = await ThingModel.findThingByName(thingName);
if (_.isUndefined(thing) || _.isNull(thing)) {
const thingNotFoundError = new Error("Thing not found");
logError(thingNotFoundError);
return next(thingNotFoundError);
}
socket.token = token;
socket.thing = thing;
socket.type = type;
return next();
}
const authError = new Error("Auth error");
logError(authError);
return next(authError);
} catch (err) {
logError(err);
return next(err);
}
});
return io;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment