Skip to content

Instantly share code, notes, and snippets.

@alex-hladun
Last active November 1, 2021 23:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alex-hladun/9977e00606237a32dee802ac9ec9f368 to your computer and use it in GitHub Desktop.
Save alex-hladun/9977e00606237a32dee802ac9ec9f368 to your computer and use it in GitHub Desktop.
Auth middleware for socket
class SocketManager {
io: SocketIO.Server;
pubClient: redis.RedisClient;
sessionStore: RedisSessionStore;
serverConfig: IServerConfig;
redisEnabled: boolean;
dynamoEnabled: boolean;
constructor(server: http.Server, config: IServerConfig) {
this.configureMiddleware();
}
configureMiddleware = () => {
this.io.use(async (socket: ICustomSocket, next) => {
const sessionId = socket.handshake.auth.sessionId;
if (sessionId && this.redisEnabled) {
const session = await this.sessionStore.findSession(sessionId);
if (session) {
socket.sessionId = sessionId;
socket.username = session.username;
return next();
}
}
const username = socket.handshake.auth.username;
if (!username) {
return next(new Error("invalid username"));
}
socket.sessionId = v4();
socket.username = username;
next();
});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment