mirror of
https://gitlab.com/MrFry/mrfrys-node-server
synced 2026-04-28 03:07:38 +02:00
55 lines
1013 B
TypeScript
55 lines
1013 B
TypeScript
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
|
|
}
|
|
}
|