Last active
March 20, 2020 19:07
-
-
Save mmontes11/7352d144c26f1ae75c8d388821bbf025 to your computer and use it in GitHub Desktop.
Backend Socket.io middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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