Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion backend/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,24 @@ const app = express();
const PORT = process.env.PORT || 5000;

// ── Rate Limiters ─────────────────────────────
const authLimiter = rateLimit({
// Strict limit for login/OAuth attempts only — must NOT cover /api/auth/me,
// which the frontend calls on every page load.
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 20,
standardHeaders: true,
legacyHeaders: false,
message: { status: 'error', message: 'Too many requests, please try again later.' },
});

const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 300,
standardHeaders: true,
legacyHeaders: false,
message: { status: 'error', message: 'Too many requests, please try again later.' },
});

const aiLimiter = rateLimit({
windowMs: 60 * 60 * 1000,
max: 10,
Expand Down Expand Up @@ -103,6 +113,7 @@ app.get('/api/health', (req, res) => {
});

// ── API Routes ───────────────────────────────
app.use('/api/auth/google', loginLimiter); // covers /google and /google/callback
app.use('/api/auth', authLimiter, authRoutes);
app.use('/api/courses', courseRoutes);
app.use('/api/enrollments', enrollmentRoutes);
Expand Down
22 changes: 18 additions & 4 deletions frontend/src/store/authStore.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,20 @@ const clearAuth = (set) => {
set({ user: null, role: null, isAuthenticated: false, isLoading: false });
};

/**
* Handle a failed /me fetch. Transient failures (rate limiting, server errors,
* network) keep the stored token so the session survives the next page load;
* anything else means the backend rejected the request, so discard it.
*/
const handleAuthError = (set, error) => {
const isTransient = !error?.status || error.status === 429 || error.status >= 500;
if (isTransient) {
set({ user: null, role: null, isAuthenticated: false, isLoading: false });
} else {
clearAuth(set);
}
};

const useAuthStore = create((set) => ({
user: null,
role: null,
Expand All @@ -51,8 +65,8 @@ const useAuthStore = create((set) => ({

try {
await loadCurrentUser(set);
} catch {
clearAuth(set);
} catch (error) {
handleAuthError(set, error);
}
},

Expand All @@ -63,8 +77,8 @@ const useAuthStore = create((set) => ({
setToken(token);
try {
return await loadCurrentUser(set);
} catch {
clearAuth(set);
} catch (error) {
handleAuthError(set, error);
return null;
}
},
Expand Down
16 changes: 16 additions & 0 deletions frontend/src/tests/authStore.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,22 @@ describe('useAuthStore Zustand Store', () => {
expect(localStorage.getItem('studylabs_token')).toBeNull();
});

test('should keep the stored token when /me fails with a transient error (429)', async () => {
localStorage.setItem('studylabs_token', 'still_valid_token');

global.fetch.mockImplementationOnce(() => mockFetchErrorResponse('Too many requests', 429));

await act(async () => {
await useAuthStore.getState().initialize();
});

const state = useAuthStore.getState();
expect(state.isLoading).toBe(false);
expect(state.isAuthenticated).toBe(false);
expect(state.user).toBeNull();
expect(localStorage.getItem('studylabs_token')).toBe('still_valid_token');
});

test('should finish loading and remain unauthenticated when no token exists during initialization', async () => {
await act(async () => {
await useAuthStore.getState().initialize();
Expand Down
Loading