Added chat submodule and socketAuth middleware

This commit is contained in:
mrfry 2021-05-26 18:38:22 +02:00
parent a12aadf32d
commit 106bd88f17
2 changed files with 266 additions and 0 deletions

View file

@ -0,0 +1,54 @@
import logger from '../utils/logger'
import dbtools from '../utils/dbtools'
import cookie from 'cookie'
interface Options {
userDB: any
}
export default function (options: Options): any {
const { userDB } = options
return function (socket, next) {
const cookies = cookie.parse(socket.handshake.headers.cookie)
const sessionID = cookies.sessionID
if (process.env.NS_NOUSER) {
next()
return
}
if (!sessionID) {
next(new Error('Authentication error'))
return
}
const user = GetUserBySessionID(userDB, sessionID)
if (!user) {
next(new Error('Authentication error'))
return
}
next()
}
}
function GetUserBySessionID(db: any, sessionID: string) {
logger.DebugLog(`Getting user from db`, 'auth', 2)
const session = dbtools.Select(db, 'sessions', {
id: sessionID,
})[0]
if (!session) {
return
}
const user = dbtools.Select(db, 'users', {
id: session.userID,
})[0]
if (user) {
return user
}
}