1
0
forked from noxious/server

Converted more procedural programming to OOP

This commit is contained in:
2024-12-26 23:34:25 +01:00
parent b7f448cb17
commit e571cf2230
46 changed files with 449 additions and 382 deletions

View File

@ -1,47 +1,55 @@
import { verify } from 'jsonwebtoken'
import { TSocket } from '#application/types'
import config from '#application/config'
import UserRepository from '#repositories/userRepository'
import { User } from '@prisma/client'
import { gameLogger } from '#application/logger'
/**
* Socket io jwt auth middleware
* @param socket
* @param next
*/
export async function Authentication(socket: TSocket, next: any) {
if (!socket.request.headers.cookie) {
gameLogger.warn('No cookie provided')
return next(new Error('Authentication error'))
export class SocketAuthenticator {
private socket: TSocket
private readonly next: any
constructor(socket: TSocket, next: any) {
this.socket = socket
this.next = next
}
/**
* Parse cookies
*/
const cookies = socket.request.headers.cookie.split('; ').reduce((prev: any, current: any) => {
const [name, value] = current.split('=')
prev[name] = value
return prev
}, {})
public async authenticate(): Promise<void> {
if (!this.socket.request.headers.cookie) {
gameLogger.warn('No cookie provided')
return this.next(new Error('Authentication error'))
}
const token = cookies['token']
const token = this.parseCookies()['token']
/**
* Verify token, if valid, set user on socket and continue
*/
if (token) {
verify(token, config.JWT_SECRET, async (err: any, decoded: any) => {
if (!token) {
gameLogger.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 {
verify(token, config.JWT_SECRET, (err: any, decoded: any) => {
if (err) {
gameLogger.error('Invalid token')
return next(new Error('Authentication error'))
return this.next(new Error('Authentication error'))
}
socket.userId = decoded.id
next()
this.socket.userId = decoded.id
this.next()
})
} else {
gameLogger.warn('No token provided')
return next(new Error('Authentication error'))
}
}
export async function Authentication(socket: TSocket, next: any) {
const authenticator = new SocketAuthenticator(socket, next)
await authenticator.authenticate()
}