@@ -8,17 +8,22 @@ import { getUserNames } from './helpers/defaultRoleGenerator';
8
8
interface CustomSocket extends Socket {
9
9
userId ?: string ;
10
10
}
11
- export const findId = ( socket : CustomSocket ) => {
11
+ export const findId = async ( socket : CustomSocket ) => {
12
12
try {
13
13
const { token } = socket . handshake . auth ;
14
+ if ( ! token ) {
15
+ socket . disconnect ( ) ;
16
+ return ;
17
+ }
14
18
const decoded = decodedToken ( token ) ;
15
19
const id = typeof decoded === 'string' ? decoded : decoded ? decoded . id : null ;
16
20
if ( typeof id === 'string' ) {
17
- socket . emit ( 'sendUserId' , id ) ;
21
+ await socket . emit ( 'sendUserId' , id ) ;
18
22
socket . userId = id ;
19
23
return id ;
20
24
} else {
21
- throw new Error ( 'Token is not a string' ) ;
25
+ // throw new Error('Token is not a string');
26
+ logger . error ( 'No Token Provided!' ) ;
22
27
}
23
28
} catch ( error ) {
24
29
logger . error ( 'Error find Id' , error ) ;
@@ -39,7 +44,6 @@ const sentMessage = async (socket: CustomSocket, data: Message, io: Server) => {
39
44
if ( senderId ) {
40
45
try {
41
46
const { content } = data ;
42
- console . log ( '--------------messages are here,' , data ) ;
43
47
const { firstName } = await getUserNames ( socket . userId as string ) ;
44
48
45
49
const chat = await Chat . create ( { senderId, content } ) ;
@@ -74,9 +78,19 @@ export const socketSetUp = (server: HttpServer) => {
74
78
} ) ;
75
79
// eslint-disable-next-line @typescript-eslint/no-misused-promises
76
80
io . use ( async ( socket : CustomSocket , next ) => {
77
- const id = findId ( socket ) ;
78
- socket . userId = id ;
79
- next ( ) ;
81
+ try {
82
+ const id = await findId ( socket ) ;
83
+ if ( typeof id === 'undefined' || id . length < 2 ) {
84
+ socket . disconnect ( ) ;
85
+ return ;
86
+ }
87
+ socket . userId = id ;
88
+ next ( ) ;
89
+ } catch ( err ) {
90
+ const error = err as Error ;
91
+ logger . error ( error . stack ) ;
92
+ next ( error ) ;
93
+ }
80
94
} ) ;
81
95
82
96
io . on ( 'connection' , async ( socket : CustomSocket ) => {
0 commit comments