server/src/middleware/authentication.ts
2025-02-07 20:07:36 +01:00

58 lines
1.5 KiB
TypeScript

import jwt from 'jsonwebtoken'
import config from '#application/config'
import Logger, { LoggerType } from '#application/logger'
import { TSocket } from '#application/types'
class SocketAuthenticator {
private socket: TSocket
private readonly next: any
private readonly logger = Logger.type(LoggerType.APP)
constructor(socket: TSocket, next: any) {
this.socket = socket
this.next = next
}
public async authenticate(): Promise<void> {
if (!this.socket.request.headers.cookie) {
this.logger.warn('No cookie provided')
return this.next(new Error('Authentication error'))
}
const token = this.parseCookies()['token']
if (!token) {
this.logger.warn('No token provided')
return this.next(new Error('Authentication error'))
}
this.verifyToken(token)
}
private parseCookies(): Record<string, string> {
return this.socket.request.headers.cookie.split('; ').reduce((prev: any, current: any) => {
const [name, value] = current.split('=')
prev[name] = value
return prev
}, {})
}
private verifyToken(token: string): void {
jwt.verify(token, config.JWT_SECRET, (err: any, decoded: any) => {
if (err) {
this.logger.error('Invalid token')
return this.next(new Error('Authentication error'))
}
this.socket.userId = decoded.id
this.next()
})
}
}
export async function Authentication(socket: TSocket, next: any) {
const authenticator = new SocketAuthenticator(socket, next)
await authenticator.authenticate()
}