fix: WebSocket cookie auth + connect on layout mount
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import { useEffect } from 'react';
|
||||
import { Link, Outlet, useLocation, useNavigate } from 'react-router-dom';
|
||||
import { useAuthStore } from '../stores/auth.ts';
|
||||
import { useWebSocketStore } from '../stores/ws.ts';
|
||||
import { ServerBar } from './ServerBar.tsx';
|
||||
import { ChannelList } from './ChannelList.tsx';
|
||||
import { MemberList } from './MemberList.tsx';
|
||||
@@ -12,12 +13,16 @@ export function Layout() {
|
||||
const user = useAuthStore((state) => state.user);
|
||||
const fetchMe = useAuthStore((state) => state.fetchMe);
|
||||
const logout = useAuthStore((state) => state.logout);
|
||||
const wsConnect = useWebSocketStore((s) => s.connect);
|
||||
const wsDisconnect = useWebSocketStore((s) => s.disconnect);
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
|
||||
useEffect(() => {
|
||||
fetchMe();
|
||||
}, [fetchMe]);
|
||||
wsConnect();
|
||||
return () => { wsDisconnect(); };
|
||||
}, [fetchMe, wsConnect, wsDisconnect]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoading && !isAuthenticated && location.pathname !== '/login') {
|
||||
|
||||
@@ -19,7 +19,7 @@ export interface WsEvent {
|
||||
interface WebSocketState {
|
||||
socket: WebSocket | null;
|
||||
connected: boolean;
|
||||
connect: (token: string) => void;
|
||||
connect: () => void;
|
||||
disconnect: () => void;
|
||||
send: (event: WsEvent) => void;
|
||||
}
|
||||
@@ -64,7 +64,7 @@ export const useWebSocketStore = create<WebSocketState>((set, get) => ({
|
||||
socket: null,
|
||||
connected: false,
|
||||
|
||||
connect: (token: string) => {
|
||||
connect: () => {
|
||||
const existing = get().socket;
|
||||
if (existing && (existing.readyState === WebSocket.OPEN || existing.readyState === WebSocket.CONNECTING)) {
|
||||
return;
|
||||
@@ -82,14 +82,15 @@ export const useWebSocketStore = create<WebSocketState>((set, get) => ({
|
||||
}
|
||||
reconnectTimeout = window.setTimeout(() => {
|
||||
if (!get().connected) {
|
||||
get().connect(token);
|
||||
get().connect();
|
||||
}
|
||||
}, reconnectDelay);
|
||||
reconnectDelay = Math.min(reconnectDelay * 2, maxReconnectDelay);
|
||||
};
|
||||
|
||||
socket.onopen = () => {
|
||||
socket.send(JSON.stringify({ token }));
|
||||
// Cookie-based auth: browser sends session cookie automatically.
|
||||
// No need to send a token frame.
|
||||
};
|
||||
|
||||
socket.onmessage = (event) => {
|
||||
|
||||
Reference in New Issue
Block a user