mirror of
https://gitlab.com/MrFry/mrfrys-node-server
synced 2025-04-01 20:24:18 +02:00
Added chat submodule and socketAuth middleware
This commit is contained in:
parent
a12aadf32d
commit
106bd88f17
2 changed files with 266 additions and 0 deletions
54
src/middlewares/socketAuth.middleware.ts
Normal file
54
src/middlewares/socketAuth.middleware.ts
Normal 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
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue