diff --git a/backend/src/controllers/hackathonController.ts b/backend/src/controllers/hackathonController.ts index 341e7f1..3ae1cf0 100755 --- a/backend/src/controllers/hackathonController.ts +++ b/backend/src/controllers/hackathonController.ts @@ -2,7 +2,8 @@ import { Request, Response } from 'express'; import { prisma } from '../config/db'; import { cache } from '../config/cache'; import { formatHackathonDetail, formatHackathonSummary } from '../utils/formatters'; -import { hackathonSummarySelect } from '../utils/queries'; +import { hackathonSummarySelect, publicHackathonSelect } from '../utils/queries'; +import { parseJsonArray } from '../utils/formatters'; import { AuthRequest } from '../middleware/auth'; export async function getUpcomingHackathons(req: Request, res: Response) { @@ -22,13 +23,20 @@ export async function getUpcomingHackathons(req: Request, res: Response) { }, take: limit, orderBy: { date: 'asc' }, - select: hackathonSummarySelect, + select: publicHackathonSelect, }); const payload = { success: true, data: { - hackathons: hackathons.map(formatHackathonSummary), + hackathons: hackathons.map((hackathon) => ({ + _id: hackathon.id, + title: hackathon.title, + date: hackathon.date, + registrationDeadline: hackathon.registrationDeadline, + location: hackathon.location, + tags: parseJsonArray(hackathon.tags), + })), }, message: 'Upcoming hackathons retrieved successfully.', }; diff --git a/backend/src/controllers/requestController.ts b/backend/src/controllers/requestController.ts index 4f55935..1b03c61 100755 --- a/backend/src/controllers/requestController.ts +++ b/backend/src/controllers/requestController.ts @@ -104,6 +104,31 @@ export async function getUserRequests(req: AuthRequest, res: Response) { } } +export async function getMyTeamRequest(req: AuthRequest, res: Response) { + try { + const userId = req.user?.id; + const { teamId } = req.params; + const team = await prisma.team.findUnique({ where: { id: teamId }, select: { id: true } }); + if (!team) { + return res.status(404).json({ success: false, data: null, message: 'Team not found.' }); + } + + const request = await prisma.teamRequest.findFirst({ + where: { teamId, senderId: userId, type: 'join_request' }, + orderBy: [{ createdAt: 'desc' }, { id: 'desc' }], + select: { status: true }, + }); + + return res.status(200).json({ + success: true, + data: { status: request?.status || null }, + message: 'Your join request status retrieved.', + }); + } catch { + return res.status(500).json({ success: false, data: null, message: 'Failed to fetch your join request.' }); + } +} + export async function getTeamRequests(req: AuthRequest, res: Response) { try { const userId = req.user?.id; diff --git a/backend/src/routes/requestRoutes.ts b/backend/src/routes/requestRoutes.ts index a6d779d..335706f 100755 --- a/backend/src/routes/requestRoutes.ts +++ b/backend/src/routes/requestRoutes.ts @@ -1,5 +1,5 @@ import { Router } from 'express'; -import { createRequest, getUserRequests, getTeamRequests, respondToRequest } from '../controllers/requestController'; +import { createRequest, getUserRequests, getTeamRequests, getMyTeamRequest, respondToRequest } from '../controllers/requestController'; import { authenticateToken } from '../middleware/auth'; import { writeRateLimiter } from '../middleware/rateLimiter'; import { validate } from '../middleware/validate'; @@ -9,6 +9,7 @@ const router = Router(); router.get('/', authenticateToken, validate({ query: listRequestsQuery }), getUserRequests); router.post('/', authenticateToken, writeRateLimiter, validate({ body: createRequestSchema }), createRequest); +router.get('/team/:teamId/mine', authenticateToken, validate({ params: teamIdOnlyParam }), getMyTeamRequest); router.get('/team/:teamId', authenticateToken, validate({ params: teamIdOnlyParam }), getTeamRequests); router.put('/:id/respond', authenticateToken, validate({ params: idParam, body: respondRequestSchema }), respondToRequest); diff --git a/backend/src/utils/queries.ts b/backend/src/utils/queries.ts index 0cf60f4..934ef7a 100644 --- a/backend/src/utils/queries.ts +++ b/backend/src/utils/queries.ts @@ -36,6 +36,15 @@ export const hackathonSummarySelect = { isActive: true, } as const; +export const publicHackathonSelect = { + id: true, + title: true, + date: true, + registrationDeadline: true, + location: true, + tags: true, +} as const; + export const teamInclude = { leader: { select: userSummarySelect }, members: { select: { user: { select: userSummarySelect } } }, diff --git a/backend/tests/hackathons.test.ts b/backend/tests/hackathons.test.ts index 2c3be10..59ffb49 100644 --- a/backend/tests/hackathons.test.ts +++ b/backend/tests/hackathons.test.ts @@ -68,11 +68,15 @@ describe('hackathons', () => { expect(response.body.data.hackathons).toHaveLength(3); expect(response.body.data.hackathons[0].rules).toBeUndefined(); expect(response.body.data.hackathons[0].registrationLink).toBeUndefined(); + expect(response.body.data.hackathons[0].description).toBeUndefined(); + expect(response.body.data.hackathons[0].prizePool).toBeUndefined(); const today = new Date().toISOString().slice(0, 10); for (const hackathon of response.body.data.hackathons) { expect(hackathon.date >= today).toBe(true); - expect(hackathon.isActive).toBe(true); + expect(Object.keys(hackathon).sort()).toEqual([ + '_id', 'title', 'date', 'registrationDeadline', 'location', 'tags', + ].sort()); } }); diff --git a/backend/tests/requests.test.ts b/backend/tests/requests.test.ts index b722af8..952496e 100644 --- a/backend/tests/requests.test.ts +++ b/backend/tests/requests.test.ts @@ -30,6 +30,16 @@ beforeAll(async () => { }); describe('team requests', () => { + it('limits personal status to the authenticated applicant', async () => { + expect((await request(app).get(`/api/requests/team/${teamId}/mine`)).status).toBe(401); + const empty = await request(app).get(`/api/requests/team/${teamId}/mine`).set('Authorization', `Bearer ${applicantToken}`); + expect(empty.status).toBe(200); + expect(empty.body.data.status).toBeNull(); + expect(empty.body.data.sender).toBeUndefined(); + expect((await request(app).get('/api/requests/team/not-a-uuid/mine').set('Authorization', `Bearer ${applicantToken}`)).status).toBe(400); + expect((await request(app).get('/api/requests/team/99999999-9999-4999-8999-999999999999/mine').set('Authorization', `Bearer ${applicantToken}`)).status).toBe(404); + }); + it('walks the core journey: sign up, create team, request to join, accept', async () => { const created = await request(app) .post('/api/requests') @@ -39,6 +49,10 @@ describe('team requests', () => { expect(created.body.data.status).toBe('pending'); expect(created.body.data.type).toBe('join_request'); requestId = created.body.data._id; + const pending = await request(app).get(`/api/requests/team/${teamId}/mine`).set('Authorization', `Bearer ${applicantToken}`); + expect(pending.body.data.status).toBe('pending'); + const otherUser = await request(app).get(`/api/requests/team/${teamId}/mine`).set('Authorization', `Bearer ${leaderToken}`); + expect(otherUser.body.data.status).toBeNull(); const received = await request(app) .get('/api/requests?direction=received&status=pending') @@ -58,6 +72,8 @@ describe('team requests', () => { .send({ action: 'accept' }); expect(accepted.status).toBe(200); expect(accepted.body.data.status).toBe('accepted'); + const own = await request(app).get(`/api/requests/team/${teamId}/mine`).set('Authorization', `Bearer ${applicantToken}`); + expect(own.body.data.status).toBe('accepted'); const team = await request(app).get(`/api/teams/${teamId}`).set('Authorization', `Bearer ${leaderToken}`); expect(team.body.data.members.some((member: any) => member._id === applicantId)).toBe(true); @@ -69,6 +85,26 @@ describe('team requests', () => { expect(twice.status).toBe(400); }); + it('shows declined status to the applicant on later visits', async () => { + const team = await request(app) + .post('/api/teams') + .set('Authorization', `Bearer ${leaderToken}`) + .send({ teamName: 'Decline Test Team', description: 'A team for testing declined applications.' }); + const id = team.body.data._id; + const join = await request(app) + .post('/api/requests') + .set('Authorization', `Bearer ${applicantToken}`) + .send({ teamId: id }); + expect(join.status).toBe(201); + const declined = await request(app) + .put(`/api/requests/${join.body.data._id}/respond`) + .set('Authorization', `Bearer ${leaderToken}`) + .send({ action: 'reject' }); + expect(declined.status).toBe(200); + const own = await request(app).get(`/api/requests/team/${id}/mine`).set('Authorization', `Bearer ${applicantToken}`); + expect(own.body.data.status).toBe('rejected'); + }); + it('rejects duplicate, self and invalid requests', async () => { const duplicate = await request(app) .post('/api/requests') diff --git a/client/index.html b/client/index.html index 86e3629..43ba504 100755 --- a/client/index.html +++ b/client/index.html @@ -4,7 +4,7 @@ - + - + diff --git a/client/public/robots.txt b/client/public/robots.txt new file mode 100644 index 0000000..c2a49f4 --- /dev/null +++ b/client/public/robots.txt @@ -0,0 +1,2 @@ +User-agent: * +Allow: / diff --git a/client/src/App.tsx b/client/src/App.tsx index 38294dd..76d1942 100755 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -1,5 +1,5 @@ import React, { Suspense, lazy, useEffect } from 'react'; -import { BrowserRouter as Router, Navigate, Route, Routes } from 'react-router-dom'; +import { BrowserRouter as Router, Navigate, Route, Routes, useLocation } from 'react-router-dom'; import { useAuthStore } from './store/authStore'; import Navbar from './components/Navbar'; import ServerStatusBanner from './components/ServerStatusBanner'; @@ -20,6 +20,17 @@ const TeamDetailPage = lazy(() => import('./pages/TeamDetailPage')); const CreateTeamPage = lazy(() => import('./pages/CreateTeamPage')); const PeoplePage = lazy(() => import('./pages/PeoplePage')); +const SessionExpiryRedirect: React.FC = () => { + const expiredPath = useAuthStore((state) => state.expiredPath); + const location = useLocation(); + + if (expiredPath && location.pathname !== '/login') { + return ; + } + + return null; +}; + const App: React.FC = () => { const fetchCurrentUser = useAuthStore((state) => state.fetchCurrentUser); @@ -30,6 +41,7 @@ const App: React.FC = () => { return ( + diff --git a/client/src/api/index.ts b/client/src/api/index.ts index 9a8e856..c46404a 100755 --- a/client/src/api/index.ts +++ b/client/src/api/index.ts @@ -5,6 +5,11 @@ export const API_BASE_URL = import.meta.env.VITE_API_URL || (import.meta.env.DEV ? 'http://localhost:5000' : window.location.origin); const requestCache = new Map(); +let onSessionExpired: (() => void) | null = null; + +export function setSessionExpiryHandler(handler: () => void): void { + onSessionExpired = handler; +} interface CacheableConfig extends AxiosRequestConfig { cacheTtl?: number; @@ -94,17 +99,11 @@ api.interceptors.response.use( useServerStore.getState().setWaking(true); } - if (status === 401) { - localStorage.removeItem('hackmatch_token'); - clearApiCache(); - if ( - !window.location.pathname.startsWith('/login') && - !window.location.pathname.startsWith('/register') && - window.location.pathname !== '/' - ) { - const next = encodeURIComponent(`${window.location.pathname}${window.location.search}`); - window.location.href = `/login?expired=true&next=${next}`; - } + if ( + status === 401 && + error.config?.headers?.Authorization === `Bearer ${localStorage.getItem('hackmatch_token')}` + ) { + onSessionExpired?.(); } return Promise.reject(error); diff --git a/client/src/components/HackathonCard.tsx b/client/src/components/HackathonCard.tsx index 010c785..b649c75 100755 --- a/client/src/components/HackathonCard.tsx +++ b/client/src/components/HackathonCard.tsx @@ -2,22 +2,15 @@ import React from 'react'; import { Link } from 'react-router-dom'; import { Calendar, MapPin } from 'lucide-react'; import { HackathonSummary } from '../types'; +import { formatDate } from '../utils/format'; interface HackathonCardProps { hackathon: HackathonSummary; } -function formatDate(value: string) { - return new Date(`${value}T00:00:00`).toLocaleDateString('en-US', { - month: 'short', - day: 'numeric', - year: 'numeric', - }); -} - const HackathonCard: React.FC = ({ hackathon }) => { return ( - + {hackathon.mode} Teams of {hackathon.teamSize.min}–{hackathon.teamSize.max} diff --git a/client/src/components/Navbar.tsx b/client/src/components/Navbar.tsx index e1af628..920e691 100755 --- a/client/src/components/Navbar.tsx +++ b/client/src/components/Navbar.tsx @@ -18,6 +18,7 @@ const Navbar: React.FC = () => { const [mobileOpen, setMobileOpen] = useState(false); const [menuOpen, setMenuOpen] = useState(false); const menuRef = useRef(null); + const menuButtonRef = useRef(null); const navigate = useNavigate(); const location = useLocation(); @@ -36,6 +37,26 @@ const Navbar: React.FC = () => { setMenuOpen(false); }, [location.pathname]); + useEffect(() => { + if (menuOpen) menuRef.current?.querySelector('[role="menuitem"]')?.focus(); + }, [menuOpen]); + + const onMenuKeyDown = (event: React.KeyboardEvent) => { + if (event.key === 'Escape') { + setMenuOpen(false); + menuButtonRef.current?.focus(); + return; + } + if (event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return; + const items = Array.from(menuRef.current?.querySelectorAll('[role="menuitem"]') || []); + const current = items.indexOf(document.activeElement as HTMLElement); + const next = (current + (event.key === 'ArrowDown' ? 1 : items.length - 1)) % items.length; + if (items[next]) { + event.preventDefault(); + items[next].focus(); + } + }; + const handleLogout = () => { logout(); navigate('/'); @@ -46,7 +67,7 @@ const Navbar: React.FC = () => { return ( - + @@ -55,7 +76,7 @@ const Navbar: React.FC = () => { @@ -67,13 +88,15 @@ const Navbar: React.FC = () => { {signedIn && user ? ( - + setMenuOpen((open) => !open)} - className="flex items-center gap-2 rounded-lg border border-line p-1 pr-2 text-sm hover:bg-subtle" + className="flex min-h-11 items-center gap-2 rounded-lg border border-line p-1 pr-2 text-sm hover:bg-subtle" aria-haspopup="menu" aria-expanded={menuOpen} + aria-controls="account-menu" aria-label="Account menu" > @@ -84,6 +107,7 @@ const Navbar: React.FC = () => { {menuOpen && ( @@ -93,14 +117,14 @@ const Navbar: React.FC = () => { Dashboard Profile @@ -108,7 +132,7 @@ const Navbar: React.FC = () => { type="button" role="menuitem" onClick={handleLogout} - className="flex w-full items-center gap-2 rounded-lg px-3 py-2 text-left text-sm text-muted hover:bg-subtle hover:text-fg" + className="flex min-h-11 w-full items-center gap-2 rounded-lg px-3 py-2 text-left text-sm text-muted hover:bg-subtle hover:text-fg" > Log out @@ -132,9 +156,10 @@ const Navbar: React.FC = () => { setMobileOpen((open) => !open)} - className="btn btn-secondary !h-9 !w-9 !px-0" + className="btn btn-secondary !h-11 !w-11 !px-0" aria-label={mobileOpen ? 'Close menu' : 'Open menu'} aria-expanded={mobileOpen} + aria-controls="mobile-menu" > {mobileOpen ? : } @@ -142,13 +167,15 @@ const Navbar: React.FC = () => { {mobileOpen && ( - + { + if (event.key === 'Escape') setMobileOpen(false); + }}> {(signedIn ? NAV_LINKS : []).map((link) => ( @@ -157,16 +184,16 @@ const Navbar: React.FC = () => { ))} {signedIn && user ? ( <> - + Dashboard - + Profile Log out diff --git a/client/src/components/RequestCard.tsx b/client/src/components/RequestCard.tsx index 999526a..f4ef157 100755 --- a/client/src/components/RequestCard.tsx +++ b/client/src/components/RequestCard.tsx @@ -46,7 +46,7 @@ const RequestCard: React.FC = ({ request, onRespond }) => { type="button" onClick={() => respond('accept')} disabled={pending !== null} - className="btn btn-primary !h-8 !px-3 !text-xs" + className="btn btn-primary !px-3" > {pending === 'accept' ? 'Accepting…' : 'Accept'} @@ -54,7 +54,7 @@ const RequestCard: React.FC = ({ request, onRespond }) => { type="button" onClick={() => respond('reject')} disabled={pending !== null} - className="btn btn-secondary !h-8 !px-3 !text-xs" + className="btn btn-secondary !px-3" > {pending === 'reject' ? 'Declining…' : 'Decline'} diff --git a/client/src/components/TeamCard.tsx b/client/src/components/TeamCard.tsx index 968d10d..bcdc910 100755 --- a/client/src/components/TeamCard.tsx +++ b/client/src/components/TeamCard.tsx @@ -13,16 +13,16 @@ const TeamCard: React.FC = ({ team }) => { const isFull = team.memberCount >= team.maxSize; return ( - + - {isFull ? 'Full' : 'Open'} + {isFull ? 'Full' : 'Open'} {team.memberCount}/{team.maxSize} - + {team.teamName} @@ -42,7 +42,7 @@ const TeamCard: React.FC = ({ team }) => { {team.leader && } Led by {team.leader?.name || 'Unknown'} - + View team diff --git a/client/src/components/ThemeToggle.tsx b/client/src/components/ThemeToggle.tsx index 17ffc65..22f366c 100644 --- a/client/src/components/ThemeToggle.tsx +++ b/client/src/components/ThemeToggle.tsx @@ -35,7 +35,7 @@ const ThemeToggle: React.FC = () => { diff --git a/client/src/components/UserCard.tsx b/client/src/components/UserCard.tsx index 052d607..e5db673 100755 --- a/client/src/components/UserCard.tsx +++ b/client/src/components/UserCard.tsx @@ -10,7 +10,7 @@ interface UserCardProps { const UserCard: React.FC = ({ user }) => { return ( - + diff --git a/client/src/index.css b/client/src/index.css index e2af890..df4dfb2 100755 --- a/client/src/index.css +++ b/client/src/index.css @@ -5,6 +5,7 @@ --color-card: var(--card); --color-subtle: var(--subtle); --color-line: var(--line); + --color-line-hover: var(--line-hover); --color-fg: var(--fg); --color-muted: var(--muted); --color-accent: var(--accent); @@ -12,44 +13,59 @@ --color-accent-fg: var(--accent-fg); --color-accent-soft: var(--accent-soft); --color-accent-text: var(--accent-text); + --color-success: var(--success); + --color-success-soft: var(--success-soft); + --color-warning: var(--warning); + --color-warning-soft: var(--warning-soft); --color-danger: var(--danger); --color-danger-soft: var(--danger-soft); --font-sans: 'Inter', system-ui, -apple-system, sans-serif; --font-mono: 'JetBrains Mono', ui-monospace, SFMono-Regular, monospace; + --shadow-card-hover: 0 8px 20px -6px rgba(24, 24, 27, 0.08); } :root, [data-theme='light'] { - --app: #fafafa; + --app: #faf9f6; --card: #ffffff; - --subtle: #f3f4f6; - --line: #e1e5ea; - --fg: #111827; - --muted: #4b5563; - --accent: #4f46e5; - --accent-hover: #4338ca; - --accent-fg: #ffffff; - --accent-soft: #eef2ff; - --accent-text: #4338ca; + --subtle: #f3f1ec; + --line: #e5e2dc; + --line-hover: #d0cbc1; + --fg: #18181b; + --muted: #52525b; + --accent: #d95d39; + --accent-hover: #c04d2b; + --accent-fg: #18181b; + --accent-soft: #fff2ec; + --accent-text: #a63f20; + --success: #15803d; + --success-soft: #ecfdf5; + --warning: #b45309; + --warning-soft: #fffbeb; --danger: #b91c1c; --danger-soft: #fef2f2; - --shadow: 0 1px 2px rgba(17, 24, 39, 0.04); + --shadow: 0 1px 2px rgba(24, 24, 27, 0.04); color-scheme: light; } [data-theme='dark'] { --app: #0b0d10; --card: #12151a; - --subtle: #181c22; - --line: #232830; + --subtle: #1e2226; + --line: #303236; + --line-hover: #55585f; --fg: #e6e8eb; --muted: #9aa3ae; - --accent: #818cf8; - --accent-hover: #a5b4fc; + --accent: #f19273; + --accent-hover: #ffab8a; --accent-fg: #0b0d10; - --accent-soft: #1b1f2a; - --accent-text: #a5b4fc; + --accent-soft: #33241f; + --accent-text: #ffad8d; + --success: #62d590; + --success-soft: #142b20; + --warning: #f5bc70; + --warning-soft: #302417; --danger: #f87171; --danger-soft: #2a1517; --shadow: 0 1px 2px rgba(0, 0, 0, 0.3); @@ -94,16 +110,36 @@ .card { background-color: var(--card); border: 1px solid var(--line); - border-radius: 8px; + border-radius: 12px; box-shadow: var(--shadow); } + .card-interactive { + transition: transform 180ms cubic-bezier(0.22, 1, 0.36, 1), border-color 180ms ease, box-shadow 180ms ease; + } + + .card-interactive:hover { + transform: translateY(-2px); + border-color: var(--line-hover); + box-shadow: var(--shadow-card-hover); + } + + .tap-link { + display: inline-flex; + min-height: 44px; + align-items: center; + } + + .page-enter { + animation: page-enter 360ms cubic-bezier(0.22, 1, 0.36, 1) both; + } + .btn { display: inline-flex; align-items: center; justify-content: center; gap: 6px; - height: 36px; + min-height: 44px; padding: 0 14px; border: 1px solid transparent; border-radius: 8px; @@ -126,6 +162,11 @@ .btn-primary:hover:not(:disabled) { background-color: var(--accent-hover); + color: #ffffff; + } + + [data-theme='dark'] .btn-primary:hover:not(:disabled) { + color: var(--accent-fg); } .btn-secondary { @@ -140,7 +181,7 @@ .input { width: 100%; - height: 36px; + min-height: 44px; padding: 0 10px; border: 1px solid var(--line); border-radius: 8px; @@ -158,7 +199,11 @@ } .input::placeholder { - color: var(--muted); + color: #71717a; + } + + [data-theme='dark'] .input::placeholder { + color: #a1a1aa; } .input:focus { @@ -197,6 +242,20 @@ } } +@keyframes page-enter { + from { opacity: 0; transform: translateY(6px); } + to { opacity: 1; transform: translateY(0); } +} + +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + scroll-behavior: auto !important; + transition-duration: 0.01ms !important; + } +} + @keyframes pulse-soft { 0%, 100% { diff --git a/client/src/pages/CreateTeamPage.tsx b/client/src/pages/CreateTeamPage.tsx index db0238f..c8b8c77 100755 --- a/client/src/pages/CreateTeamPage.tsx +++ b/client/src/pages/CreateTeamPage.tsx @@ -93,12 +93,14 @@ const CreateTeamPage: React.FC = () => { setTeamName(event.target.value)} className="input" placeholder="Neural Sync" /> - {fieldErrors.teamName && {fieldErrors.teamName}} + {fieldErrors.teamName && {fieldErrors.teamName}} @@ -107,13 +109,15 @@ const CreateTeamPage: React.FC = () => { setDescription(event.target.value)} maxLength={600} className="input" placeholder="What are you building, and who do you need?" /> - {fieldErrors.description && {fieldErrors.description}} + {fieldErrors.description && {fieldErrors.description}} @@ -123,6 +127,8 @@ const CreateTeamPage: React.FC = () => { { onChange={(event) => setMaxSize(Number(event.target.value))} className="input" /> - {fieldErrors.maxSize && {fieldErrors.maxSize}} + {fieldErrors.maxSize && {fieldErrors.maxSize}} diff --git a/client/src/pages/DashboardPage.tsx b/client/src/pages/DashboardPage.tsx index f6edf2e..6f7a2ab 100755 --- a/client/src/pages/DashboardPage.tsx +++ b/client/src/pages/DashboardPage.tsx @@ -4,68 +4,89 @@ import api from '../api'; import { useAuthStore } from '../store/authStore'; import { HackathonSummary, TeamRequest, TeamSummary } from '../types'; import { toast } from '../store/toastStore'; -import { errorMessage } from '../utils/format'; +import { errorMessage, formatDate } from '../utils/format'; import TeamCard from '../components/TeamCard'; import RequestCard from '../components/RequestCard'; import EmptyState from '../components/EmptyState'; +const SectionSkeleton: React.FC = () => ( + + + + +); + +const SectionError: React.FC<{ message: string; onRetry: () => void }> = ({ message, onRetry }) => ( + + {message} + Retry + +); + const DashboardPage: React.FC = () => { const { user } = useAuthStore(); const [teams, setTeams] = useState([]); const [requests, setRequests] = useState([]); const [hackathons, setHackathons] = useState([]); - const [loading, setLoading] = useState(true); + const [loading, setLoading] = useState({ teams: true, requests: true, hackathons: true }); + const [errors, setErrors] = useState({ teams: '', requests: '', hackathons: '' }); - const load = useCallback(async () => { + const loadTeams = useCallback(async () => { if (!user) return; - setLoading(true); + setLoading((current) => ({ ...current, teams: true })); + setErrors((current) => ({ ...current, teams: '' })); try { - const [teamResponse, requestResponse, hackathonResponse] = await Promise.all([ - api.get('/teams', { params: { memberId: user._id, limit: 6 } }), - api.get('/requests', { params: { direction: 'received', status: 'pending' } }), - api.get('/hackathons', { params: { upcoming: 'true', limit: 3 }, cacheTtl: 60000 }), - ]); - setTeams(teamResponse.data.data.teams); - setRequests(requestResponse.data.data); - setHackathons(hackathonResponse.data.data.hackathons); - } catch (error) { - toast(errorMessage(error, 'Could not load your dashboard.'), 'error'); + const response = await api.get('/teams', { params: { memberId: user._id, limit: 6 } }); + setTeams(response.data.data.teams); + } catch { + setErrors((current) => ({ ...current, teams: 'Could not load your teams.' })); } finally { - setLoading(false); + setLoading((current) => ({ ...current, teams: false })); } }, [user]); + const loadRequests = useCallback(async () => { + setLoading((current) => ({ ...current, requests: true })); + setErrors((current) => ({ ...current, requests: '' })); + try { + const response = await api.get('/requests', { params: { direction: 'received', status: 'pending' } }); + setRequests(response.data.data); + } catch { + setErrors((current) => ({ ...current, requests: 'Could not load join requests.' })); + } finally { + setLoading((current) => ({ ...current, requests: false })); + } + }, []); + + const loadHackathons = useCallback(async () => { + setLoading((current) => ({ ...current, hackathons: true })); + setErrors((current) => ({ ...current, hackathons: '' })); + try { + const response = await api.get('/hackathons', { params: { upcoming: 'true', limit: 3 }, cacheTtl: 60000 }); + setHackathons(response.data.data.hackathons); + } catch { + setErrors((current) => ({ ...current, hackathons: 'Could not load upcoming hackathons.' })); + } finally { + setLoading((current) => ({ ...current, hackathons: false })); + } + }, []); + useEffect(() => { - load(); - }, [load]); + loadTeams(); + loadRequests(); + loadHackathons(); + }, [loadTeams, loadRequests, loadHackathons]); const respond = async (requestId: string, action: 'accept' | 'reject') => { try { await api.put(`/requests/${requestId}/respond`, { action }); toast(action === 'accept' ? 'Teammate added to your team.' : 'Request declined.', 'success'); - await load(); + await Promise.all([loadRequests(), loadTeams()]); } catch (error) { toast(errorMessage(error, 'Could not respond to that request.'), 'error'); } }; - if (loading) { - return ( - - - - {[0, 1, 2].map((index) => ( - - - - - - ))} - - - ); - } - return ( Dashboard @@ -75,12 +96,16 @@ const DashboardPage: React.FC = () => { Your teams - + Host a team - {teams.length === 0 ? ( + {errors.teams ? ( + + ) : loading.teams ? ( + + ) : teams.length === 0 ? ( { Join requests - {requests.length === 0 ? ( + {errors.requests ? ( + + ) : loading.requests ? ( + + ) : requests.length === 0 ? ( No pending join requests. ) : ( @@ -121,11 +150,15 @@ const DashboardPage: React.FC = () => { Upcoming hackathons - + View all - {hackathons.length === 0 ? ( + {errors.hackathons ? ( + + ) : loading.hackathons ? ( + + ) : hackathons.length === 0 ? ( No upcoming hackathons have been listed yet. ) : ( @@ -136,7 +169,7 @@ const DashboardPage: React.FC = () => { className="flex flex-col gap-1 px-5 py-4 transition-colors hover:bg-subtle sm:flex-row sm:items-center sm:justify-between" > {hackathon.title} - {hackathon.date} + {formatDate(hackathon.date)} ))} diff --git a/client/src/pages/LandingPage.tsx b/client/src/pages/LandingPage.tsx index 4d979b5..b2f8ee6 100755 --- a/client/src/pages/LandingPage.tsx +++ b/client/src/pages/LandingPage.tsx @@ -2,8 +2,8 @@ import React, { useEffect, useState } from 'react'; import { Link } from 'react-router-dom'; import api from '../api'; import { useAuthStore } from '../store/authStore'; -import { HackathonSummary } from '../types'; -import HackathonCard from '../components/HackathonCard'; +import { PublicHackathon } from '../types'; +import { formatDate } from '../utils/format'; const STEPS = [ { @@ -23,7 +23,7 @@ const STEPS = [ const LandingPage: React.FC = () => { const { isAuthenticated, initialized } = useAuthStore(); const signedIn = isAuthenticated && initialized; - const [hackathons, setHackathons] = useState([]); + const [hackathons, setHackathons] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { @@ -51,41 +51,53 @@ const LandingPage: React.FC = () => { return ( - - Hackathon team finder - - Find your hackathon team. - - - HackMatch is where hackathon participants show what they bring, find complementary teammates, and - build a roster before the event starts. - - - {signedIn ? ( - <> - - Find a team - - - Host a team - - > - ) : ( - <> - - Create account - - - Sign in - - > + + + Hackathon team finder / Build together + + Find your hackathon team. + + + HackMatch is where hackathon participants show what they bring, find complementary teammates, and + build a roster before the event starts. + + + {signedIn ? ( + <> + + Find a team + + + Host a team + + > + ) : ( + <> + + Create account + + + Sign in + + > + )} + + {!signedIn && ( + + Sign in to open event details, browse teams, and view people. + )} - {!signedIn && ( - - Sign in to open event details, browse teams, and view people. - - )} + + + TEAM WORKFLOWhackmatch / 01 + + + 01 / DISCOVERPick a hackathon that fits your interests. + 02 / CONNECTFind teammates whose skills complement yours. + 03 / SHIPJoin a roster and build something together. + + @@ -116,7 +128,7 @@ const LandingPage: React.FC = () => { {signedIn && ( - + View all )} @@ -133,7 +145,21 @@ const LandingPage: React.FC = () => { )) - : hackathons.map((hackathon) => )} + : hackathons.map((hackathon) => ( + + UPCOMING EVENT / {formatDate(hackathon.date)} + {hackathon.title} + {hackathon.location} + Registration closes {formatDate(hackathon.registrationDeadline)} + + {hackathon.tags.slice(0, 3).map((tag) => {tag})} + + + ))} {!loading && hackathons.length === 0 && ( diff --git a/client/src/pages/LoginPage.tsx b/client/src/pages/LoginPage.tsx index 462adfc..b6e97c3 100755 --- a/client/src/pages/LoginPage.tsx +++ b/client/src/pages/LoginPage.tsx @@ -4,7 +4,7 @@ import { useAuthStore } from '../store/authStore'; import { safeNextPath } from '../utils/navigation'; const LoginPage: React.FC = () => { - const { login, error, loading, clearError } = useAuthStore(); + const { login, error, loading, clearError, expiredPath } = useAuthStore(); const navigate = useNavigate(); const [searchParams] = useSearchParams(); const [email, setEmail] = useState(''); @@ -46,9 +46,9 @@ const LoginPage: React.FC = () => { {nextPath === '/dashboard' ? 'Find your next hackathon team.' : 'Sign in to continue where you left off.'} - {searchParams.get('expired') === 'true' && ( + {(searchParams.get('expired') === 'true' || expiredPath !== null) && ( - Your session expired. Sign in again. + Session expired, please sign in again. )} @@ -66,6 +66,8 @@ const LoginPage: React.FC = () => { { setEmail(event.target.value); @@ -75,7 +77,7 @@ const LoginPage: React.FC = () => { className="input" placeholder="you@college.edu" /> - {fieldErrors.email && {fieldErrors.email}} + {fieldErrors.email && {fieldErrors.email}} @@ -85,6 +87,8 @@ const LoginPage: React.FC = () => { { setPassword(event.target.value); @@ -94,7 +98,7 @@ const LoginPage: React.FC = () => { className="input" placeholder="••••••••" /> - {fieldErrors.password && {fieldErrors.password}} + {fieldErrors.password && {fieldErrors.password}} diff --git a/client/src/pages/ProfilePage.tsx b/client/src/pages/ProfilePage.tsx index 0e82efe..668cb15 100755 --- a/client/src/pages/ProfilePage.tsx +++ b/client/src/pages/ProfilePage.tsx @@ -107,7 +107,7 @@ const ProfilePage: React.FC = () => { This is what teammates see when they search for you. {error && ( - + {error} )} @@ -173,7 +173,7 @@ const ProfilePage: React.FC = () => { Full name - setName(event.target.value)} className="input" /> + setName(event.target.value)} className="input" aria-invalid={error.includes('Name')} aria-describedby={error.includes('Name') ? 'profile-error' : undefined} /> @@ -183,6 +183,8 @@ const ProfilePage: React.FC = () => { setCollege(event.target.value)} className="input" diff --git a/client/src/pages/RegisterPage.tsx b/client/src/pages/RegisterPage.tsx index 60a6c92..181f787 100755 --- a/client/src/pages/RegisterPage.tsx +++ b/client/src/pages/RegisterPage.tsx @@ -88,13 +88,15 @@ const RegisterPage: React.FC = () => { setName(event.target.value)} autoComplete="name" className="input" placeholder="Priya Menon" /> - {fieldErrors.name && {fieldErrors.name}} + {fieldErrors.name && {fieldErrors.name}} @@ -104,13 +106,15 @@ const RegisterPage: React.FC = () => { setEmail(event.target.value)} autoComplete="email" className="input" placeholder="you@college.edu" /> - {fieldErrors.email && {fieldErrors.email}} + {fieldErrors.email && {fieldErrors.email}} @@ -120,13 +124,15 @@ const RegisterPage: React.FC = () => { setPassword(event.target.value)} autoComplete="new-password" className="input" placeholder="At least 8 characters, one number" /> - {fieldErrors.password && {fieldErrors.password}} + {fieldErrors.password && {fieldErrors.password}} @@ -135,12 +141,14 @@ const RegisterPage: React.FC = () => { setCollege(event.target.value)} className="input" placeholder="MIT" /> - {fieldErrors.college && {fieldErrors.college}} + {fieldErrors.college && {fieldErrors.college}} diff --git a/client/src/pages/TeamDetailPage.tsx b/client/src/pages/TeamDetailPage.tsx index d8ac436..1e7a4e3 100755 --- a/client/src/pages/TeamDetailPage.tsx +++ b/client/src/pages/TeamDetailPage.tsx @@ -19,6 +19,9 @@ const TeamDetailPage: React.FC = () => { const [message, setMessage] = useState(''); const [sending, setSending] = useState(false); const [requestError, setRequestError] = useState(''); + const [myRequestStatus, setMyRequestStatus] = useState(null); + const [statusLoading, setStatusLoading] = useState(true); + const [statusError, setStatusError] = useState(false); const loadTeam = useCallback(async () => { const response = await api.get(`/teams/${id}`, { cacheTtl: 15000 }); @@ -55,6 +58,27 @@ const TeamDetailPage: React.FC = () => { const isMember = Boolean(user && team?.members.some((member) => member._id === user._id)); const isFull = Boolean(team && team.memberCount >= team.maxSize); + const loadMyRequest = useCallback(async () => { + if (!team || !user || isLeader || isMember) { + setStatusLoading(false); + return; + } + setStatusLoading(true); + setStatusError(false); + try { + const response = await api.get(`/requests/team/${team._id}/mine`); + setMyRequestStatus(response.data.data.status); + } catch { + setStatusError(true); + } finally { + setStatusLoading(false); + } + }, [team, user, isLeader, isMember]); + + useEffect(() => { + loadMyRequest(); + }, [loadMyRequest]); + const loadRequests = useCallback(async () => { if (!team || !isLeader) { setRequests([]); @@ -80,6 +104,7 @@ const TeamDetailPage: React.FC = () => { try { await api.post('/requests', { teamId: team._id, message: message.trim() || undefined }); setMessage(''); + setMyRequestStatus('pending'); toast('Join request sent to the team leader.', 'success'); } catch (submitError) { setRequestError(errorMessage(submitError, 'Could not send that request.')); @@ -211,6 +236,19 @@ const TeamDetailPage: React.FC = () => { {' '} to send a join request. + ) : statusLoading ? ( + Checking your request status… + ) : statusError ? ( + + Could not check your request status. + Retry + + ) : myRequestStatus === 'pending' ? ( + Request pending + ) : myRequestStatus === 'rejected' ? ( + Declined. The team leader did not accept your request. + ) : myRequestStatus === 'accepted' ? ( + You are a member. Refresh the page to see the updated roster. ) : isFull ? ( This team is full. ) : team.status !== 'open' ? ( diff --git a/client/src/store/authStore.ts b/client/src/store/authStore.ts index 706dea6..e9d3470 100755 --- a/client/src/store/authStore.ts +++ b/client/src/store/authStore.ts @@ -1,6 +1,7 @@ import { create } from 'zustand'; -import api, { clearApiCache } from '../api'; +import api, { clearApiCache, setSessionExpiryHandler } from '../api'; import { clearAvatarCache } from '../utils/avatarCache'; +import { toast } from './toastStore'; import { ApiResponse, User } from '../types'; export type ProfileUpdate = Partial & { avatar?: string | null; password?: string }; @@ -12,6 +13,8 @@ interface AuthState { initialized: boolean; loading: boolean; error: string | null; + expiredPath: string | null; + expireSession: () => void; login: (email: string, password: string) => Promise; register: (data: ProfileUpdate) => Promise; logout: () => void; @@ -27,6 +30,25 @@ export const useAuthStore = create((set) => ({ initialized: false, loading: false, error: null, + expiredPath: null, + + expireSession: () => { + if (!localStorage.getItem('hackmatch_token')) return; + const path = `${window.location.pathname}${window.location.search}`; + localStorage.removeItem('hackmatch_token'); + clearApiCache(); + clearAvatarCache(); + set({ + token: null, + user: null, + isAuthenticated: false, + initialized: true, + loading: false, + expiredPath: path.startsWith('/login') || path.startsWith('/register') ? '/dashboard' : path, + error: null, + }); + toast('Session expired, please sign in again', 'error'); + }, login: async (email, password) => { set({ loading: true, error: null }); @@ -42,6 +64,7 @@ export const useAuthStore = create((set) => ({ initialized: true, loading: false, error: null, + expiredPath: null, }); return true; } catch (err) { @@ -67,6 +90,7 @@ export const useAuthStore = create((set) => ({ initialized: true, loading: false, error: null, + expiredPath: null, }); return true; } catch (err) { @@ -88,6 +112,7 @@ export const useAuthStore = create((set) => ({ initialized: true, loading: false, error: null, + expiredPath: null, }); }, @@ -108,17 +133,15 @@ export const useAuthStore = create((set) => ({ loading: false, }); } catch { - localStorage.removeItem('hackmatch_token'); - clearApiCache(); - clearAvatarCache(); - set({ - token: null, - user: null, - isAuthenticated: false, - initialized: true, - loading: false, - error: 'Session expired. Please sign in again.', - }); + if (localStorage.getItem('hackmatch_token')) { + set({ + user: null, + isAuthenticated: false, + loading: false, + initialized: true, + error: 'Could not verify your session. Please try again.', + }); + } } }, @@ -143,3 +166,5 @@ export const useAuthStore = create((set) => ({ clearError: () => set({ error: null }), })); + +setSessionExpiryHandler(() => useAuthStore.getState().expireSession()); diff --git a/client/src/test/DashboardPage.test.tsx b/client/src/test/DashboardPage.test.tsx new file mode 100644 index 0000000..da10715 --- /dev/null +++ b/client/src/test/DashboardPage.test.tsx @@ -0,0 +1,53 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; + +const { get } = vi.hoisted(() => ({ get: vi.fn() })); +vi.mock('../api', () => ({ + default: { get }, + clearApiCache: vi.fn(), + setSessionExpiryHandler: vi.fn(), +})); + +import DashboardPage from '../pages/DashboardPage'; +import { useAuthStore } from '../store/authStore'; + +beforeEach(() => { + get.mockReset(); + useAuthStore.setState({ + user: { + _id: 'user-id', id: 'user-id', name: 'Priya Menon', college: 'MIT', branch: '', + bio: '', skills: [], experience: 'advanced', isAvailable: true, hasAvatar: false, + }, + token: 'token', isAuthenticated: true, initialized: true, + }); +}); + +describe('DashboardPage', () => { + it('keeps healthy sections usable and retries only the failed section', async () => { + let teamAttempts = 0; + get.mockImplementation((url: string) => { + if (url === '/teams') { + teamAttempts += 1; + if (teamAttempts === 1) return Promise.reject(new Error('Temporary outage')); + return Promise.resolve({ data: { data: { teams: [] } } }); + } + if (url === '/requests') return Promise.resolve({ data: { data: [] } }); + return Promise.resolve({ data: { data: { hackathons: [{ + _id: 'event-1', title: 'NovaHack 2027', date: '2027-02-12', + }] } } }); + }); + + render(); + + expect(await screen.findByText('Could not load your teams.')).toBeInTheDocument(); + expect(screen.getByText('No pending join requests.')).toBeInTheDocument(); + expect(screen.getByText('NovaHack 2027')).toBeInTheDocument(); + expect(screen.getByText('Feb 12, 2027')).toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', { name: 'Retry' })); + expect(await screen.findByText('You are not on a team yet')).toBeInTheDocument(); + await waitFor(() => expect(teamAttempts).toBe(2)); + expect(screen.getByText('NovaHack 2027')).toBeInTheDocument(); + }); +}); diff --git a/client/src/test/LandingPage.test.tsx b/client/src/test/LandingPage.test.tsx index b8799c3..951d27b 100644 --- a/client/src/test/LandingPage.test.tsx +++ b/client/src/test/LandingPage.test.tsx @@ -7,6 +7,7 @@ const { get } = vi.hoisted(() => ({ get: vi.fn() })); vi.mock('../api', () => ({ default: { get }, clearApiCache: vi.fn(), + setSessionExpiryHandler: vi.fn(), API_BASE_URL: 'http://localhost:5000', })); @@ -17,16 +18,10 @@ const hackathon = { _id: '22222222-2222-4222-8222-222222222221', id: '22222222-2222-4222-8222-222222222221', title: 'NovaHack 2027', - organizer: 'Nova Labs', - description: 'A 48-hour sprint.', date: '2027-02-12', registrationDeadline: '2027-02-05', location: 'Online', - mode: 'online', - prizePool: '$40,000', - teamSize: { min: 2, max: 4 }, tags: ['AI', 'Web'], - isActive: true, }; beforeEach(() => { @@ -56,6 +51,8 @@ describe('LandingPage', () => { expect(screen.getByRole('link', { name: 'Sign in' })).toHaveAttribute('href', '/login'); expect(screen.queryByRole('link', { name: 'Teams' })).not.toBeInTheDocument(); expect(await screen.findByText('NovaHack 2027')).toBeInTheDocument(); + expect(screen.getByText('Registration closes Feb 5, 2027')).toBeInTheDocument(); + expect(screen.queryByText(/\$40,000/)).not.toBeInTheDocument(); }); it('shows the three how-it-works steps and no invented social proof', async () => { diff --git a/client/src/test/LoginPage.test.tsx b/client/src/test/LoginPage.test.tsx index f45bf1d..86c4331 100644 --- a/client/src/test/LoginPage.test.tsx +++ b/client/src/test/LoginPage.test.tsx @@ -8,6 +8,7 @@ const { post } = vi.hoisted(() => ({ post: vi.fn() })); vi.mock('../api', () => ({ default: { post, get: vi.fn(), put: vi.fn(), delete: vi.fn() }, clearApiCache: vi.fn(), + setSessionExpiryHandler: vi.fn(), })); import LoginPage from '../pages/LoginPage'; diff --git a/client/src/test/RegisterPage.test.tsx b/client/src/test/RegisterPage.test.tsx index d891c9e..a2a60ff 100644 --- a/client/src/test/RegisterPage.test.tsx +++ b/client/src/test/RegisterPage.test.tsx @@ -8,6 +8,7 @@ const { post } = vi.hoisted(() => ({ post: vi.fn() })); vi.mock('../api', () => ({ default: { post, get: vi.fn(), put: vi.fn(), delete: vi.fn() }, clearApiCache: vi.fn(), + setSessionExpiryHandler: vi.fn(), })); import RegisterPage from '../pages/RegisterPage'; diff --git a/client/src/test/TeamDetailPage.test.tsx b/client/src/test/TeamDetailPage.test.tsx new file mode 100644 index 0000000..22df64e --- /dev/null +++ b/client/src/test/TeamDetailPage.test.tsx @@ -0,0 +1,60 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { render, screen } from '@testing-library/react'; +import { MemoryRouter, Route, Routes } from 'react-router-dom'; + +const { get } = vi.hoisted(() => ({ get: vi.fn() })); +vi.mock('../api', () => ({ + default: { get, post: vi.fn(), put: vi.fn() }, + clearApiCache: vi.fn(), + setSessionExpiryHandler: vi.fn(), +})); + +import TeamDetailPage from '../pages/TeamDetailPage'; +import { useAuthStore } from '../store/authStore'; + +const leader = { _id: 'leader-id', name: 'Priya Menon', college: 'MIT', hasAvatar: false }; +const applicant = { _id: 'applicant-id', name: 'Yuki Tanaka', college: 'Tokyo', hasAvatar: false }; +const team = { + _id: 'team-id', teamName: 'Neural Sync', description: 'Build a collaborative editor together.', + memberCount: 1, maxSize: 4, requiredSkills: [], status: 'open', + leader, members: [leader], hackathon: null, +}; + +function openTeam() { + return render( + + } /> + + ); +} + +beforeEach(() => { + get.mockReset(); + useAuthStore.setState({ + user: { ...applicant, id: 'applicant-id', branch: '', bio: '', skills: [], experience: 'beginner', isAvailable: true }, + token: 'token', isAuthenticated: true, initialized: true, + }); +}); + +describe('TeamDetailPage', () => { + it('shows a pending request after revisiting instead of another submit form', async () => { + get.mockImplementation((url: string) => Promise.resolve({ data: { data: url.endsWith('/mine') ? { status: 'pending' } : team } })); + openTeam(); + expect(await screen.findByRole('button', { name: 'Request pending' })).toBeDisabled(); + expect(screen.queryByRole('button', { name: 'Send join request' })).not.toBeInTheDocument(); + }); + + it('shows a declined request from the server', async () => { + get.mockImplementation((url: string) => Promise.resolve({ data: { data: url.endsWith('/mine') ? { status: 'rejected' } : team } })); + openTeam(); + expect(await screen.findByText(/Declined\. The team leader/)).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Send join request' })).not.toBeInTheDocument(); + }); + + it('shows membership when the roster contains the signed-in user', async () => { + get.mockResolvedValue({ data: { data: { ...team, members: [leader, applicant], memberCount: 2 } } }); + openTeam(); + expect(await screen.findByText(/You are on this team/)).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Send join request' })).not.toBeInTheDocument(); + }); +}); diff --git a/client/src/test/avatarCache.test.ts b/client/src/test/avatarCache.test.ts new file mode 100644 index 0000000..ef9aafd --- /dev/null +++ b/client/src/test/avatarCache.test.ts @@ -0,0 +1,41 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const { get } = vi.hoisted(() => ({ get: vi.fn() })); +vi.mock('../api', () => ({ + default: { get }, + clearApiCache: vi.fn(), + setSessionExpiryHandler: vi.fn(), +})); + +import { clearAvatarCache, loadAvatar } from '../utils/avatarCache'; +import { useAuthStore } from '../store/authStore'; + +beforeEach(() => { + localStorage.setItem('hackmatch_token', 'test-token'); + vi.stubGlobal('URL', { + ...URL, + createObjectURL: vi.fn(() => 'blob:avatar'), + revokeObjectURL: vi.fn(), + }); + get.mockReset(); +}); + +afterEach(() => { + clearAvatarCache(); + vi.unstubAllGlobals(); +}); + +describe('authenticated avatar cache', () => { + it('never creates an object URL for a request completing after logout', async () => { + let resolve!: (value: { data: Blob }) => void; + get.mockReturnValue(new Promise((done) => { resolve = done; })); + + const pending = loadAvatar('user-id'); + useAuthStore.getState().logout(); + resolve({ data: new Blob(['avatar'], { type: 'image/webp' }) }); + + await expect(pending).rejects.toThrow('cancelled'); + expect(URL.createObjectURL).not.toHaveBeenCalled(); + expect(get).toHaveBeenCalledTimes(1); + }); +}); diff --git a/client/src/test/sessionExpiry.test.ts b/client/src/test/sessionExpiry.test.ts new file mode 100644 index 0000000..a90e1a7 --- /dev/null +++ b/client/src/test/sessionExpiry.test.ts @@ -0,0 +1,46 @@ +import axios from 'axios'; +import { beforeEach, describe, expect, it } from 'vitest'; +import api from '../api'; +import { useAuthStore } from '../store/authStore'; +import { useToastStore } from '../store/toastStore'; + +beforeEach(() => { + localStorage.setItem('hackmatch_token', 'expired-token'); + window.history.replaceState({}, '', '/teams?skill=React'); + useToastStore.setState({ toasts: [] }); + useAuthStore.setState({ + token: 'expired-token', + user: null, + isAuthenticated: true, + initialized: true, + expiredPath: null, + }); +}); + +describe('session expiry', () => { + it('clears auth once for concurrent 401s, shows one toast, and retains the return path', async () => { + const previous = api.defaults.adapter; + api.defaults.adapter = async (config) => { + throw new axios.AxiosError('Unauthorized', 'ERR_BAD_RESPONSE', config, undefined, { + data: {}, + status: 401, + statusText: 'Unauthorized', + headers: {}, + config, + }); + }; + + try { + const results = await Promise.allSettled([api.get('/teams'), api.get('/users')]); + expect(results.map((result) => result.status)).toEqual(['rejected', 'rejected']); + expect(localStorage.getItem('hackmatch_token')).toBeNull(); + expect(useAuthStore.getState().expiredPath).toBe('/teams?skill=React'); + expect(useAuthStore.getState().isAuthenticated).toBe(false); + expect(useToastStore.getState().toasts).toHaveLength(1); + expect(useToastStore.getState().toasts[0].message).toBe('Session expired, please sign in again'); + expect(window.location.pathname).toBe('/teams'); + } finally { + api.defaults.adapter = previous; + } + }); +}); diff --git a/client/src/types/index.ts b/client/src/types/index.ts index 1cd86c3..09d9542 100755 --- a/client/src/types/index.ts +++ b/client/src/types/index.ts @@ -33,6 +33,11 @@ export interface HackathonSummary { isActive: boolean; } +export type PublicHackathon = Pick< + HackathonSummary, + '_id' | 'title' | 'date' | 'registrationDeadline' | 'location' | 'tags' +>; + export interface Hackathon extends HackathonSummary { registrationLink?: string; rules?: string; diff --git a/client/src/utils/avatarCache.ts b/client/src/utils/avatarCache.ts index 7fe4847..3b83380 100644 --- a/client/src/utils/avatarCache.ts +++ b/client/src/utils/avatarCache.ts @@ -2,6 +2,7 @@ import api from '../api'; const avatarUrls = new Map(); const pendingAvatars = new Map>(); +let generation = 0; function avatarKey(userId: string, version: string | undefined): string { const token = localStorage.getItem('hackmatch_token') || 'anonymous'; @@ -16,15 +17,19 @@ export async function loadAvatar(userId: string, version?: string): Promise { + if (requestGeneration !== generation) { + throw new Error('Avatar request was cancelled.'); + } const url = URL.createObjectURL(response.data as Blob); avatarUrls.set(key, url); return url; }) .finally(() => { - pendingAvatars.delete(key); + if (pendingAvatars.get(key) === request) pendingAvatars.delete(key); }); pendingAvatars.set(key, request); @@ -32,6 +37,7 @@ export async function loadAvatar(userId: string, version?: string): Promise
{fieldErrors.teamName}
{fieldErrors.description}
{fieldErrors.maxSize}
{message}
No pending join requests.
No upcoming hackathons have been listed yet.
Hackathon team finder
- HackMatch is where hackathon participants show what they bring, find complementary teammates, and - build a roster before the event starts. -
Hackathon team finder / Build together
+ HackMatch is where hackathon participants show what they bring, find complementary teammates, and + build a roster before the event starts. +
+ Sign in to open event details, browse teams, and view people. +
- Sign in to open event details, browse teams, and view people. -
Pick a hackathon that fits your interests.
Find teammates whose skills complement yours.
Join a roster and build something together.
{hackathon.location}
Registration closes {formatDate(hackathon.registrationDeadline)}
- Your session expired. Sign in again. + Session expired, please sign in again.
{fieldErrors.email}
{fieldErrors.password}
This is what teammates see when they search for you.
+
{error}
{fieldErrors.name}
{fieldErrors.college}
Checking your request status…
Declined. The team leader did not accept your request.
You are a member. Refresh the page to see the updated roster.
This team is full.