W
Wasp-lang•9mo ago
jaan

WebSocket authentication

Hello this is maybe a stupid question, but looking at the websocket page in the docs I couldn't determine if there is a way (or maybe it already exists by default and it's just not mentioned) to restrict websocket connections to only authenticated users?
5 Replies
Vinny (@Wasp)
Vinny (@Wasp)•9mo ago
i would guess that you just look for the user on the socker.data object and if it doesn't exist, then throw an error:
// other imports
import { HttpError } from 'wasp/server'

export const webSocketFn: WebSocketFn = (io, context) => {
io.on('connection', (socket) => {
const username = getFirstProviderUserId(socket.data.user)
if (!username) {
throw new HttpError(
401, // status code
"No user found", // message
{ foo: 'bar' } // data (optional)
)
}

//...
})
}
// other imports
import { HttpError } from 'wasp/server'

export const webSocketFn: WebSocketFn = (io, context) => {
io.on('connection', (socket) => {
const username = getFirstProviderUserId(socket.data.user)
if (!username) {
throw new HttpError(
401, // status code
"No user found", // message
{ foo: 'bar' } // data (optional)
)
}

//...
})
}
maybe @miho knows a better way
jaan
jaanOP•9mo ago
Ah that makes sense actually 😅 Thanks!
Vinny (@Wasp)
Vinny (@Wasp)•9mo ago
yeah let me know if it works after you've given it a try
jaan
jaanOP•9mo ago
Well throwing an error seems like it just crashes the whole thing, but I remembered that I can just do socket.disconnect() instead of throwing an error
No description
Vinny (@Wasp)
Vinny (@Wasp)•9mo ago
ok cool. yeah, sorry, i don;t have much experience with websockets
Want results from more Discord servers?
Add your server