server/src/middleware/authentication.ts

48 lines
1.3 KiB
TypeScript

import { verify } from 'jsonwebtoken'
import { TSocket } from '../utilities/types'
import config from '../utilities/config'
import UserRepository from '../repositories/userRepository'
import { User } from '@prisma/client'
import { gameLogger } from '../utilities/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'))
}
/**
* Parse cookies
*/
const cookies = socket.request.headers.cookie.split('; ').reduce((prev: any, current: any) => {
const [name, value] = current.split('=')
prev[name] = value
return prev
}, {})
const token = cookies['token']
/**
* Verify token, if valid, set user on socket and continue
*/
if (token) {
verify(token, config.JWT_SECRET, async (err: any, decoded: any) => {
if (err) {
gameLogger.error('Invalid token')
return next(new Error('Authentication error'))
}
socket.user = (await UserRepository.getById(decoded.id)) as User
next()
})
} else {
gameLogger.warn('No token provided')
return next(new Error('Authentication error'))
}
}