Last active
November 1, 2021 23:22
-
-
Save alex-hladun/9977e00606237a32dee802ac9ec9f368 to your computer and use it in GitHub Desktop.
Auth middleware for socket
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
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