diff --git a/README.md b/README.md index b8b8762..cafc194 100755 --- a/README.md +++ b/README.md @@ -2,24 +2,26 @@ Find teammates for a hackathon, or host a team of your own. -HackMatch is a React and Express team finder. Guests can explore a small upcoming-event preview; an account unlocks event details, teammate search, team browsing, and join requests. The interface uses a warm editorial style with light and dark themes. +HackMatch is a React and Express team finder. Guests can explore a small upcoming-event preview; an account unlocks event details, teammate search, team browsing, join requests, follows, notifications, and team chat. The interface uses a warm editorial style with light and dark themes. ## What works today - **Public landing page:** introduction and up to three upcoming events. Preview cards show only the event name, date, registration deadline, location, and tags; opening details requires sign-in. - **Accounts and profiles:** email/password registration and sign-in, skills, experience, bio, links, availability, and optional uploaded avatar. There is no OAuth sign-in. -- **Hackathons:** searchable, filterable, paginated event list and details, with a link to find teams for an event. -- **People and teams:** search people by name, college, bio, or skill; browse and filter teams; host a team, set needed skills, and view its roster. +- **Hackathons:** searchable, filterable, paginated event list with a city filter remembered in `localStorage`, details pages, an Apply/Official-site link that opens safely in a new tab, and a small cached community-news section when the feed is available. +- **People and teams:** search people by name, college, bio, or skill (including custom skills); browse and filter teams; follow people; host a team, set needed skills, and view its roster. - **Join requests:** applicants see their own current request status on the team page. Leaders accept or decline pending requests on their dashboard or the team page. Dashboard teams, requests, and events load and retry independently. +- **Notifications:** navbar bell with an unread badge and the latest 20 notifications, a full paginated page, mark-one and mark-all actions, and links to the related page. Notifications are created for join requests, accepted/declined requests, new followers, and new team-chat messages. Chat messages are grouped per team and skipped while that chat is open. +- **Team chat:** members-only Chat tab with Socket.IO, JWT-authenticated sockets, server-side membership checks, the last 50 messages plus older history on scroll, plain-text messages up to 1000 characters, and a 5-messages-per-5-seconds limit. +- **Admin panel:** `/admin` for admins with Hackathons, Teams, Users, Admins, and Audit log tabs. Admins can create/edit/hide/delete hackathons, delete teams and users, promote/demote admins, run an import sync, and inspect the last 50 admin actions. Destructive actions confirm first, and the last admin cannot be demoted or deleted. +- **Hackathon feed sync:** a server-side import from Hack Club's public upcoming-events JSON every 6 hours, on startup when the last sync is stale, and on demand from the admin panel. Imported rows are deduplicated and admin-created/edited rows are never overwritten. - **Session handling:** expired sessions show one notification and return you to the page you were visiting after sign-in. Logging out clears cached API data and avatars, including pending avatar loads. -- **Accessibility and performance:** keyboard-accessible menus, associated form errors, reduced-motion support, larger touch targets, paginated responses, and short-lived caches. - -The database schema also contains models for messages, notifications, project ideas, and badges; these are **not** shipped product features. Authentication uses JWTs, not OAuth or a user-facing roles system. +- **Accessibility and performance:** keyboard-accessible menus, notification bell, and chat; associated form errors; live regions; reduced-motion support; larger touch targets; paginated responses; lazy-loaded admin and chat chunks; and short-lived caches. ## Stack -- **Client:** React 19, TypeScript, Vite, Tailwind CSS v4, Zustand, React Router -- **API:** Node.js 20, Express, TypeScript, Prisma, PostgreSQL, Zod, JWT +- **Client:** React 19, TypeScript, Vite, Tailwind CSS v4, Zustand, React Router, Socket.IO client +- **API:** Node.js 20, Express, TypeScript, Prisma, PostgreSQL, Zod, JWT, Socket.IO, node-cron - **Testing:** Vitest, Supertest, Testing Library, Playwright ## Run locally @@ -38,7 +40,7 @@ npm run dev The client runs at **http://localhost:3000** and the API at **http://localhost:5000**. The example `DATABASE_URL` matches the Docker Compose Postgres service on port 5432; change `backend/.env` if your local database uses another address or credentials. Set a local `JWT_SECRET` of at least 32 characters. Seeding is an explicit command; `AUTO_SEED` defaults to `false`. -Prisma migrations in `backend/prisma/migrations` define the schema. The repeatable `npm run db:seed` command populates **12 demo users, 12 hackathons, 12 teams, 12 pending requests, 27 team memberships, and 13 event registrations**. Demo records are seed data, not schema migrations: run both migration and seed commands on each fresh database. Resetting a database permanently deletes its accounts and teams; only do this to a disposable **local** database you intend to replace. +Prisma migrations in `backend/prisma/migrations` define the schema. The repeatable `npm run db:seed` command populates **13 demo users (1 admin), 12 hackathons, 12 teams, pending requests and memberships, 7 follows, 10 chat messages, and 6 notifications**. Seed data uses fixed IDs and upserts, so it is idempotent and does not overwrite accounts or teams you create later. Demo records are seed data, not schema migrations: run both migration and seed commands on each fresh database. Resetting a database permanently deletes its accounts and teams; only do this to a disposable **local** database you intend to replace. ### Demo accounts @@ -46,12 +48,41 @@ Seeded accounts use the password `Demo1234!`. | Try | Email | | --- | --- | +| Admin | `admin@hackmatch.dev` | | Regular user | `aisha.rahman@hackmatch.dev` | | Team leader (Neural Sync) | `priya.menon@example.com` | | Team leader (CareBridge AI) | `marcus.lee@example.com` | | Applicant with a pending request | `yuki.tanaka@example.com` | -Priya's Neural Sync team and Marcus's CareBridge AI team have pending requests in the seed data, so you can try the leader flow without creating new accounts. +Priya's Neural Sync team and Marcus's CareBridge AI team have pending requests and seeded chat messages, so you can try the leader and chat flows without creating new accounts. + +### Admin setup + +The local seed creates one admin (`admin@hackmatch.dev`) with the demo password above. This account is for local demos only; do not reuse that password in production. + +For production, register the person normally, then promote their existing account by email: + +```bash +cd backend +npm run make-admin -- person@example.com +``` + +The script updates `User.role` to `admin`. Every admin API request re-reads the role from the database, so an old JWT does not keep admin access after a demotion. + +## Hackathon and news sources + +Source behavior was verified by making real requests while building this feature: + +| Source | Result | Decision | +| --- | --- | --- | +| Hack Club upcoming events JSON (`hackathons.hackclub.com/api/events/upcoming`) | `200` JSON with upcoming events | **Used** for hackathon imports | +| dev.to articles API (`dev.to/api/articles?tag=hackathon`) | `200` JSON | **Used** for the community-news list, cached server-side | +| Kontests API | `404` | Not used | +| Brabble Developers API | DNS resolution failure | Not used | +| Devpost / MLH public listings | HTML listing pages only | Not scraped | +| NewsAPI / GNews | Requires a key and has production restrictions | Not used | + +No third-party call is made from the browser. The API fetches, normalizes, and caches external data. A failing source is isolated: it records an error in the sync status but never breaks the app or another source. Imports are deduplicated by `source` plus `externalId`, and rows with `isEditedByAdmin` are skipped. ## Tests @@ -66,11 +97,13 @@ npm run test:e2e Backend tests need a **separate local** Postgres database configured with `DATABASE_URL_TEST` (see `backend/.env.example`). Playwright needs a separate local database set with `E2E_DATABASE_URL`; its default is `hackmatch_e2e` on `localhost:5433`, so override it if you use the Compose database on port 5432. Create these test databases before running the suites. Playwright builds, migrates, and seeds its E2E database; it starts the API on port 5000 and the client on port 3100. Stop other servers on those ports first so it does not reuse an older instance. The test configuration rejects Neon/production-style database URLs. -For backend coverage, run `npm --prefix backend run test:coverage`. CI runs backend build and coverage tests, client lint/build/tests, and the Playwright journeys on pushes to `main` and `polish-v2` and on pull requests. +The automated suites cover admin authorization and the last-admin rule, notification ownership/grouping/polling, follow rules and counts, skill normalization, chat membership/rate limits/history, hackathon normalization/dedupe/edit protection/source failure/filters, and two-browser-context chat plus admin and follow/custom-skill journeys. + +For backend coverage, run `npm --prefix backend run test:coverage`. CI runs backend build and coverage tests, client lint/build/tests, and the Playwright journeys on pushes and pull requests. ## API overview -Except for the public event preview and auth endpoints, these routes require a JWT. +Except for the public event preview, cities, news, and auth endpoints, these routes require a JWT. | Method | Route | Purpose | | --- | --- | --- | @@ -78,23 +111,88 @@ Except for the public event preview and auth endpoints, these routes require a J | `POST` | `/api/auth/login` | Sign in and receive a JWT | | `GET` | `/api/auth/me` | Current user | | `GET` | `/api/hackathons/upcoming` | Public upcoming preview (`limit`, max 6; restricted fields) | -| `GET` | `/api/hackathons` | Paginated events (`search`, `mode`, `upcoming`, `tag`) | +| `GET` | `/api/hackathons` | Paginated events (`search`, `mode`, `city`, `tag`, `upcoming`) | +| `GET` | `/api/hackathons/cities` | Distinct city options for the filter | +| `GET` | `/api/hackathons/news` | Cached dev.to hackathon articles | | `GET` | `/api/hackathons/:id` | Event details | -| `GET` | `/api/users` | Paginated people (`search`, `skill`, `experience`) | -| `GET` | `/api/users/:id` | Profile details | +| `POST` | `/api/hackathons/:id/register` | Toggle event registration | +| `GET` | `/api/users` | Paginated people (`search`, `skill`, `experience`, `following`) | +| `GET` | `/api/users/:id` | Profile details with follower counts | | `GET` | `/api/users/:id/avatar` | Cached WEBP avatar | -| `PUT` | `/api/users/profile` | Update profile or avatar | +| `PUT` | `/api/users/profile` | Update profile, avatar, or skills | +| `POST` | `/api/users/:id/follow` | Follow a person | +| `DELETE` | `/api/users/:id/follow` | Unfollow a person | +| `GET` | `/api/users/:id/followers` | Paginated followers | +| `GET` | `/api/users/:id/following` | Paginated following | | `GET` | `/api/teams` | Paginated teams (`search`, `skill`, `hackathonId`, `memberId`) | | `POST` | `/api/teams` | Create a team | | `GET` | `/api/teams/:id` | Team details and members | | `PUT` | `/api/teams/:id` | Update team (leader) | | `DELETE` | `/api/teams/:id` | Disband team (leader) | +| `GET` | `/api/teams/:id/messages` | Chat history (`before`, `limit`; members only) | | `GET` | `/api/requests` | Received or sent requests | | `POST` | `/api/requests` | Send a join request | | `GET` | `/api/requests/team/:teamId/mine` | Current user's latest join-request status only | | `GET` | `/api/requests/team/:teamId` | Pending team requests (leader) | | `PUT` | `/api/requests/:id/respond` | Accept or decline (leader) | +| `GET` | `/api/notifications` | Paginated notifications and unread count | +| `GET` | `/api/notifications/unread-count` | Fresh unread count | +| `PUT` | `/api/notifications/:id/read` | Mark one as read (owner only) | +| `PUT` | `/api/notifications/read-all` | Mark all as read | +| `GET` | `/api/admin/hackathons` | Admin hackathon list (`search`, pagination) | +| `POST` | `/api/admin/hackathons` | Create a hackathon | +| `PUT` | `/api/admin/hackathons/:id` | Edit or hide a hackathon | +| `DELETE` | `/api/admin/hackathons/:id` | Delete a hackathon | +| `POST` | `/api/admin/hackathons/sync` | Run the import now | +| `GET` | `/api/admin/hackathons/sync-status` | Last sync time and errors | +| `GET` | `/api/admin/teams` | Admin team list | +| `DELETE` | `/api/admin/teams/:id` | Delete a team | +| `GET` | `/api/admin/users` | Admin user list | +| `DELETE` | `/api/admin/users/:id` | Delete a user (last admin blocked) | +| `POST` | `/api/admin/users/:id/promote` | Promote to admin | +| `POST` | `/api/admin/users/:id/demote` | Demote to user (last admin blocked) | +| `GET` | `/api/admin/audit` | Last 50 audit-log entries | + +All `/api/admin/*` routes return `403` for authenticated non-admins and `401` without a token. + +### Socket.IO events + +The client connects with the JWT in the handshake auth payload. The server verifies the token and the user on connect. + +| Direction | Event | Purpose | +| --- | --- | --- | +| Client → server | `chat:join` | Join a team room after a server-side membership check | +| Client → server | `chat:leave` | Leave a team room | +| Client → server | `chat:message` | Send `{ teamId, content }` with an acknowledgement callback | +| Server → client | `chat:new` | Broadcast a persisted message to the team room | +| Server → client | `chat:error` | Report validation, membership, or rate-limit errors | +| Server → client | `chat:removed` | Tell clients a team/room is no longer available | +| Server → client | `notification:new` | Push a new notification to the user room | ## Deployment configuration -The repository includes `render.yaml` and client build configuration for a Render API and Vercel client, but **their presence does not mean the app is deployed**. For a deployment, provide PostgreSQL through `DATABASE_URL`, a strong `JWT_SECRET`, the client origin in `CLIENT_URL`, and `AUTO_SEED=false` on the API. Apply Prisma migrations before starting the API. Set the client's build-time `VITE_API_URL` to the API origin. Do not put database secrets in client environment variables. +The repository includes `render.yaml` and client build configuration for a Render API and Vercel client, but **their presence does not mean the app is deployed**. + +Production checklist: + +1. Apply the additive migration with the direct (non-pooled) Neon connection string: + ```bash + cd backend + DATABASE_URL="postgresql://...neon.tech/neondb?sslmode=require" npx prisma migrate deploy + ``` +2. Register the first production admin normally, then promote them: + ```bash + cd backend + DATABASE_URL="postgresql://...neon.tech/neondb?sslmode=require" npm run make-admin -- person@example.com + ``` +3. Set these API environment variables on Render: + - `DATABASE_URL` — Neon direct connection string with `?sslmode=require` + - `JWT_SECRET` — at least 32 random characters + - `CLIENT_URL` — the Vercel origin, e.g. `https://your-app.vercel.app` + - `AUTO_SEED=false` + - `NODE_ENV=production` +4. Set the client variable on Vercel: + - `VITE_API_URL` — the Render API origin, e.g. `https://your-service.onrender.com` +5. Redeploy/restart the API after the migration. + +Do not put database secrets in client environment variables. Do not run `prisma migrate reset` or `db:seed` against production. The import cron runs inside the API process every 6 hours, and the startup check catches up after Render free-tier sleep. diff --git a/backend/.env.example b/backend/.env.example index 0159a7f..0304ad8 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -16,6 +16,11 @@ DATABASE_URL="postgresql://postgres:postgrespassword@localhost:5432/hackmatch?sc # The test setup refuses to run against a Neon/production URL. DATABASE_URL_TEST="postgresql://postgres:postgrespassword@localhost:5433/hackmatch_test?schema=public" +# Separate local database used by Playwright. Export this in the shell when +# running `npm run test:e2e`; the Playwright config defaults to the value below. +# The Playwright config also refuses Neon/production-style URLs. +E2E_DATABASE_URL="postgresql://postgres:postgrespassword@localhost:5433/hackmatch_e2e?schema=public" + # Authentication & Security # Generate a secure 256-bit secret key in production (e.g., using: openssl rand -base64 32) JWT_SECRET="your_jwt_secret_key_minimum_32_characters_for_hs256_security" diff --git a/backend/package-lock.json b/backend/package-lock.json index 32f1dfd..6353028 100755 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -18,7 +18,9 @@ "express-rate-limit": "^7.5.0", "helmet": "^8.1.0", "jsonwebtoken": "^9.0.2", + "node-cron": "^4.6.0", "prisma": "^6.4.1", + "socket.io": "^4.8.4", "zod": "^3.24.2" }, "devDependencies": { @@ -28,6 +30,7 @@ "@types/express": "^4.17.21", "@types/jsonwebtoken": "^9.0.9", "@types/node": "^22.13.9", + "@types/node-cron": "^3.0.11", "@types/supertest": "^6.0.3", "@vitest/coverage-v8": "^3.2.4", "nodemon": "^3.1.9", @@ -1106,6 +1109,12 @@ "win32" ] }, + "node_modules/@socket.io/component-emitter": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz", + "integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==", + "license": "MIT" + }, "node_modules/@standard-schema/spec": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", @@ -1193,7 +1202,6 @@ "version": "2.8.19", "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.19.tgz", "integrity": "sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg==", - "dev": true, "dependencies": { "@types/node": "*" } @@ -1275,11 +1283,17 @@ "version": "22.20.4", "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.4.tgz", "integrity": "sha512-zJRE40jpHtKqE/C4fgHrAKQLJuSpzEnP9ff9Y7YtoR3Wd2pwqzlekDeEuUQXjRd+QCYnVnNwuJYmhdk9XV8gvA==", - "dev": true, "dependencies": { "undici-types": "~6.21.0" } }, + "node_modules/@types/node-cron": { + "version": "3.0.11", + "resolved": "https://registry.npmjs.org/@types/node-cron/-/node-cron-3.0.11.tgz", + "integrity": "sha512-0ikrnug3/IyneSHqCBeslAhlK2aBfYek1fGo4bP4QnZPmiqSGRK+Oy7ZMisLWkesffJvQ1cqAcBnJC+8+nxIAg==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/qs": { "version": "6.15.1", "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.15.1.tgz", @@ -1346,6 +1360,15 @@ "@types/superagent": "^8.1.0" } }, + "node_modules/@types/ws": { + "version": "8.18.2", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz", + "integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@vitest/coverage-v8": { "version": "3.2.7", "resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-3.2.7.tgz", @@ -2200,6 +2223,58 @@ "node": ">= 0.8" } }, + "node_modules/engine.io": { + "version": "6.6.13", + "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.6.13.tgz", + "integrity": "sha512-KoGsH77uceU1N1dyTEYgHTsEk9aEpwraBlzGtgph/OiCX5v3S27h/uwqKi8K2QLxWNoHDKWE/jW0bWbQrwwSmQ==", + "license": "MIT", + "dependencies": { + "@types/cors": "^2.8.12", + "@types/node": ">=10.0.0", + "@types/ws": "^8.5.12", + "accepts": "~1.3.4", + "cookie": "~0.7.2", + "cors": "~2.8.5", + "debug": "~4.4.1", + "engine.io-parser": "~5.2.1", + "ws": "^8.23.0" + }, + "engines": { + "node": ">=10.2.0" + } + }, + "node_modules/engine.io-parser": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.3.tgz", + "integrity": "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/engine.io/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/engine.io/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, "node_modules/es-define-property": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", @@ -3159,6 +3234,15 @@ "node": ">= 0.6" } }, + "node_modules/node-cron": { + "version": "4.6.0", + "resolved": "https://registry.npmjs.org/node-cron/-/node-cron-4.6.0.tgz", + "integrity": "sha512-Si/bzYiKRHOB8/a99T2+SDGN582ONDMSTlJr5oCkT6GtnqPjZ2s10eoQRYkW9ZHwjVxONL+W8Fb+qR0AHMQsdg==", + "license": "ISC", + "engines": { + "node": ">=20" + } + }, "node_modules/node-fetch-native": { "version": "1.6.7", "resolved": "https://registry.npmjs.org/node-fetch-native/-/node-fetch-native-1.6.7.tgz", @@ -3778,6 +3862,115 @@ "node": ">=10" } }, + "node_modules/socket.io": { + "version": "4.8.4", + "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.8.4.tgz", + "integrity": "sha512-9ZV9zg8vN8hO3Y25DhR7nUkJ1VDnBhq5O/JrXhFT9s6+F0gqytSASTHVfCFc2mJXaTfARroErplXlzFWwETZqQ==", + "license": "MIT", + "dependencies": { + "accepts": "~1.3.4", + "cors": "~2.8.5", + "debug": "~4.4.1", + "engine.io": "~6.6.0", + "socket.io-adapter": "~2.5.2", + "socket.io-parser": "~4.2.4" + }, + "engines": { + "node": ">=10.2.0" + } + }, + "node_modules/socket.io-adapter": { + "version": "2.5.9", + "resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.5.9.tgz", + "integrity": "sha512-SEuWaysGaqPiGApa6nvwVI5u/7k0U6em6XF4A4RbR8GY1kZUbNDAzw6v9HK/cZ0UQFcdayjLjBYxKjaB1/yPQw==", + "license": "MIT", + "dependencies": { + "debug": "~4.4.1", + "ws": "^8.23.0" + } + }, + "node_modules/socket.io-adapter/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/socket.io-adapter/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/socket.io-parser": { + "version": "4.2.7", + "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.7.tgz", + "integrity": "sha512-IH/iSeO9T6gz1KkFleGDWkG9N3dl4jXVYUtMhIqH10Md0ttMer8nUNWiP1DKuNrybD2xBrixLJdCC9J6ECoYkg==", + "license": "MIT", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.4.1" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/socket.io-parser/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/socket.io-parser/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/socket.io/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/socket.io/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, "node_modules/source-map-js": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.3.0.tgz", @@ -4374,8 +4567,7 @@ "node_modules/undici-types": { "version": "6.21.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", - "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", - "dev": true + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==" }, "node_modules/unpipe": { "version": "1.0.0", @@ -4972,6 +5164,27 @@ "dev": true, "license": "ISC" }, + "node_modules/ws": { + "version": "8.23.1", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.1.tgz", + "integrity": "sha512-1rzWDSN0NOi3tpwgHsQExjWRoKUGtjCkJ2gZRaaRtzhYLboMytOI9pj9PU7yCgY37auqdd4OyLofZDbkeuZmPA==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, "node_modules/yn": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", diff --git a/backend/package.json b/backend/package.json index 182cd0e..2fb38b8 100755 --- a/backend/package.json +++ b/backend/package.json @@ -14,6 +14,7 @@ "db:push": "prisma db push", "db:generate": "prisma generate", "db:seed": "ts-node src/seed.ts", + "make-admin": "ts-node src/scripts/make-admin.ts", "migrate": "prisma migrate deploy", "migrate:dev": "prisma migrate dev", "test": "vitest run", @@ -30,7 +31,9 @@ "express-rate-limit": "^7.5.0", "helmet": "^8.1.0", "jsonwebtoken": "^9.0.2", + "node-cron": "^4.6.0", "prisma": "^6.4.1", + "socket.io": "^4.8.4", "zod": "^3.24.2" }, "devDependencies": { @@ -40,6 +43,7 @@ "@types/express": "^4.17.21", "@types/jsonwebtoken": "^9.0.9", "@types/node": "^22.13.9", + "@types/node-cron": "^3.0.11", "@types/supertest": "^6.0.3", "@vitest/coverage-v8": "^3.2.4", "nodemon": "^3.1.9", diff --git a/backend/prisma/migrations/20261205000000_features_v3/migration.sql b/backend/prisma/migrations/20261205000000_features_v3/migration.sql new file mode 100644 index 0000000..bb1a52e --- /dev/null +++ b/backend/prisma/migrations/20261205000000_features_v3/migration.sql @@ -0,0 +1,83 @@ +-- AlterTable +ALTER TABLE "Hackathon" ADD COLUMN "city" TEXT, +ADD COLUMN "endDate" TEXT, +ADD COLUMN "externalId" TEXT, +ADD COLUMN "isEditedByAdmin" BOOLEAN NOT NULL DEFAULT false, +ADD COLUMN "isExternal" BOOLEAN NOT NULL DEFAULT false, +ADD COLUMN "source" TEXT, +ADD COLUMN "sourceUrl" TEXT, +ADD COLUMN "websiteUrl" TEXT; + +-- AlterTable +ALTER TABLE "Notification" ADD COLUMN "count" INTEGER NOT NULL DEFAULT 1, +ADD COLUMN "groupKey" TEXT, +ADD COLUMN "link" TEXT, +ADD COLUMN "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP; + +-- CreateTable +CREATE TABLE "Follow" ( + "id" TEXT NOT NULL, + "followerId" TEXT NOT NULL, + "followingId" TEXT NOT NULL, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "Follow_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "AuditLog" ( + "id" TEXT NOT NULL, + "actorId" TEXT, + "action" TEXT NOT NULL, + "targetType" TEXT NOT NULL, + "targetId" TEXT, + "details" TEXT, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "AuditLog_pkey" PRIMARY KEY ("id") +); + +-- CreateTable +CREATE TABLE "SyncState" ( + "id" TEXT NOT NULL, + "lastSyncAt" TIMESTAMP(3), + "lastError" TEXT, + "lastDurationMs" INTEGER, + "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "SyncState_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE INDEX "Follow_followingId_idx" ON "Follow"("followingId"); + +-- CreateIndex +CREATE UNIQUE INDEX "Follow_followerId_followingId_key" ON "Follow"("followerId", "followingId"); + +-- CreateIndex +CREATE INDEX "AuditLog_createdAt_idx" ON "AuditLog"("createdAt"); + +-- CreateIndex +CREATE INDEX "AuditLog_targetType_idx" ON "AuditLog"("targetType"); + +-- CreateIndex +CREATE INDEX "Hackathon_city_idx" ON "Hackathon"("city"); + +-- CreateIndex +CREATE INDEX "Hackathon_source_idx" ON "Hackathon"("source"); + +-- CreateIndex +CREATE UNIQUE INDEX "Hackathon_source_externalId_key" ON "Hackathon"("source", "externalId"); + +-- CreateIndex +CREATE INDEX "Notification_userId_groupKey_idx" ON "Notification"("userId", "groupKey"); + +-- AddForeignKey +ALTER TABLE "Follow" ADD CONSTRAINT "Follow_followerId_fkey" FOREIGN KEY ("followerId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Follow" ADD CONSTRAINT "Follow_followingId_fkey" FOREIGN KEY ("followingId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "AuditLog" ADD CONSTRAINT "AuditLog_actorId_fkey" FOREIGN KEY ("actorId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE; + diff --git a/backend/prisma/migrations/20261205001000_backfill_hackathon_location/migration.sql b/backend/prisma/migrations/20261205001000_backfill_hackathon_location/migration.sql new file mode 100644 index 0000000..4025dec --- /dev/null +++ b/backend/prisma/migrations/20261205001000_backfill_hackathon_location/migration.sql @@ -0,0 +1,9 @@ +-- Backfill the new location fields for hackathons that existed before this feature. +-- Only NULL values are touched, so later admin edits and imported rows are untouched. +UPDATE "Hackathon" +SET "city" = CASE WHEN "mode" = 'online' THEN 'Online' ELSE "location" END +WHERE "city" IS NULL; + +UPDATE "Hackathon" +SET "endDate" = "date" +WHERE "endDate" IS NULL; diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index a1037c3..5f1d0de 100755 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -38,6 +38,9 @@ model User { notifications Notification[] projectIdeas ProjectIdea[] badges Badge[] + following Follow[] @relation("FollowFollower") + followers Follow[] @relation("FollowFollowing") + auditLogs AuditLog[] @relation("AuditActor") @@index([isAvailable]) @@index([role]) @@ -59,15 +62,26 @@ model Hackathon { registrationLink String? rules String? isActive Boolean @default(true) + endDate String? + city String? + websiteUrl String? + source String? + sourceUrl String? + externalId String? + isExternal Boolean @default(false) + isEditedByAdmin Boolean @default(false) createdAt DateTime @default(now()) updatedAt DateTime @updatedAt teams Team[] participants HackathonParticipant[] + @@unique([source, externalId]) @@index([date]) @@index([isActive]) @@index([mode]) + @@index([city]) + @@index([source]) } model Team { @@ -159,14 +173,55 @@ model Notification { id String @id @default(uuid()) userId String text String - type String // join_request, invitation, acceptance, rejection, deadline, left_team, custom + type String // join_request, request_accepted, request_rejected, follow, team_chat, invitation, deadline, left_team, custom + link String? + groupKey String? + count Int @default(1) isRead Boolean @default(false) createdAt DateTime @default(now()) + updatedAt DateTime @default(now()) @updatedAt user User @relation(fields: [userId], references: [id], onDelete: Cascade) @@index([userId, createdAt]) @@index([userId, isRead]) + @@index([userId, groupKey]) +} + +model Follow { + id String @id @default(uuid()) + followerId String + followingId String + createdAt DateTime @default(now()) + + follower User @relation("FollowFollower", fields: [followerId], references: [id], onDelete: Cascade) + following User @relation("FollowFollowing", fields: [followingId], references: [id], onDelete: Cascade) + + @@unique([followerId, followingId]) + @@index([followingId]) +} + +model AuditLog { + id String @id @default(uuid()) + actorId String? + action String + targetType String + targetId String? + details String? + createdAt DateTime @default(now()) + + actor User? @relation("AuditActor", fields: [actorId], references: [id], onDelete: SetNull) + + @@index([createdAt]) + @@index([targetType]) +} + +model SyncState { + id String @id + lastSyncAt DateTime? + lastError String? + lastDurationMs Int? + updatedAt DateTime @default(now()) @updatedAt } model ProjectIdea { diff --git a/backend/src/app.ts b/backend/src/app.ts index 2f5e07d..80dad5b 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -12,6 +12,8 @@ import userRoutes from './routes/userRoutes'; import teamRoutes from './routes/teamRoutes'; import hackathonRoutes from './routes/hackathonRoutes'; import requestRoutes from './routes/requestRoutes'; +import adminRoutes from './routes/adminRoutes'; +import notificationRoutes from './routes/notificationRoutes'; export function createApp() { const app = express(); @@ -29,7 +31,6 @@ export function createApp() { app.use(cors({ origin: parseCorsOrigins(process.env.CLIENT_URL) })); app.use(express.json({ limit: '400kb' })); app.use(express.urlencoded({ extended: true, limit: '400kb' })); - app.get('/api/health', (req, res) => { res.status(200).json({ status: 'UP', @@ -39,12 +40,13 @@ export function createApp() { }); app.use('/api', apiRateLimiter); - app.use('/api/auth', authRoutes); app.use('/api/users', userRoutes); app.use('/api/teams', teamRoutes); app.use('/api/hackathons', hackathonRoutes); app.use('/api/requests', requestRoutes); + app.use('/api/admin', adminRoutes); + app.use('/api/notifications', notificationRoutes); app.use(notFound); app.use(errorHandler); diff --git a/backend/src/controllers/adminController.ts b/backend/src/controllers/adminController.ts new file mode 100644 index 0000000..22e681e --- /dev/null +++ b/backend/src/controllers/adminController.ts @@ -0,0 +1,377 @@ +import { Response } from 'express'; +import { prisma } from '../config/db'; +import { cache } from '../config/cache'; +import { formatHackathonSummary, formatTeamSummary, formatUserSummary } from '../utils/formatters'; +import { hackathonSummarySelect, teamSummaryInclude, userSummarySelect } from '../utils/queries'; +import { AuthRequest } from '../middleware/auth'; +import { emitToRoom, teamRoom, disconnectUserSockets } from '../services/realtime'; +import { getSyncStatus, syncHackathons } from '../services/hackathonSyncService'; + +type AuthHandler = (req: AuthRequest, res: Response) => Promise; + +async function audit(actorId: string | undefined, action: string, targetType: string, targetId?: string, details?: string) { + if (!actorId) return; + await prisma.auditLog.create({ + data: { actorId, action, targetType, targetId, details }, + }); +} + +async function clearHackathonCaches() { + await Promise.all([ + cache.delPattern('hackathons_query'), + cache.delPattern('hackathons_upcoming'), + cache.delPattern('hackathon_detail'), + ]); +} + +function hackathonData(body: Record) { + const mode = body.mode as string | undefined; + const city = (body.city as string | undefined) || ''; + const data: Record = { + title: body.title, + description: body.description, + organizer: (body.organizer as string | undefined)?.trim() || 'HackMatch', + date: body.date, + endDate: (body.endDate as string | undefined) || null, + registrationDeadline: body.registrationDeadline, + mode: mode || 'online', + city: city || null, + location: (body.location as string | undefined)?.trim() + || (mode === 'online' ? 'Online' : city || 'In person'), + prizePool: (body.prizePool as string | undefined)?.trim() || 'See official site', + websiteUrl: (body.websiteUrl as string | undefined) || null, + registrationLink: (body.websiteUrl as string | undefined) || (body.registrationLink as string | undefined) || null, + rules: (body.rules as string | undefined) || null, + minTeamSize: typeof body.minTeamSize === 'number' ? body.minTeamSize : 1, + maxTeamSize: typeof body.maxTeamSize === 'number' ? body.maxTeamSize : 4, + tags: JSON.stringify(Array.isArray(body.tags) ? body.tags : []), + }; + return data; +} + +export async function listAdminHackathons(req: AuthRequest, res: Response) { + try { + const query = req.query as { search?: string; page?: number; limit?: number }; + const page = Number(query.page) || 1; + const limit = Math.min(Number(query.limit) || 20, 100); + const where: Record = {}; + if (query.search) { + where.OR = [ + { title: { contains: query.search, mode: 'insensitive' } }, + { organizer: { contains: query.search, mode: 'insensitive' } }, + { city: { contains: query.search, mode: 'insensitive' } }, + ]; + } + + const [hackathons, total] = await Promise.all([ + prisma.hackathon.findMany({ + where, + skip: (page - 1) * limit, + take: limit, + orderBy: { date: 'asc' }, + select: hackathonSummarySelect, + }), + prisma.hackathon.count({ where }), + ]); + + return res.status(200).json({ + success: true, + data: { + hackathons: hackathons.map(formatHackathonSummary), + pagination: { total, page, limit, pages: Math.ceil(total / limit) }, + }, + message: 'Admin hackathons retrieved.', + }); + } catch { + return res.status(500).json({ success: false, data: null, message: 'Failed to fetch admin hackathons.' }); + } +} + +export async function createHackathon(req: AuthRequest, res: Response) { + try { + const hackathon = await prisma.hackathon.create({ + data: { + ...hackathonData(req.body), + isActive: req.body.isActive !== false, + isExternal: false, + isEditedByAdmin: true, + } as never, + select: hackathonSummarySelect, + }); + await clearHackathonCaches(); + await audit(req.user?.id, 'hackathon.create', 'hackathon', hackathon.id, hackathon.title ?? undefined); + return res.status(201).json({ success: true, data: formatHackathonSummary(hackathon), message: 'Hackathon created.' }); + } catch { + return res.status(500).json({ success: false, data: null, message: 'Failed to create hackathon.' }); + } +} + +export async function updateHackathon(req: AuthRequest, res: Response) { + try { + const existing = await prisma.hackathon.findUnique({ where: { id: req.params.id }, select: { id: true, title: true } }); + if (!existing) { + return res.status(404).json({ success: false, data: null, message: 'Hackathon not found.' }); + } + + const body = req.body as Record; + const data: Record = {}; + const fields = ['title', 'description', 'organizer', 'date', 'endDate', 'registrationDeadline', 'mode', 'city', 'location', 'prizePool', 'websiteUrl', 'registrationLink', 'rules', 'minTeamSize', 'maxTeamSize']; + for (const field of fields) { + if (body[field] !== undefined) data[field] = body[field] === '' ? null : body[field]; + } + if (body.tags !== undefined) data.tags = JSON.stringify(Array.isArray(body.tags) ? body.tags : []); + if (body.isActive !== undefined) data.isActive = Boolean(body.isActive); + data.isEditedByAdmin = true; + + const hackathon = await prisma.hackathon.update({ + where: { id: existing.id }, + data: data as never, + select: hackathonSummarySelect, + }); + await clearHackathonCaches(); + await audit(req.user?.id, 'hackathon.update', 'hackathon', hackathon.id, hackathon.title ?? undefined); + return res.status(200).json({ success: true, data: formatHackathonSummary(hackathon), message: 'Hackathon updated.' }); + } catch { + return res.status(500).json({ success: false, data: null, message: 'Failed to update hackathon.' }); + } +} + +export async function deleteHackathon(req: AuthRequest, res: Response) { + try { + const existing = await prisma.hackathon.findUnique({ where: { id: req.params.id }, select: { id: true, title: true } }); + if (!existing) { + return res.status(404).json({ success: false, data: null, message: 'Hackathon not found.' }); + } + await prisma.hackathon.delete({ where: { id: existing.id } }); + await clearHackathonCaches(); + await audit(req.user?.id, 'hackathon.delete', 'hackathon', existing.id, existing.title); + return res.status(200).json({ success: true, data: null, message: 'Hackathon deleted.' }); + } catch { + return res.status(500).json({ success: false, data: null, message: 'Failed to delete hackathon.' }); + } +} + +export async function listAdminTeams(req: AuthRequest, res: Response) { + try { + const query = req.query as { search?: string; page?: number; limit?: number }; + const page = Number(query.page) || 1; + const limit = Math.min(Number(query.limit) || 20, 100); + const where: Record = {}; + if (query.search) { + where.OR = [ + { teamName: { contains: query.search, mode: 'insensitive' } }, + { description: { contains: query.search, mode: 'insensitive' } }, + ]; + } + + const [teams, total] = await Promise.all([ + prisma.team.findMany({ + where, + skip: (page - 1) * limit, + take: limit, + orderBy: { createdAt: 'desc' }, + include: teamSummaryInclude, + }), + prisma.team.count({ where }), + ]); + + return res.status(200).json({ + success: true, + data: { + teams: teams.map(formatTeamSummary), + pagination: { total, page, limit, pages: Math.ceil(total / limit) }, + }, + message: 'Admin teams retrieved.', + }); + } catch { + return res.status(500).json({ success: false, data: null, message: 'Failed to fetch admin teams.' }); + } +} + +export async function deleteAdminTeam(req: AuthRequest, res: Response) { + try { + const team = await prisma.team.findUnique({ where: { id: req.params.id }, select: { id: true, teamName: true } }); + if (!team) { + return res.status(404).json({ success: false, data: null, message: 'Team not found.' }); + } + await prisma.team.delete({ where: { id: team.id } }); + await Promise.all([cache.delPattern('teams_query'), cache.delPattern(`team_detail:${team.id}`)]); + emitToRoom(teamRoom(team.id), 'chat:removed', { teamId: team.id, reason: 'This team was removed by an admin.' }); + await audit(req.user?.id, 'team.delete', 'team', team.id, team.teamName); + return res.status(200).json({ success: true, data: null, message: 'Team deleted.' }); + } catch { + return res.status(500).json({ success: false, data: null, message: 'Failed to delete team.' }); + } +} + +export async function listAdminUsers(req: AuthRequest, res: Response) { + try { + const query = req.query as { search?: string; page?: number; limit?: number }; + const page = Number(query.page) || 1; + const limit = Math.min(Number(query.limit) || 20, 100); + const where: Record = {}; + if (query.search) { + where.OR = [ + { name: { contains: query.search, mode: 'insensitive' } }, + { email: { contains: query.search, mode: 'insensitive' } }, + { college: { contains: query.search, mode: 'insensitive' } }, + ]; + } + + const [users, total] = await Promise.all([ + prisma.user.findMany({ + where, + skip: (page - 1) * limit, + take: limit, + orderBy: { createdAt: 'desc' }, + select: { + ...userSummarySelect, + email: true, + isBanned: true, + createdAt: true, + _count: { select: { followers: true, following: true, teamsLed: true } }, + }, + }), + prisma.user.count({ where }), + ]); + + return res.status(200).json({ + success: true, + data: { + users: users.map((user) => ({ + ...formatUserSummary(user), + email: user.email, + isBanned: user.isBanned, + followerCount: user._count.followers, + followingCount: user._count.following, + teamsLed: user._count.teamsLed, + createdAt: user.createdAt.toISOString(), + })), + pagination: { total, page, limit, pages: Math.ceil(total / limit) }, + }, + message: 'Admin users retrieved.', + }); + } catch { + return res.status(500).json({ success: false, data: null, message: 'Failed to fetch admin users.' }); + } +} + +async function adminCount() { + return prisma.user.count({ where: { role: 'admin' } }); +} + +export async function deleteAdminUser(req: AuthRequest, res: Response) { + try { + const user = await prisma.user.findUnique({ + where: { id: req.params.id }, + select: { id: true, name: true, email: true, role: true }, + }); + if (!user) { + return res.status(404).json({ success: false, data: null, message: 'User not found.' }); + } + if (user.role === 'admin' && (await adminCount()) <= 1) { + return res.status(400).json({ + success: false, + data: null, + message: 'The last admin cannot be deleted. Promote another admin first.', + }); + } + + await prisma.user.delete({ where: { id: user.id } }); + await Promise.all([cache.delPattern('users_query'), cache.delPattern('teams_query')]); + disconnectUserSockets(user.id); + await audit(req.user?.id, 'user.delete', 'user', user.id, user.email); + return res.status(200).json({ success: true, data: null, message: 'User deleted.' }); + } catch { + return res.status(500).json({ success: false, data: null, message: 'Failed to delete user.' }); + } +} + +async function changeRole(req: AuthRequest, res: Response, role: 'admin' | 'user') { + try { + const user = await prisma.user.findUnique({ + where: { id: req.params.id }, + select: { id: true, name: true, role: true }, + }); + if (!user) { + return res.status(404).json({ success: false, data: null, message: 'User not found.' }); + } + if (role === 'user' && user.role === 'admin' && (await adminCount()) <= 1) { + return res.status(400).json({ + success: false, + data: null, + message: 'The last admin cannot be demoted. Promote another admin first.', + }); + } + + const updated = await prisma.user.update({ where: { id: user.id }, data: { role } }); + await cache.delPattern('users_query'); + await audit(req.user?.id, role === 'admin' ? 'user.promote' : 'user.demote', 'user', user.id, updated.email); + return res.status(200).json({ + success: true, + data: formatUserSummary(updated), + message: role === 'admin' ? 'User promoted to admin.' : 'User demoted to user.', + }); + } catch { + return res.status(500).json({ success: false, data: null, message: 'Failed to change role.' }); + } +} + +export async function promoteUser(req: AuthRequest, res: Response) { + return changeRole(req, res, 'admin'); +} + +export async function demoteUser(req: AuthRequest, res: Response) { + return changeRole(req, res, 'user'); +} + +export async function listAuditLogs(req: AuthRequest, res: Response) { + try { + const logs = await prisma.auditLog.findMany({ + orderBy: { createdAt: 'desc' }, + take: 50, + include: { actor: { select: { id: true, name: true, email: true } } }, + }); + return res.status(200).json({ + success: true, + data: logs.map((log) => ({ + _id: log.id, + id: log.id, + action: log.action, + targetType: log.targetType, + targetId: log.targetId, + details: log.details, + actor: log.actor, + createdAt: log.createdAt.toISOString(), + })), + message: 'Audit log retrieved.', + }); + } catch { + return res.status(500).json({ success: false, data: null, message: 'Failed to fetch audit log.' }); + } +} + +export async function syncHackathonsNow(req: AuthRequest, res: Response) { + try { + const summary = await syncHackathons(); + await audit(req.user?.id, 'hackathon.sync', 'hackathon', undefined, JSON.stringify(summary)); + return res.status(200).json({ + success: true, + data: { ...summary, status: await getSyncStatus() }, + message: summary.errors.length ? 'Sync finished with source errors.' : 'Sync finished.', + }); + } catch { + return res.status(500).json({ success: false, data: null, message: 'Sync failed.' }); + } +} + +export async function getAdminSyncStatus(req: AuthRequest, res: Response) { + try { + return res.status(200).json({ success: true, data: await getSyncStatus(), message: 'Sync status retrieved.' }); + } catch { + return res.status(500).json({ success: false, data: null, message: 'Failed to fetch sync status.' }); + } +} + +// Keeps the handler type used by the router explicit. +export type { AuthHandler }; diff --git a/backend/src/controllers/authController.ts b/backend/src/controllers/authController.ts index 718a4cb..5a9cfd6 100755 --- a/backend/src/controllers/authController.ts +++ b/backend/src/controllers/authController.ts @@ -5,6 +5,7 @@ import { prisma } from '../config/db'; import { cache } from '../config/cache'; import { formatUserDetail } from '../utils/formatters'; import { userDetailSelect } from '../utils/queries'; +import { normalizeSkills } from '../utils/skills'; import { AuthRequest } from '../middleware/auth'; const JWT_EXPIRES_IN = process.env.JWT_EXPIRES_IN || '7d'; @@ -30,6 +31,11 @@ export async function register(req: Request, res: Response) { try { const { name, email, password, college, branch, bio, skills, experience, githubUrl, linkedinUrl, portfolioUrl } = req.body; + const normalized = normalizeSkills(skills); + if (normalized.error) { + return res.status(400).json({ success: false, data: null, message: normalized.error }); + } + const existingUser = await prisma.user.findUnique({ where: { email }, select: { id: true } }); if (existingUser) { return res.status(400).json({ @@ -48,7 +54,7 @@ export async function register(req: Request, res: Response) { college, branch: branch || '', bio: bio || '', - skills: JSON.stringify(Array.isArray(skills) ? skills : []), + skills: JSON.stringify(normalized.skills), experience: experience || 'beginner', githubUrl: githubUrl || '', linkedinUrl: linkedinUrl || '', diff --git a/backend/src/controllers/chatController.ts b/backend/src/controllers/chatController.ts new file mode 100644 index 0000000..67e9eef --- /dev/null +++ b/backend/src/controllers/chatController.ts @@ -0,0 +1,32 @@ +import { Response } from 'express'; +import { AuthRequest } from '../middleware/auth'; +import { getChatHistory } from '../services/chatService'; + +export async function getMessages(req: AuthRequest, res: Response) { + try { + const userId = req.user?.id; + if (!userId) { + return res.status(401).json({ success: false, data: null, message: 'Unauthorized' }); + } + + const teamId = req.params.id; + const query = req.query as { before?: string; limit?: number }; + const limit = Math.min(Math.max(Number(query.limit) || 50, 1), 50); + const result = await getChatHistory(userId, teamId, query.before, limit); + + if ('error' in result) { + if (result.error === 'team_not_found') { + return res.status(404).json({ success: false, data: null, message: 'Team not found.' }); + } + return res.status(403).json({ success: false, data: null, message: 'Only team members can read this chat.' }); + } + + return res.status(200).json({ + success: true, + data: result, + message: 'Messages retrieved.', + }); + } catch { + return res.status(500).json({ success: false, data: null, message: 'Failed to fetch messages.' }); + } +} diff --git a/backend/src/controllers/followController.ts b/backend/src/controllers/followController.ts new file mode 100644 index 0000000..34dc482 --- /dev/null +++ b/backend/src/controllers/followController.ts @@ -0,0 +1,126 @@ +import { Response } from 'express'; +import { prisma } from '../config/db'; +import { cache } from '../config/cache'; +import { formatUserSummary } from '../utils/formatters'; +import { userSummarySelect } from '../utils/queries'; +import { AuthRequest } from '../middleware/auth'; +import { notifyFollow } from '../services/notificationService'; + +async function clearUserCaches() { + await Promise.all([cache.delPattern('users_query'), cache.delPattern('teams_query')]); +} + +export async function followUser(req: AuthRequest, res: Response) { + try { + const followerId = req.user?.id; + const followingId = req.params.id; + if (!followerId) { + return res.status(401).json({ success: false, data: null, message: 'Unauthorized' }); + } + if (followerId === followingId) { + return res.status(400).json({ success: false, data: null, message: 'You cannot follow yourself.' }); + } + + const target = await prisma.user.findUnique({ where: { id: followingId }, select: { id: true, name: true } }); + if (!target) { + return res.status(404).json({ success: false, data: null, message: 'User not found.' }); + } + + const existing = await prisma.follow.findUnique({ + where: { followerId_followingId: { followerId, followingId } }, + select: { id: true }, + }); + if (existing) { + return res.status(400).json({ success: false, data: null, message: 'You already follow this user.' }); + } + + await prisma.follow.create({ data: { followerId, followingId } }); + const follower = await prisma.user.findUnique({ where: { id: followerId }, select: { name: true } }); + + await notifyFollow({ + followerId, + followerName: follower?.name || 'Someone', + followingId, + }); + await clearUserCaches(); + + return res.status(201).json({ success: true, data: { isFollowing: true }, message: 'Now following this user.' }); + } catch { + return res.status(500).json({ success: false, data: null, message: 'Failed to follow this user.' }); + } +} + +export async function unfollowUser(req: AuthRequest, res: Response) { + try { + const followerId = req.user?.id; + const followingId = req.params.id; + if (!followerId) { + return res.status(401).json({ success: false, data: null, message: 'Unauthorized' }); + } + + const result = await prisma.follow.deleteMany({ where: { followerId, followingId } }); + await clearUserCaches(); + + return res.status(200).json({ + success: true, + data: { isFollowing: false, removed: result.count > 0 }, + message: result.count > 0 ? 'Unfollowed this user.' : 'You were not following this user.', + }); + } catch { + return res.status(500).json({ success: false, data: null, message: 'Failed to unfollow this user.' }); + } +} + +async function listFollows(req: AuthRequest, res: Response, direction: 'followers' | 'following') { + try { + const userId = req.params.id; + const user = await prisma.user.findUnique({ where: { id: userId }, select: { id: true } }); + if (!user) { + return res.status(404).json({ success: false, data: null, message: 'User not found.' }); + } + + const page = Number((req.query as { page?: number }).page) || 1; + const limit = Number((req.query as { limit?: number }).limit) || 12; + const skip = (page - 1) * limit; + const where = direction === 'followers' ? { followingId: userId } : { followerId: userId }; + + const [rows, total] = await Promise.all([ + prisma.follow.findMany({ + where, + skip, + take: limit, + orderBy: { createdAt: 'desc' }, + select: { + createdAt: true, + follower: { select: userSummarySelect }, + following: { select: userSummarySelect }, + }, + }), + prisma.follow.count({ where }), + ]); + + const users = rows.map((row) => ({ + ...formatUserSummary(direction === 'followers' ? row.follower : row.following), + followedAt: row.createdAt.toISOString(), + })); + + return res.status(200).json({ + success: true, + data: { + users, + pagination: { total, page, limit, pages: Math.ceil(total / limit) }, + }, + message: direction === 'followers' ? 'Followers retrieved.' : 'Following retrieved.', + }); + } catch { + return res.status(500).json({ success: false, data: null, message: 'Failed to fetch follows.' }); + } +} + +export async function getFollowers(req: AuthRequest, res: Response) { + return listFollows(req, res, 'followers'); +} + +export async function getFollowing(req: AuthRequest, res: Response) { + return listFollows(req, res, 'following'); +} diff --git a/backend/src/controllers/hackathonController.ts b/backend/src/controllers/hackathonController.ts index 3ae1cf0..134dfde 100755 --- a/backend/src/controllers/hackathonController.ts +++ b/backend/src/controllers/hackathonController.ts @@ -5,6 +5,7 @@ import { formatHackathonDetail, formatHackathonSummary } from '../utils/formatte import { hackathonSummarySelect, publicHackathonSelect } from '../utils/queries'; import { parseJsonArray } from '../utils/formatters'; import { AuthRequest } from '../middleware/auth'; +import { getHackathonNews } from '../services/hackathonSyncService'; export async function getUpcomingHackathons(req: Request, res: Response) { try { @@ -50,17 +51,18 @@ export async function getUpcomingHackathons(req: Request, res: Response) { export async function getHackathons(req: Request, res: Response) { try { - const { search, mode, active, upcoming, tag, page, limit } = req.query as unknown as { + const { search, mode, active, upcoming, tag, city, page, limit } = req.query as unknown as { search?: string; mode?: string; active?: string; upcoming?: string; tag?: string; + city?: string; page: number; limit: number; }; - const cacheKey = `hackathons_query:${search || ''}:${mode || ''}:${active || ''}:${upcoming || ''}:${tag || ''}:${page}:${limit}`; + const cacheKey = `hackathons_query:${search || ''}:${mode || ''}:${active || ''}:${upcoming || ''}:${tag || ''}:${city || ''}:${page}:${limit}`; const cached = await cache.get(cacheKey); if (cached) { return res.status(200).json(cached); @@ -68,15 +70,21 @@ export async function getHackathons(req: Request, res: Response) { const skip = (page - 1) * limit; const where: any = {}; - if (active === 'true') where.isActive = true; + // Public listings only show visible events. Admins use /api/admin/hackathons + // when they need to see hidden rows. + if (active !== 'false' && active !== 'all') where.isActive = true; + if (active === 'false') where.isActive = false; if (mode) where.mode = mode; if (tag) where.tags = { contains: tag, mode: 'insensitive' }; + if (city) where.city = { equals: city, mode: 'insensitive' }; if (upcoming === 'true') where.date = { gte: new Date().toISOString().slice(0, 10) }; if (search) { where.OR = [ { title: { contains: search, mode: 'insensitive' } }, { organizer: { contains: search, mode: 'insensitive' } }, { description: { contains: search, mode: 'insensitive' } }, + { city: { contains: search, mode: 'insensitive' } }, + { tags: { contains: search, mode: 'insensitive' } }, ]; } @@ -178,3 +186,45 @@ export async function registerForHackathon(req: AuthRequest, res: Response) { return res.status(500).json({ success: false, data: null, message: 'Failed to register for hackathon.' }); } } + +export async function getHackathonCities(_req: Request, res: Response) { + try { + const cacheKey = 'hackathons_cities'; + const cached = await cache.get(cacheKey); + if (cached) return res.status(200).json(cached); + + const groups = await prisma.hackathon.findMany({ + where: { isActive: true, city: { not: null } }, + select: { city: true }, + distinct: ['city'], + orderBy: { city: 'asc' }, + }); + + const payload = { + success: true, + data: { + cities: groups + .map((group) => group.city) + .filter((city): city is string => Boolean(city && city.trim())), + }, + message: 'Cities retrieved.', + }; + await cache.set(cacheKey, payload, 300); + return res.status(200).json(payload); + } catch { + return res.status(500).json({ success: false, data: null, message: 'Failed to fetch cities.' }); + } +} + +export async function getNews(_req: Request, res: Response) { + try { + const items = await getHackathonNews(); + return res.status(200).json({ + success: true, + data: { items }, + message: 'Hackathon news retrieved.', + }); + } catch { + return res.status(200).json({ success: true, data: { items: [] }, message: 'Hackathon news unavailable.' }); + } +} diff --git a/backend/src/controllers/notificationController.ts b/backend/src/controllers/notificationController.ts new file mode 100644 index 0000000..9cd1646 --- /dev/null +++ b/backend/src/controllers/notificationController.ts @@ -0,0 +1,102 @@ +import { Response } from 'express'; +import { prisma } from '../config/db'; +import { formatNotification } from '../utils/formatters'; +import { AuthRequest } from '../middleware/auth'; + +export async function getNotifications(req: AuthRequest, res: Response) { + try { + const userId = req.user?.id; + if (!userId) { + return res.status(401).json({ success: false, data: null, message: 'Unauthorized' }); + } + + const page = Number((req.query as { page?: number }).page) || 1; + const limit = Number((req.query as { limit?: number }).limit) || 20; + + const [notifications, total, unreadCount] = await Promise.all([ + prisma.notification.findMany({ + where: { userId }, + orderBy: { updatedAt: 'desc' }, + skip: (page - 1) * limit, + take: limit, + }), + prisma.notification.count({ where: { userId } }), + prisma.notification.count({ where: { userId, isRead: false } }), + ]); + + return res.status(200).json({ + success: true, + data: { + notifications: notifications.map(formatNotification), + unreadCount, + pagination: { total, page, limit, pages: Math.ceil(total / limit) }, + }, + message: 'Notifications retrieved.', + }); + } catch { + return res.status(500).json({ success: false, data: null, message: 'Failed to fetch notifications.' }); + } +} + +export async function getUnreadCount(req: AuthRequest, res: Response) { + try { + const userId = req.user?.id; + if (!userId) { + return res.status(401).json({ success: false, data: null, message: 'Unauthorized' }); + } + const unreadCount = await prisma.notification.count({ where: { userId, isRead: false } }); + return res.status(200).json({ success: true, data: { unreadCount }, message: 'Unread count retrieved.' }); + } catch { + return res.status(500).json({ success: false, data: null, message: 'Failed to count notifications.' }); + } +} + +export async function markNotificationRead(req: AuthRequest, res: Response) { + try { + const userId = req.user?.id; + if (!userId) { + return res.status(401).json({ success: false, data: null, message: 'Unauthorized' }); + } + + const notification = await prisma.notification.findFirst({ + where: { id: req.params.id, userId }, + }); + if (!notification) { + return res.status(404).json({ success: false, data: null, message: 'Notification not found.' }); + } + + const updated = notification.isRead + ? notification + : await prisma.notification.update({ where: { id: notification.id }, data: { isRead: true } }); + + return res.status(200).json({ + success: true, + data: formatNotification(updated), + message: 'Notification marked as read.', + }); + } catch { + return res.status(500).json({ success: false, data: null, message: 'Failed to update notification.' }); + } +} + +export async function markAllNotificationsRead(req: AuthRequest, res: Response) { + try { + const userId = req.user?.id; + if (!userId) { + return res.status(401).json({ success: false, data: null, message: 'Unauthorized' }); + } + + const result = await prisma.notification.updateMany({ + where: { userId, isRead: false }, + data: { isRead: true }, + }); + + return res.status(200).json({ + success: true, + data: { updated: result.count, unreadCount: 0 }, + message: 'All notifications marked as read.', + }); + } catch { + return res.status(500).json({ success: false, data: null, message: 'Failed to update notifications.' }); + } +} diff --git a/backend/src/controllers/requestController.ts b/backend/src/controllers/requestController.ts index 1b03c61..ff23e41 100755 --- a/backend/src/controllers/requestController.ts +++ b/backend/src/controllers/requestController.ts @@ -4,6 +4,7 @@ import { cache } from '../config/cache'; import { formatTeamRequest } from '../utils/formatters'; import { requestInclude } from '../utils/queries'; import { AuthRequest } from '../middleware/auth'; +import { notifyJoinRequest, notifyRequestResponse } from '../services/notificationService'; export async function createRequest(req: AuthRequest, res: Response) { try { @@ -60,6 +61,14 @@ export async function createRequest(req: AuthRequest, res: Response) { include: requestInclude, }); + const sender = await prisma.user.findUnique({ where: { id: senderId }, select: { name: true } }); + await notifyJoinRequest({ + leaderId: team.leaderId, + senderName: sender?.name || 'Someone', + teamId, + teamName: team.teamName, + }); + return res.status(201).json({ success: true, data: formatTeamRequest(teamRequest), @@ -170,7 +179,7 @@ export async function respondToRequest(req: AuthRequest, res: Response) { const teamRequest = await prisma.teamRequest.findUnique({ where: { id }, - include: { team: { select: { id: true, members: { select: { userId: true } }, maxSize: true } } }, + include: { team: { select: { id: true, teamName: true, members: { select: { userId: true } }, maxSize: true } } }, }); if (!teamRequest) { return res.status(404).json({ success: false, data: null, message: 'Request not found.' }); @@ -214,6 +223,13 @@ export async function respondToRequest(req: AuthRequest, res: Response) { cache.delPattern(`team_detail:${teamRequest.teamId}`), ]); + await notifyRequestResponse({ + senderId: memberUserId, + teamId: teamRequest.teamId, + teamName: teamRequest.team.teamName, + accepted: action === 'accept', + }); + return res.status(200).json({ success: true, data: formatTeamRequest(updatedRequest), diff --git a/backend/src/controllers/teamController.ts b/backend/src/controllers/teamController.ts index ed9ceeb..7847954 100755 --- a/backend/src/controllers/teamController.ts +++ b/backend/src/controllers/teamController.ts @@ -3,6 +3,8 @@ import { prisma } from '../config/db'; import { cache } from '../config/cache'; import { formatTeamDetail, formatTeamSummary } from '../utils/formatters'; import { teamInclude } from '../utils/queries'; +import { normalizeSkills } from '../utils/skills'; +import { emitToRoom, emitToUser, teamRoom } from '../services/realtime'; import { AuthRequest } from '../middleware/auth'; export async function getTeams(req: Request, res: Response) { @@ -38,6 +40,8 @@ export async function getTeams(req: Request, res: Response) { OR: [ { teamName: { contains: search, mode: 'insensitive' } }, { description: { contains: search, mode: 'insensitive' } }, + { requiredSkills: { contains: search, mode: 'insensitive' } }, + { tags: { contains: search, mode: 'insensitive' } }, ], }, ]; @@ -110,6 +114,10 @@ export async function createTeam(req: AuthRequest, res: Response) { } const { teamName, description, requiredSkills, maxSize, hackathonId } = req.body; + const normalized = normalizeSkills(requiredSkills); + if (normalized.error) { + return res.status(400).json({ success: false, data: null, message: normalized.error }); + } if (hackathonId) { const hackathon = await prisma.hackathon.findUnique({ where: { id: hackathonId }, select: { id: true } }); @@ -123,7 +131,7 @@ export async function createTeam(req: AuthRequest, res: Response) { teamName, description, leaderId, - requiredSkills: JSON.stringify(Array.isArray(requiredSkills) ? requiredSkills : []), + requiredSkills: JSON.stringify(normalized.skills), maxSize: maxSize || 4, hackathonId: hackathonId || null, members: { create: { userId: leaderId } }, @@ -157,10 +165,15 @@ export async function updateTeam(req: AuthRequest, res: Response) { } const { teamName, description, requiredSkills, maxSize, hackathonId, status } = req.body; + const normalized = normalizeSkills(requiredSkills); + if (requiredSkills !== undefined && normalized.error) { + return res.status(400).json({ success: false, data: null, message: normalized.error }); + } + const updateData: any = {}; if (teamName !== undefined) updateData.teamName = teamName; if (description !== undefined) updateData.description = description; - if (requiredSkills !== undefined) updateData.requiredSkills = JSON.stringify(Array.isArray(requiredSkills) ? requiredSkills : []); + if (requiredSkills !== undefined) updateData.requiredSkills = JSON.stringify(normalized.skills); if (hackathonId !== undefined) updateData.hackathonId = hackathonId || null; if (maxSize !== undefined) { if (maxSize < team.members.length) { @@ -183,6 +196,47 @@ export async function updateTeam(req: AuthRequest, res: Response) { } } +export async function leaveTeam(req: AuthRequest, res: Response) { + try { + const userId = req.user?.id; + const { id } = req.params; + if (!userId) { + return res.status(401).json({ success: false, data: null, message: 'Unauthorized' }); + } + + const team = await prisma.team.findUnique({ + where: { id }, + select: { leaderId: true, status: true }, + }); + if (!team) { + return res.status(404).json({ success: false, data: null, message: 'Team not found.' }); + } + if (team.leaderId === userId) { + return res.status(400).json({ + success: false, + data: null, + message: 'Leaders cannot leave their own team. Disband it instead.', + }); + } + + const result = await prisma.teamMember.deleteMany({ where: { teamId: id, userId } }); + if (result.count === 0) { + return res.status(400).json({ success: false, data: null, message: 'You are not a member of this team.' }); + } + + if (team.status === 'full') { + await prisma.team.update({ where: { id }, data: { status: 'open' } }); + } + + await Promise.all([cache.delPattern('teams_query'), cache.delPattern(`team_detail:${id}`)]); + emitToUser(userId, 'chat:removed', { teamId: id, reason: 'You left this team.' }); + + return res.status(200).json({ success: true, data: null, message: 'You left the team.' }); + } catch { + return res.status(500).json({ success: false, data: null, message: 'Failed to leave team.' }); + } +} + export async function deleteTeam(req: AuthRequest, res: Response) { try { const userId = req.user?.id; @@ -198,6 +252,10 @@ export async function deleteTeam(req: AuthRequest, res: Response) { await prisma.team.delete({ where: { id } }); await Promise.all([cache.delPattern('teams_query'), cache.delPattern(`team_detail:${id}`)]); + emitToRoom(teamRoom(id), 'chat:removed', { + teamId: id, + reason: 'This team was disbanded.', + }); return res.status(200).json({ success: true, data: null, message: 'Team disbanded.' }); } catch { diff --git a/backend/src/controllers/userController.ts b/backend/src/controllers/userController.ts index 8d27c46..1d836aa 100755 --- a/backend/src/controllers/userController.ts +++ b/backend/src/controllers/userController.ts @@ -4,20 +4,25 @@ import { cache } from '../config/cache'; import { formatUserDetail, formatUserSummary } from '../utils/formatters'; import { AVATAR_MIME, parseAvatarDataUrl } from '../utils/avatar'; import { userDetailSelect, userSummarySelect } from '../utils/queries'; +import { normalizeSkills } from '../utils/skills'; import { AuthRequest } from '../middleware/auth'; -export async function getUsers(req: Request, res: Response) { +export async function getUsers(req: AuthRequest, res: Response) { try { - const { search, skill, experience, available, page, limit } = req.query as unknown as { + const { search, skill, experience, available, following, page, limit } = req.query as unknown as { search?: string; skill?: string; experience?: string; available?: string; + following?: string; page: number; limit: number; }; - const cacheKey = `users_query:${search || ''}:${skill || ''}:${experience || ''}:${available || ''}:${page}:${limit}`; + // The "following" filter is viewer-specific, so it must not share a cache + // entry with the same query from another account. + const viewerKey = following === 'true' ? req.user?.id || 'anon' : 'all'; + const cacheKey = `users_query:${viewerKey}:${search || ''}:${skill || ''}:${experience || ''}:${available || ''}:${following || ''}:${page}:${limit}`; const cached = await cache.get(cacheKey); if (cached) { return res.status(200).json(cached); @@ -29,6 +34,9 @@ export async function getUsers(req: Request, res: Response) { const where: any = { isBanned: false }; if (available === 'true') where.isAvailable = true; + if (following === 'true' && req.user?.id) { + where.followers = { some: { followerId: req.user.id } }; + } if (experience) where.experience = experience; if (skill) where.skills = { contains: skill, mode: 'insensitive' }; if (search) { @@ -37,6 +45,7 @@ export async function getUsers(req: Request, res: Response) { { college: { contains: search, mode: 'insensitive' } }, { branch: { contains: search, mode: 'insensitive' } }, { bio: { contains: search, mode: 'insensitive' } }, + { skills: { contains: search, mode: 'insensitive' } }, ]; } @@ -72,18 +81,34 @@ export async function getUsers(req: Request, res: Response) { } } -export async function getUserById(req: Request, res: Response) { +export async function getUserById(req: AuthRequest, res: Response) { try { const { id } = req.params; - const user = await prisma.user.findUnique({ where: { id }, select: userDetailSelect }); + const viewerId = req.user?.id; + const user = await prisma.user.findUnique({ + where: { id }, + select: { + ...userDetailSelect, + _count: { select: { followers: true, following: true } }, + }, + }); if (!user) { return res.status(404).json({ success: false, data: null, message: 'User not found.' }); } + let isFollowing = false; + if (viewerId && viewerId !== id) { + const follow = await prisma.follow.findUnique({ + where: { followerId_followingId: { followerId: viewerId, followingId: id } }, + select: { id: true }, + }); + isFollowing = Boolean(follow); + } + return res.status(200).json({ success: true, - data: formatUserDetail(user), + data: formatUserDetail(user, viewerId === id, isFollowing), message: 'User details retrieved.', }); } catch { @@ -121,12 +146,17 @@ export async function updateProfile(req: AuthRequest, res: Response) { const { name, college, branch, bio, avatar, skills, experience, githubUrl, linkedinUrl, portfolioUrl, isAvailable } = req.body; + const normalized = normalizeSkills(skills); + if (skills !== undefined && normalized.error) { + return res.status(400).json({ success: false, data: null, message: normalized.error }); + } + const dataToUpdate: any = {}; if (name !== undefined) dataToUpdate.name = name; if (college !== undefined) dataToUpdate.college = college; if (branch !== undefined) dataToUpdate.branch = branch; if (bio !== undefined) dataToUpdate.bio = bio; - if (skills !== undefined) dataToUpdate.skills = JSON.stringify(Array.isArray(skills) ? skills : []); + if (skills !== undefined) dataToUpdate.skills = JSON.stringify(normalized.skills); if (experience !== undefined) dataToUpdate.experience = experience; if (githubUrl !== undefined) dataToUpdate.githubUrl = githubUrl; if (linkedinUrl !== undefined) dataToUpdate.linkedinUrl = linkedinUrl; @@ -146,7 +176,10 @@ export async function updateProfile(req: AuthRequest, res: Response) { const updatedUser = await prisma.user.update({ where: { id: userId }, data: dataToUpdate, - select: userDetailSelect, + select: { + ...userDetailSelect, + _count: { select: { followers: true, following: true } }, + }, }); await Promise.all([ diff --git a/backend/src/middleware/auth.ts b/backend/src/middleware/auth.ts index ceff1f6..47a2375 100755 --- a/backend/src/middleware/auth.ts +++ b/backend/src/middleware/auth.ts @@ -1,5 +1,6 @@ import { Request, Response, NextFunction } from 'express'; import jwt from 'jsonwebtoken'; +import { prisma } from '../config/db'; export interface AuthUser { id: string; @@ -22,6 +23,14 @@ function getJwtSecret(): string { return secret; } +export function verifyToken(token: string): AuthUser | null { + try { + return jwt.verify(token, getJwtSecret()) as AuthUser; + } catch { + return null; + } +} + export function authenticateToken(req: AuthRequest, res: Response, next: NextFunction) { const authHeader = req.headers['authorization']; const token = authHeader && authHeader.split(' ')[1]; @@ -30,12 +39,39 @@ export function authenticateToken(req: AuthRequest, res: Response, next: NextFun return res.status(401).json({ success: false, data: null, message: 'Access token required.' }); } + const decoded = verifyToken(token); + if (!decoded) { + return res.status(401).json({ success: false, data: null, message: 'Invalid or expired token.' }); + } + + req.user = decoded; + return next(); +} + +/** + * Admin privileges are always reloaded from Postgres. A stale JWT that still + * says "admin" cannot keep access after a demotion, and a forged role claim is + * never trusted. + */ +export async function requireAdmin(req: AuthRequest, res: Response, next: NextFunction) { + if (!req.user) { + return res.status(401).json({ success: false, data: null, message: 'Authentication required.' }); + } + try { - const decoded = jwt.verify(token, getJwtSecret()) as AuthUser; - req.user = decoded; + const dbUser = await prisma.user.findUnique({ + where: { id: req.user.id }, + select: { id: true, email: true, role: true, isBanned: true }, + }); + + if (!dbUser || dbUser.isBanned || dbUser.role !== 'admin') { + return res.status(403).json({ success: false, data: null, message: 'Forbidden. Admin access required.' }); + } + + req.user = { id: dbUser.id, email: dbUser.email, role: dbUser.role }; return next(); } catch { - return res.status(401).json({ success: false, data: null, message: 'Invalid or expired token.' }); + return res.status(500).json({ success: false, data: null, message: 'Could not verify admin access.' }); } } diff --git a/backend/src/routes/adminRoutes.ts b/backend/src/routes/adminRoutes.ts new file mode 100644 index 0000000..24ba21e --- /dev/null +++ b/backend/src/routes/adminRoutes.ts @@ -0,0 +1,47 @@ +import { Router } from 'express'; +import { + listAdminHackathons, + createHackathon, + updateHackathon, + deleteHackathon, + listAdminTeams, + deleteAdminTeam, + listAdminUsers, + deleteAdminUser, + promoteUser, + demoteUser, + listAuditLogs, + syncHackathonsNow, + getAdminSyncStatus, +} from '../controllers/adminController'; +import { authenticateToken, requireAdmin } from '../middleware/auth'; +import { validate } from '../middleware/validate'; +import { + adminHackathonSchema, + adminHackathonUpdateSchema, + idParam, + paginationQuery, +} from '../validation/schemas'; + +const router = Router(); + +router.use(authenticateToken, requireAdmin); + +router.get('/hackathons', validate({ query: paginationQuery }), listAdminHackathons); +router.post('/hackathons', validate({ body: adminHackathonSchema }), createHackathon); +router.post('/hackathons/sync', syncHackathonsNow); +router.get('/hackathons/sync-status', getAdminSyncStatus); +router.put('/hackathons/:id', validate({ params: idParam, body: adminHackathonUpdateSchema }), updateHackathon); +router.delete('/hackathons/:id', validate({ params: idParam }), deleteHackathon); + +router.get('/teams', validate({ query: paginationQuery }), listAdminTeams); +router.delete('/teams/:id', validate({ params: idParam }), deleteAdminTeam); + +router.get('/users', validate({ query: paginationQuery }), listAdminUsers); +router.delete('/users/:id', validate({ params: idParam }), deleteAdminUser); +router.post('/users/:id/promote', validate({ params: idParam }), promoteUser); +router.post('/users/:id/demote', validate({ params: idParam }), demoteUser); + +router.get('/audit', listAuditLogs); + +export default router; diff --git a/backend/src/routes/hackathonRoutes.ts b/backend/src/routes/hackathonRoutes.ts index 82e201a..b6712d2 100755 --- a/backend/src/routes/hackathonRoutes.ts +++ b/backend/src/routes/hackathonRoutes.ts @@ -3,6 +3,8 @@ import { getHackathons, getHackathonById, getUpcomingHackathons, + getHackathonCities, + getNews, registerForHackathon, } from '../controllers/hackathonController'; import { authenticateToken } from '../middleware/auth'; @@ -12,6 +14,8 @@ import { idParam, paginationQuery, publicHackathonQuery } from '../validation/sc const router = Router(); router.get('/upcoming', validate({ query: publicHackathonQuery }), getUpcomingHackathons); +router.get('/cities', getHackathonCities); +router.get('/news', getNews); router.get('/', authenticateToken, validate({ query: paginationQuery }), getHackathons); router.get('/:id', authenticateToken, validate({ params: idParam }), getHackathonById); router.post('/:id/register', authenticateToken, validate({ params: idParam }), registerForHackathon); diff --git a/backend/src/routes/notificationRoutes.ts b/backend/src/routes/notificationRoutes.ts new file mode 100644 index 0000000..4f2828a --- /dev/null +++ b/backend/src/routes/notificationRoutes.ts @@ -0,0 +1,21 @@ +import { Router } from 'express'; +import { + getNotifications, + getUnreadCount, + markNotificationRead, + markAllNotificationsRead, +} from '../controllers/notificationController'; +import { authenticateToken } from '../middleware/auth'; +import { validate } from '../middleware/validate'; +import { idParam, notificationListQuery } from '../validation/schemas'; + +const router = Router(); + +router.use(authenticateToken); + +router.get('/', validate({ query: notificationListQuery }), getNotifications); +router.get('/unread-count', getUnreadCount); +router.put('/read-all', markAllNotificationsRead); +router.put('/:id/read', validate({ params: idParam }), markNotificationRead); + +export default router; diff --git a/backend/src/routes/teamRoutes.ts b/backend/src/routes/teamRoutes.ts index 777d84d..d441973 100755 --- a/backend/src/routes/teamRoutes.ts +++ b/backend/src/routes/teamRoutes.ts @@ -1,16 +1,19 @@ import { Router } from 'express'; -import { getTeams, getTeamById, createTeam, updateTeam, deleteTeam } from '../controllers/teamController'; +import { getTeams, getTeamById, createTeam, updateTeam, deleteTeam, leaveTeam } from '../controllers/teamController'; +import { getMessages } from '../controllers/chatController'; import { authenticateToken } from '../middleware/auth'; import { writeRateLimiter } from '../middleware/rateLimiter'; import { validate } from '../middleware/validate'; -import { createTeamSchema, idParam, paginationQuery, updateTeamSchema } from '../validation/schemas'; +import { chatHistoryQuery, createTeamSchema, idParam, paginationQuery, updateTeamSchema } from '../validation/schemas'; const router = Router(); router.get('/', authenticateToken, validate({ query: paginationQuery }), getTeams); router.post('/', authenticateToken, writeRateLimiter, validate({ body: createTeamSchema }), createTeam); +router.get('/:id/messages', authenticateToken, validate({ params: idParam, query: chatHistoryQuery }), getMessages); router.get('/:id', authenticateToken, validate({ params: idParam }), getTeamById); router.put('/:id', authenticateToken, validate({ params: idParam, body: updateTeamSchema }), updateTeam); +router.delete('/:id/leave', authenticateToken, writeRateLimiter, validate({ params: idParam }), leaveTeam); router.delete('/:id', authenticateToken, validate({ params: idParam }), deleteTeam); export default router; diff --git a/backend/src/routes/userRoutes.ts b/backend/src/routes/userRoutes.ts index 58f6a7b..041f833 100755 --- a/backend/src/routes/userRoutes.ts +++ b/backend/src/routes/userRoutes.ts @@ -1,13 +1,19 @@ import { Router } from 'express'; import { getUsers, getUserById, getAvatar, updateProfile } from '../controllers/userController'; +import { followUser, unfollowUser, getFollowers, getFollowing } from '../controllers/followController'; import { authenticateToken } from '../middleware/auth'; +import { writeRateLimiter } from '../middleware/rateLimiter'; import { validate } from '../middleware/validate'; -import { idParam, paginationQuery, updateProfileSchema } from '../validation/schemas'; +import { followListQuery, idParam, paginationQuery, updateProfileSchema } from '../validation/schemas'; const router = Router(); router.get('/', authenticateToken, validate({ query: paginationQuery }), getUsers); router.put('/profile', authenticateToken, validate({ body: updateProfileSchema }), updateProfile); +router.post('/:id/follow', authenticateToken, writeRateLimiter, validate({ params: idParam }), followUser); +router.delete('/:id/follow', authenticateToken, writeRateLimiter, validate({ params: idParam }), unfollowUser); +router.get('/:id/followers', authenticateToken, validate({ params: idParam, query: followListQuery }), getFollowers); +router.get('/:id/following', authenticateToken, validate({ params: idParam, query: followListQuery }), getFollowing); router.get('/:id/avatar', authenticateToken, validate({ params: idParam }), getAvatar); router.get('/:id', authenticateToken, validate({ params: idParam }), getUserById); diff --git a/backend/src/scripts/make-admin.ts b/backend/src/scripts/make-admin.ts new file mode 100644 index 0000000..28b6e7a --- /dev/null +++ b/backend/src/scripts/make-admin.ts @@ -0,0 +1,31 @@ +import 'dotenv/config'; +import { prisma } from '../config/db'; + +async function main() { + const email = process.argv[2]?.trim().toLowerCase(); + if (!email) { + throw new Error('Usage: npm run make-admin -- '); + } + + const user = await prisma.user.findUnique({ where: { email }, select: { id: true, email: true, role: true } }); + if (!user) { + throw new Error(`No user exists with the email ${email}.`); + } + + if (user.role === 'admin') { + console.log(`${user.email} is already an admin.`); + return; + } + + await prisma.user.update({ where: { id: user.id }, data: { role: 'admin' } }); + console.log(`${user.email} is now an admin.`); +} + +main() + .catch((error) => { + console.error(error instanceof Error ? error.message : error); + process.exitCode = 1; + }) + .finally(async () => { + await prisma.$disconnect(); + }); diff --git a/backend/src/seed.ts b/backend/src/seed.ts index 7f65fd0..ed46be2 100755 --- a/backend/src/seed.ts +++ b/backend/src/seed.ts @@ -17,6 +17,7 @@ const USER_IDS = { theo: '11111111-1111-4111-8111-111111111120', mina: '11111111-1111-4111-8111-111111111121', ravi: '11111111-1111-4111-8111-111111111122', + admin: '11111111-1111-4111-8111-111111111123', }; const HACKATHON_IDS = { @@ -64,6 +65,38 @@ const REQUEST_IDS = { theoCare: '88888888-8888-4888-8888-888888888892', }; +const FOLLOW_IDS = { + aishaPriya: '44444444-4444-4444-8444-444444444441', + marcusPriya: '44444444-4444-4444-8444-444444444442', + yukiSofia: '44444444-4444-4444-8444-444444444443', + raviTheo: '44444444-4444-4444-8444-444444444444', + amaraAisha: '44444444-4444-4444-8444-444444444445', + minaPriya: '44444444-4444-4444-8444-444444444446', + danielAisha: '44444444-4444-4444-8444-444444444447', +}; + +const MESSAGE_IDS = { + neural1: '55555555-5555-4555-8555-555555555551', + neural2: '55555555-5555-4555-8555-555555555552', + neural3: '55555555-5555-4555-8555-555555555553', + neural4: '55555555-5555-4555-8555-555555555554', + care1: '55555555-5555-4555-8555-555555555555', + care2: '55555555-5555-4555-8555-555555555556', + care3: '55555555-5555-4555-8555-555555555557', + green1: '55555555-5555-4555-8555-555555555558', + green2: '55555555-5555-4555-8555-555555555559', + green3: '55555555-5555-4555-8555-555555555560', +}; + +const NOTIFICATION_IDS = { + yukiRequest: '66666666-6666-4666-8666-666666666661', + aishaCareRequest: '66666666-6666-4666-8666-666666666662', + priyaFollow: '66666666-6666-4666-8666-666666666663', + chatNeural: '66666666-6666-4666-8666-666666666664', + raviFollow: '66666666-6666-4666-8666-666666666665', + chatGreen: '66666666-6666-4666-8666-666666666666', +}; + async function seedUsers(passwordHash: string) { const users = [ { @@ -103,7 +136,7 @@ async function seedUsers(passwordHash: string) { college: 'Tecnológico de Monterrey', branch: 'Software Engineering', bio: 'Mobile developer shipping Flutter apps for climate and civic tech.', - skills: ['Flutter', 'React Native', 'JavaScript', 'UI/UX Design'], + skills: ['Flutter', 'React Native', 'JavaScript', 'UI Design'], experience: 'advanced', }, { @@ -123,7 +156,7 @@ async function seedUsers(passwordHash: string) { college: 'University of Tokyo', branch: 'Information Science', bio: 'Product designer learning to code. I care about accessible interfaces and clear copy.', - skills: ['UI/UX Design', 'HTML/CSS', 'JavaScript', 'Graphic Design'], + skills: ['UI Design', 'HTML CSS', 'JavaScript', 'Graphic Design', 'Figma'], experience: 'beginner', }, { @@ -143,7 +176,7 @@ async function seedUsers(passwordHash: string) { college: 'Georgia Institute of Technology', branch: 'Computer Engineering', bio: 'Platform engineer who enjoys distributed systems and developer tooling.', - skills: ['Java', 'Node.js', 'Redis', 'Cloud (AWS/GCP/Azure)', 'DevOps'], + skills: ['Java', 'Node.js', 'Redis', 'AWS', 'DevOps'], experience: 'intermediate', }, { @@ -153,7 +186,7 @@ async function seedUsers(passwordHash: string) { college: 'University of Toronto', branch: 'Human-Computer Interaction', bio: 'I turn complex public services into clear, accessible experiences. Interested in civic tech and community data.', - skills: ['UI/UX Design', 'React', 'Accessibility', 'Data Analysis'], + skills: ['UI Design', 'React', 'Accessibility', 'Data Analysis'], experience: 'intermediate', }, { @@ -173,7 +206,7 @@ async function seedUsers(passwordHash: string) { college: 'University of British Columbia', branch: 'Computer Science', bio: 'Frontend engineer building thoughtful tools for makers and educators.', - skills: ['TypeScript', 'React', 'HTML/CSS', 'UI/UX Design'], + skills: ['TypeScript', 'React', 'HTML CSS', 'UI Design'], experience: 'intermediate', }, { @@ -183,9 +216,20 @@ async function seedUsers(passwordHash: string) { college: 'National University of Singapore', branch: 'Information Systems', bio: 'I work on streaming data, developer tooling, and small practical prototypes.', - skills: ['Go', 'Python', 'Cloud (AWS/GCP/Azure)', 'Data Analysis'], + skills: ['Go', 'Python', 'AWS', 'Data Analysis'], experience: 'advanced', }, + { + id: USER_IDS.admin, + name: 'HackMatch Admin', + email: 'admin@hackmatch.dev', + college: 'HackMatch', + branch: 'Operations', + bio: 'Demo administrator for local moderation, imports, and audit workflows.', + skills: ['Community', 'Operations', 'Data Analysis'], + experience: 'advanced', + role: 'admin', + }, ]; for (const user of users) { @@ -202,12 +246,13 @@ async function seedUsers(passwordHash: string) { hasAvatar: false, isAvailable: true, isBanned: false, - role: 'user', + role: (user as { role?: string }).role || 'user', }; await prisma.user.upsert({ where: { id: user.id }, - update: data, + // Never overwrite a profile, avatar, or role that changed after seeding. + update: {}, create: { id: user.id, ...data, @@ -291,7 +336,7 @@ async function seedHackathons() { prizePool: '$10,000', minTeamSize: 1, maxTeamSize: 3, - tags: ['Education', 'Web', 'Mobile', 'UI/UX Design'], + tags: ['Education', 'Web', 'Mobile', 'UI Design'], rules: 'Projects must solve a problem faced by students on campus.', }, { @@ -351,7 +396,7 @@ async function seedHackathons() { prizePool: '$12,000', minTeamSize: 2, maxTeamSize: 4, - tags: ['Accessibility', 'UI/UX Design', 'Education', 'Web'], + tags: ['Accessibility', 'UI Design', 'Education', 'Web'], rules: 'Include a keyboard walkthrough and explain your accessibility choices.', }, { @@ -396,16 +441,23 @@ async function seedHackathons() { prizePool: '$16,000', minTeamSize: 2, maxTeamSize: 4, - tags: ['Education', 'Web', 'React', 'UI/UX Design'], + tags: ['Education', 'Web', 'React', 'UI Design'], rules: 'Teams must show a working prototype and describe how it helps learners.', }, ]; for (const hackathon of hackathons) { - const data = { ...hackathon, tags: JSON.stringify(hackathon.tags) }; + const raw = hackathon as typeof hackathon & { city?: string; endDate?: string }; + const data = { + ...hackathon, + city: raw.city || (hackathon.mode === 'online' ? 'Online' : hackathon.location), + endDate: raw.endDate || hackathon.date, + tags: JSON.stringify(hackathon.tags), + }; await prisma.hackathon.upsert({ where: { id: hackathon.id }, - update: data, + // Admin edits and imports always win over the seed snapshot. + update: {}, create: data, }); } @@ -462,7 +514,7 @@ async function seedTeams() { teamName: 'CampusCart', description: 'A shared marketplace for students to buy, sell, and donate dorm supplies.', leaderId: USER_IDS.yuki, - requiredSkills: ['React', 'UI/UX Design', 'Node.js'], + requiredSkills: ['React', 'UI Design', 'Node.js'], maxSize: 3, hackathonId: HACKATHON_IDS.campus, status: 'open', @@ -495,7 +547,7 @@ async function seedTeams() { teamName: 'Pathfinders', description: 'An open map of step-free routes and community spaces, built with public geospatial data.', leaderId: USER_IDS.theo, - requiredSkills: ['React', 'UI/UX Design', 'Maps'], + requiredSkills: ['React', 'UI Design', 'Maps'], maxSize: 4, hackathonId: HACKATHON_IDS.atlas, status: 'open', @@ -506,7 +558,7 @@ async function seedTeams() { teamName: 'Clear Patterns', description: 'A simple, keyboard-first appointment experience for people navigating public services.', leaderId: USER_IDS.mina, - requiredSkills: ['Accessibility', 'Node.js', 'UI/UX Design'], + requiredSkills: ['Accessibility', 'Node.js', 'UI Design'], maxSize: 4, hackathonId: HACKATHON_IDS.design, status: 'open', @@ -517,7 +569,7 @@ async function seedTeams() { teamName: 'Good First Build', description: 'Contributor-friendly tooling that helps maintainers turn rough ideas into actionable issues.', leaderId: USER_IDS.aisha, - requiredSkills: ['TypeScript', 'DevOps', 'UI/UX Design'], + requiredSkills: ['TypeScript', 'DevOps', 'UI Design'], maxSize: 5, hackathonId: HACKATHON_IDS.open, status: 'open', @@ -539,7 +591,7 @@ async function seedTeams() { teamName: 'Workshop Commons', description: 'A welcoming place for makers to share short tutorials and organize collaborative learning sessions.', leaderId: USER_IDS.sofia, - requiredSkills: ['React', 'Node.js', 'UI/UX Design'], + requiredSkills: ['React', 'Node.js', 'UI Design'], maxSize: 4, hackathonId: HACKATHON_IDS.maker, status: 'open', @@ -552,7 +604,8 @@ async function seedTeams() { const data = { ...teamData, requiredSkills: JSON.stringify(team.requiredSkills), tags: '[]' }; await prisma.team.upsert({ where: { id: team.id }, - update: data, + // Keep changes made by leaders after the initial seed. + update: {}, create: data, }); @@ -683,7 +736,7 @@ async function seedRequests() { for (const request of requests) { await prisma.teamRequest.upsert({ where: { id: request.id }, - update: { status: 'pending' }, + update: {}, create: { ...request, type: 'join_request', @@ -693,6 +746,74 @@ async function seedRequests() { } } +async function seedFollows() { + const follows = [ + { id: FOLLOW_IDS.aishaPriya, followerId: USER_IDS.aisha, followingId: USER_IDS.priya }, + { id: FOLLOW_IDS.marcusPriya, followerId: USER_IDS.marcus, followingId: USER_IDS.priya }, + { id: FOLLOW_IDS.yukiSofia, followerId: USER_IDS.yuki, followingId: USER_IDS.sofia }, + { id: FOLLOW_IDS.raviTheo, followerId: USER_IDS.ravi, followingId: USER_IDS.theo }, + { id: FOLLOW_IDS.amaraAisha, followerId: USER_IDS.amara, followingId: USER_IDS.aisha }, + { id: FOLLOW_IDS.minaPriya, followerId: USER_IDS.mina, followingId: USER_IDS.priya }, + { id: FOLLOW_IDS.danielAisha, followerId: USER_IDS.daniel, followingId: USER_IDS.aisha }, + ]; + + for (const follow of follows) { + await prisma.follow.upsert({ + where: { followerId_followingId: { followerId: follow.followerId, followingId: follow.followingId } }, + update: {}, + create: follow, + }); + } +} + +async function seedMessages() { + const now = Date.now(); + const minutesAgo = (minutes: number) => new Date(now - minutes * 60 * 1000); + + const messages = [ + { id: MESSAGE_IDS.neural1, teamId: TEAM_IDS.neural, senderId: USER_IDS.priya, content: 'I set up the repo and the shared editor shell. The socket connection is next.', createdAt: minutesAgo(95) }, + { id: MESSAGE_IDS.neural2, teamId: TEAM_IDS.neural, senderId: USER_IDS.marcus, content: 'The model endpoint is ready. I will add a small latency test after lunch.', createdAt: minutesAgo(80) }, + { id: MESSAGE_IDS.neural3, teamId: TEAM_IDS.neural, senderId: USER_IDS.daniel, content: 'I can wire the Postgres session store tonight. Do we need a migration?', createdAt: minutesAgo(64) }, + { id: MESSAGE_IDS.neural4, teamId: TEAM_IDS.neural, senderId: USER_IDS.priya, content: 'Yes, please keep it additive. Let us review before we deploy anything.', createdAt: minutesAgo(52) }, + { id: MESSAGE_IDS.care1, teamId: TEAM_IDS.carebridge, senderId: USER_IDS.marcus, content: 'The triage flow works with the synthetic dataset. I am cleaning up the prompts now.', createdAt: minutesAgo(120) }, + { id: MESSAGE_IDS.care2, teamId: TEAM_IDS.carebridge, senderId: USER_IDS.priya, content: 'I added the request status screen so the demo has a clear end-to-end story.', createdAt: minutesAgo(105) }, + { id: MESSAGE_IDS.care3, teamId: TEAM_IDS.carebridge, senderId: USER_IDS.marcus, content: 'Great. Let us keep the interface calm and accessible for the judging round.', createdAt: minutesAgo(90) }, + { id: MESSAGE_IDS.green1, teamId: TEAM_IDS.greenloop, senderId: USER_IDS.sofia, content: 'The recycling tracker is on my phone. I will share a short screen recording.', createdAt: minutesAgo(150) }, + { id: MESSAGE_IDS.green2, teamId: TEAM_IDS.greenloop, senderId: USER_IDS.yuki, content: 'The empty state needs one line of encouragement. I will polish that next.', createdAt: minutesAgo(135) }, + { id: MESSAGE_IDS.green3, teamId: TEAM_IDS.greenloop, senderId: USER_IDS.sofia, content: 'Perfect. Also test the layout at 360px before we call it done.', createdAt: minutesAgo(121) }, + ]; + + for (const message of messages) { + await prisma.message.upsert({ + where: { id: message.id }, + update: {}, + create: message, + }); + } +} + +async function seedNotifications() { + const now = Date.now(); + const minutesAgo = (minutes: number) => new Date(now - minutes * 60 * 1000); + + const notifications = [ + { id: NOTIFICATION_IDS.yukiRequest, userId: USER_IDS.priya, type: 'join_request', text: 'Yuki Tanaka asked to join Neural Sync.', link: `/teams/${TEAM_IDS.neural}`, createdAt: minutesAgo(75) }, + { id: NOTIFICATION_IDS.aishaCareRequest, userId: USER_IDS.marcus, type: 'join_request', text: 'Aisha Rahman asked to join CareBridge AI.', link: `/teams/${TEAM_IDS.carebridge}`, createdAt: minutesAgo(90) }, + { id: NOTIFICATION_IDS.priyaFollow, userId: USER_IDS.priya, type: 'follow', text: 'Aisha Rahman started following you.', link: `/profile/${USER_IDS.aisha}`, createdAt: minutesAgo(40) }, + { id: NOTIFICATION_IDS.chatNeural, userId: USER_IDS.daniel, type: 'team_chat', groupKey: `team_chat:${TEAM_IDS.neural}`, count: 3, text: '3 new messages in Neural Sync', link: `/teams/${TEAM_IDS.neural}?tab=chat`, createdAt: minutesAgo(64) }, + { id: NOTIFICATION_IDS.raviFollow, userId: USER_IDS.theo, type: 'follow', text: 'Ravi Shah started following you.', link: `/profile/${USER_IDS.ravi}`, createdAt: minutesAgo(30) }, + { id: NOTIFICATION_IDS.chatGreen, userId: USER_IDS.yuki, type: 'team_chat', groupKey: `team_chat:${TEAM_IDS.greenloop}`, count: 2, text: '2 new messages in GreenLoop', link: `/teams/${TEAM_IDS.greenloop}?tab=chat`, createdAt: minutesAgo(121) }, + ]; + + for (const notification of notifications) { + await prisma.notification.upsert({ + where: { id: notification.id }, + update: {}, + create: notification, + }); + } +} + export async function seedDatabase() { const passwordHash = await bcrypt.hash(DEMO_PASSWORD, 10); @@ -701,6 +822,9 @@ export async function seedDatabase() { await seedTeams(); await seedRegistrations(); await seedRequests(); + await seedFollows(); + await seedMessages(); + await seedNotifications(); console.log('Seed data ensured (idempotent).'); } diff --git a/backend/src/server.ts b/backend/src/server.ts index 949ebea..d560628 100755 --- a/backend/src/server.ts +++ b/backend/src/server.ts @@ -1,7 +1,11 @@ import 'dotenv/config'; +import { createServer } from 'http'; +import cron from 'node-cron'; import { createApp } from './app'; import { connectDB } from './config/db'; import { seedDatabase } from './seed'; +import { initSocket } from './socket'; +import { maybeSyncOnStartup, syncHackathons } from './services/hackathonSyncService'; const PORT = process.env.PORT || 5000; @@ -15,16 +19,38 @@ async function start() { assertProductionSecrets(); const app = createApp(); + const server = createServer(app); + initSocket(server); - app.listen(PORT, async () => { + await connectDB(); + + if (process.env.AUTO_SEED === 'true') { + await seedDatabase(); + } + + server.listen(PORT, async () => { console.log(`HackMatch API listening on port ${PORT}`); - await connectDB(); + if (process.env.NODE_ENV === 'test') { + return; + } - if (process.env.AUTO_SEED === 'true') { - await seedDatabase(); + try { + await maybeSyncOnStartup(); + } catch (error) { + console.error('Startup hackathon sync failed:', error); } }); + + if (process.env.NODE_ENV !== 'test') { + cron.schedule('0 */6 * * *', async () => { + try { + await syncHackathons(); + } catch (error) { + console.error('Scheduled hackathon sync failed:', error); + } + }); + } } start().catch((error) => { diff --git a/backend/src/services/chatService.ts b/backend/src/services/chatService.ts new file mode 100644 index 0000000..1fb398a --- /dev/null +++ b/backend/src/services/chatService.ts @@ -0,0 +1,119 @@ +import { prisma } from '../config/db'; +import { formatChatMessage } from '../utils/formatters'; +import { chatMessageInclude, userSummarySelect } from '../utils/queries'; +import { isUserViewingChat } from './realtime'; +import { notifyTeamChat } from './notificationService'; + +export const MAX_MESSAGE_LENGTH = 1000; +export const RATE_LIMIT_WINDOW_MS = 5000; +export const RATE_LIMIT_MAX = 5; + +export type ChatErrorCode = 'team_not_found' | 'not_member' | 'empty' | 'too_long' | 'rate_limit'; + +export type ChatResult = + | { ok: true; message: ReturnType } + | { ok: false; code: ChatErrorCode; error: string }; + +const messageBuckets = new Map(); + +export function resetChatRateLimits(): void { + messageBuckets.clear(); +} + +export async function getTeamForMember(userId: string, teamId: string) { + const team = await prisma.team.findUnique({ + where: { id: teamId }, + select: { + id: true, + teamName: true, + leaderId: true, + members: { select: { userId: true } }, + }, + }); + if (!team) return { team: null, isMember: false }; + const isMember = team.leaderId === userId || team.members.some((member) => member.userId === userId); + return { team, isMember }; +} + +export async function sendChatMessage(userId: string, teamId: string, rawContent: unknown): Promise { + const content = typeof rawContent === 'string' ? rawContent.trim() : ''; + if (!content) { + return { ok: false, code: 'empty', error: 'Message cannot be empty.' }; + } + if (content.length > MAX_MESSAGE_LENGTH) { + return { ok: false, code: 'too_long', error: `Messages can be up to ${MAX_MESSAGE_LENGTH} characters.` }; + } + + const { team, isMember } = await getTeamForMember(userId, teamId); + if (!team) { + return { ok: false, code: 'team_not_found', error: 'Team not found.' }; + } + if (!isMember) { + return { ok: false, code: 'not_member', error: 'Only team members can chat here.' }; + } + + const now = Date.now(); + const recent = (messageBuckets.get(userId) || []).filter((timestamp) => now - timestamp < RATE_LIMIT_WINDOW_MS); + if (recent.length >= RATE_LIMIT_MAX) { + messageBuckets.set(userId, recent); + return { ok: false, code: 'rate_limit', error: 'You are sending messages too quickly. Wait a moment.' }; + } + recent.push(now); + messageBuckets.set(userId, recent); + + const message = await prisma.message.create({ + data: { teamId, senderId: userId, content, type: 'text' }, + include: chatMessageInclude, + }); + + const recipientIds = [team.leaderId, ...team.members.map((member) => member.userId)] + .filter((id) => id !== userId) + .filter((id) => !isUserViewingChat(id, teamId)); + + await notifyTeamChat({ teamId, teamName: team.teamName, recipientIds }); + + return { ok: true, message: formatChatMessage(message) }; +} + +export async function getChatHistory(userId: string, teamId: string, before?: string, limit = 50) { + const { team, isMember } = await getTeamForMember(userId, teamId); + if (!team) return { error: 'team_not_found' as const }; + if (!isMember) return { error: 'not_member' as const }; + + let beforeDate: Date | undefined; + if (before) { + const cursor = await prisma.message.findFirst({ + where: { id: before, teamId }, + select: { createdAt: true }, + }); + if (cursor) beforeDate = cursor.createdAt; + } + + const messages = await prisma.message.findMany({ + where: { + teamId, + ...(beforeDate ? { createdAt: { lt: beforeDate } } : {}), + }, + orderBy: [{ createdAt: 'desc' }, { id: 'desc' }], + take: limit, + include: chatMessageInclude, + }); + + return { + messages: messages.reverse().map(formatChatMessage), + hasMore: messages.length === limit, + }; +} + +export async function listTeamMemberIds(teamId: string): Promise { + const team = await prisma.team.findUnique({ + where: { id: teamId }, + select: { leaderId: true, members: { select: { userId: true } } }, + }); + if (!team) return []; + return [...new Set([team.leaderId, ...team.members.map((member) => member.userId)])]; +} + +export async function getChatSender(userId: string) { + return prisma.user.findUnique({ where: { id: userId }, select: userSummarySelect }); +} diff --git a/backend/src/services/hackathonSyncService.ts b/backend/src/services/hackathonSyncService.ts new file mode 100644 index 0000000..792d84e --- /dev/null +++ b/backend/src/services/hackathonSyncService.ts @@ -0,0 +1,283 @@ +import { prisma } from '../config/db'; +import { cache } from '../config/cache'; + +export const SYNC_STATE_ID = 'hackathons'; +export const SYNC_INTERVAL_MS = 6 * 60 * 60 * 1000; +const FETCH_TIMEOUT_MS = 15000; +const MAX_EXTERNAL_EVENTS = 100; + +const HACK_CLUB_URL = 'https://hackathons.hackclub.com/api/events/upcoming'; +const DEV_TO_NEWS_URL = 'https://dev.to/api/articles?tag=hackathon&per_page=8&top=30'; +const NEWS_CACHE_KEY = 'hackathon_news'; + +export type FetchLike = ( + input: string, + init?: { signal?: AbortSignal; headers?: Record } +) => Promise<{ ok: boolean; status: number; json: () => Promise }>; + +export interface NormalizedExternalHackathon { + source: string; + externalId: string; + title: string; + organizer: string; + description: string; + date: string; + endDate: string; + registrationDeadline: string; + location: string; + city: string; + mode: 'online' | 'offline' | 'hybrid'; + prizePool: string; + tags: string[]; + websiteUrl: string; + sourceUrl: string; +} + +function dateOnly(value: unknown): string { + if (typeof value !== 'string') return ''; + const parsed = new Date(value); + if (Number.isNaN(parsed.getTime())) return ''; + return parsed.toISOString().slice(0, 10); +} + +function clean(value: unknown, maxLength: number): string { + if (typeof value !== 'string') return ''; + return value.trim().replace(/\s+/g, ' ').slice(0, maxLength); +} + +export function normalizeHackClubEvent(event: unknown): NormalizedExternalHackathon | null { + if (!event || typeof event !== 'object') return null; + const raw = event as Record; + const externalId = clean(raw.id, 120); + const title = clean(raw.name, 140); + const date = dateOnly(raw.start); + if (!externalId || !title || !date) return null; + + const city = clean(raw.city, 80); + const state = clean(raw.state, 80); + const country = clean(raw.country, 80); + const isVirtual = raw.virtual === true; + const isHybrid = raw.hybrid === true; + const mode: NormalizedExternalHackathon['mode'] = isVirtual ? 'online' : isHybrid ? 'hybrid' : 'offline'; + const place = [...new Set([city, state, country].filter(Boolean))].join(', '); + const location = isVirtual ? 'Online' : place || 'In person'; + const websiteUrl = typeof raw.website === 'string' && /^https?:\/\//i.test(raw.website) ? raw.website : ''; + + return { + source: 'hackclub', + externalId, + title, + organizer: 'Hack Club', + description: `${title} is an upcoming hackathon listed by Hack Club. Check the official site for schedule, eligibility, and prizes.`, + date, + endDate: dateOnly(raw.end), + registrationDeadline: date, + location, + city: isVirtual ? 'Online' : city || 'In person', + mode, + prizePool: 'See official site', + tags: [...new Set(['Hackathon', isVirtual ? 'Online' : 'In person', ...(city ? [city] : [])])], + websiteUrl, + sourceUrl: 'https://hackathons.hackclub.com/', + }; +} + +export async function fetchHackClubEvents(fetchImpl: FetchLike = fetch): Promise { + const response = await fetchImpl(HACK_CLUB_URL, { + signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), + headers: { Accept: 'application/json' }, + }); + if (!response.ok) { + throw new Error(`Hack Club source returned HTTP ${response.status}.`); + } + const payload = await response.json(); + if (!Array.isArray(payload)) throw new Error('Hack Club source returned an unexpected response.'); + return payload + .map(normalizeHackClubEvent) + .filter((item): item is NormalizedExternalHackathon => Boolean(item)) + .slice(0, MAX_EXTERNAL_EVENTS); +} + +export interface SyncSummary { + created: number; + updated: number; + skipped: number; + errors: string[]; + lastSyncAt: string | null; + durationMs: number; +} + +export async function storeExternalHackathons(items: NormalizedExternalHackathon[]) { + let created = 0; + let updated = 0; + let skipped = 0; + const now = new Date(); + + for (const item of items) { + try { + const existing = await prisma.hackathon.findUnique({ + where: { source_externalId: { source: item.source, externalId: item.externalId } }, + select: { id: true, isEditedByAdmin: true }, + }); + + if (existing?.isEditedByAdmin) { + skipped += 1; + continue; + } + + const data = { + title: item.title, + organizer: item.organizer, + description: item.description, + date: item.date, + endDate: item.endDate || null, + registrationDeadline: item.registrationDeadline, + location: item.location, + city: item.city, + mode: item.mode, + prizePool: item.prizePool, + minTeamSize: 1, + maxTeamSize: 4, + tags: JSON.stringify(item.tags), + websiteUrl: item.websiteUrl || null, + registrationLink: item.websiteUrl || null, + source: item.source, + sourceUrl: item.sourceUrl, + externalId: item.externalId, + isExternal: true, + isActive: true, + updatedAt: now, + }; + + if (existing) { + await prisma.hackathon.update({ where: { id: existing.id }, data }); + updated += 1; + } else { + await prisma.hackathon.create({ data }); + created += 1; + } + } catch (error) { + skipped += 1; + if (process.env.NODE_ENV !== 'test') { + console.error('Skipped an imported hackathon:', error instanceof Error ? error.message : error); + } + } + } + + return { created, updated, skipped }; +} + +export async function syncHackathons(options: { fetchImpl?: FetchLike } = {}): Promise { + const started = Date.now(); + const errors: string[] = []; + let created = 0; + let updated = 0; + let skipped = 0; + + try { + const events = await fetchHackClubEvents(options.fetchImpl); + const result = await storeExternalHackathons(events); + created = result.created; + updated = result.updated; + skipped = result.skipped; + } catch (error) { + errors.push(`Hack Club: ${error instanceof Error ? error.message : 'source unavailable'}`); + } + + const finished = new Date(); + const durationMs = Date.now() - started; + const state = await prisma.syncState.upsert({ + where: { id: SYNC_STATE_ID }, + create: { + id: SYNC_STATE_ID, + lastSyncAt: finished, + lastError: errors.length ? errors.join('; ').slice(0, 500) : null, + lastDurationMs: durationMs, + }, + update: { + lastSyncAt: finished, + lastError: errors.length ? errors.join('; ').slice(0, 500) : null, + lastDurationMs: durationMs, + }, + }); + + await cache.delPattern('hackathons_query'); + await cache.delPattern('hackathons_upcoming'); + + return { + created, + updated, + skipped, + errors, + lastSyncAt: state.lastSyncAt?.toISOString() ?? null, + durationMs, + }; +} + +export async function getSyncStatus() { + const state = await prisma.syncState.findUnique({ where: { id: SYNC_STATE_ID } }); + return { + lastSyncAt: state?.lastSyncAt?.toISOString() ?? null, + lastError: state?.lastError ?? '', + lastDurationMs: state?.lastDurationMs ?? null, + }; +} + +export async function maybeSyncOnStartup(): Promise { + const state = await prisma.syncState.findUnique({ where: { id: SYNC_STATE_ID } }); + const lastSync = state?.lastSyncAt?.getTime() ?? 0; + if (Date.now() - lastSync < SYNC_INTERVAL_MS) return null; + return syncHackathons(); +} + +export interface NewsItem { + title: string; + url: string; + publishedAt: string; + source: string; +} + +export async function getHackathonNews(options: { fetchImpl?: FetchLike; force?: boolean } = {}): Promise { + if (!options.force) { + const cached = await cache.get(NEWS_CACHE_KEY); + if (cached) return cached; + } + + try { + const fetchImpl: FetchLike = options.fetchImpl || fetch; + const response = await fetchImpl(DEV_TO_NEWS_URL, { + signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), + headers: { Accept: 'application/json' }, + }); + + if (!response.ok) throw new Error(`News source returned HTTP ${response.status}.`); + const payload = await response.json(); + if (!Array.isArray(payload)) throw new Error('News source returned an unexpected response.'); + + const items: NewsItem[] = payload + .map((article) => { + if (!article || typeof article !== 'object') return null; + const raw = article as Record; + const title = clean(raw.title, 160); + const url = typeof raw.url === 'string' && /^https?:\/\//i.test(raw.url) ? raw.url : ''; + if (!title || !url) return null; + return { + title, + url, + publishedAt: typeof raw.published_timestamp === 'string' ? raw.published_timestamp : '', + source: 'DEV Community', + }; + }) + .filter((item): item is NewsItem => Boolean(item)) + .slice(0, 8); + + await cache.set(NEWS_CACHE_KEY, items, 15 * 60); + return items; + } catch (error) { + if (process.env.NODE_ENV !== 'test') { + console.error('Hackathon news unavailable:', error instanceof Error ? error.message : error); + } + await cache.set(NEWS_CACHE_KEY, [], 2 * 60); + return []; + } +} diff --git a/backend/src/services/notificationService.ts b/backend/src/services/notificationService.ts new file mode 100644 index 0000000..b4e9551 --- /dev/null +++ b/backend/src/services/notificationService.ts @@ -0,0 +1,117 @@ +import { prisma } from '../config/db'; +import { formatNotification } from '../utils/formatters'; +import { emitToUser, isUserViewingChat } from './realtime'; + +interface CreateNotificationInput { + userId: string; + text: string; + type: string; + link?: string; + groupKey?: string; +} + +export async function createNotification(input: CreateNotificationInput) { + const notification = await prisma.notification.create({ + data: { + userId: input.userId, + text: input.text, + type: input.type, + link: input.link, + groupKey: input.groupKey, + }, + }); + + emitToUser(input.userId, 'notification:new', formatNotification(notification)); + return notification; +} + +interface TeamChatNotificationInput { + teamId: string; + teamName: string; + recipientIds: string[]; +} + +/** + * One grouped, unread notification per member per team. The first message + * creates it; later messages increment the count instead of adding noise. + */ +export async function notifyTeamChat({ teamId, teamName, recipientIds }: TeamChatNotificationInput) { + const groupKey = `team_chat:${teamId}`; + const link = `/teams/${teamId}?tab=chat`; + const uniqueRecipients = [...new Set(recipientIds)].filter( + (userId) => !isUserViewingChat(userId, teamId) + ); + + for (const userId of uniqueRecipients) { + const existing = await prisma.notification.findFirst({ + where: { userId, groupKey, isRead: false }, + orderBy: { updatedAt: 'desc' }, + }); + + let notification; + if (existing) { + const count = existing.count + 1; + notification = await prisma.notification.update({ + where: { id: existing.id }, + data: { + count, + text: `${count} new messages in ${teamName}`, + link, + updatedAt: new Date(), + }, + }); + } else { + notification = await prisma.notification.create({ + data: { + userId, + type: 'team_chat', + groupKey, + link, + count: 1, + text: `New message in ${teamName}`, + }, + }); + } + + emitToUser(userId, 'notification:new', formatNotification(notification)); + } +} + +export async function notifyJoinRequest(input: { + leaderId: string; + senderName: string; + teamId: string; + teamName: string; +}) { + return createNotification({ + userId: input.leaderId, + type: 'join_request', + link: `/teams/${input.teamId}`, + text: `${input.senderName} asked to join ${input.teamName}.`, + }); +} + +export async function notifyRequestResponse(input: { + senderId: string; + teamId: string; + teamName: string; + accepted: boolean; +}) { + return createNotification({ + userId: input.senderId, + type: input.accepted ? 'request_accepted' : 'request_rejected', + link: `/teams/${input.teamId}`, + text: input.accepted + ? `Your request to join ${input.teamName} was accepted.` + : `Your request to join ${input.teamName} was declined.`, + }); +} + +export async function notifyFollow(input: { followerId: string; followerName: string; followingId: string }) { + return createNotification({ + userId: input.followingId, + type: 'follow', + link: `/profile/${input.followerId}`, + text: `${input.followerName} started following you.`, + }); +} diff --git a/backend/src/services/realtime.ts b/backend/src/services/realtime.ts new file mode 100644 index 0000000..803dd51 --- /dev/null +++ b/backend/src/services/realtime.ts @@ -0,0 +1,36 @@ +export interface RealtimeEmitter { + emitToUser: (userId: string, event: string, payload: unknown) => void; + emitToRoom: (room: string, event: string, payload: unknown) => void; + isViewingChat: (userId: string, teamId: string) => boolean; + disconnectUser?: (userId: string) => void; +} + +let emitter: RealtimeEmitter | null = null; + +export function setRealtimeEmitter(value: RealtimeEmitter | null): void { + emitter = value; +} + +export function teamRoom(teamId: string): string { + return `team:${teamId}`; +} + +export function userRoom(userId: string): string { + return `user:${userId}`; +} + +export function emitToUser(userId: string, event: string, payload: unknown): void { + emitter?.emitToUser(userId, event, payload); +} + +export function emitToRoom(room: string, event: string, payload: unknown): void { + emitter?.emitToRoom(room, event, payload); +} + +export function isUserViewingChat(userId: string, teamId: string): boolean { + return emitter?.isViewingChat(userId, teamId) ?? false; +} + +export function disconnectUserSockets(userId: string): void { + emitter?.disconnectUser?.(userId); +} diff --git a/backend/src/socket.ts b/backend/src/socket.ts new file mode 100644 index 0000000..6b72d5d --- /dev/null +++ b/backend/src/socket.ts @@ -0,0 +1,131 @@ +import { Server as HttpServer } from 'http'; +import { Server } from 'socket.io'; +import { prisma } from './config/db'; +import { parseCorsOrigins } from './config/cors'; +import { verifyToken } from './middleware/auth'; +import { getTeamForMember, sendChatMessage } from './services/chatService'; +import { setRealtimeEmitter, teamRoom, userRoom } from './services/realtime'; + +interface JoinPayload { + teamId?: string; +} + +interface MessagePayload { + teamId?: string; + content?: string; +} + +type Ack = (response: { ok: boolean; message?: unknown; code?: string; error?: string }) => void; + +export function initSocket(server: HttpServer): Server { + const io = new Server(server, { + cors: { + origin: parseCorsOrigins(process.env.CLIENT_URL), + credentials: true, + }, + transports: ['websocket', 'polling'], + }); + + const activeChats = new Map>(); + + const addActiveChat = (userId: string, teamId: string) => { + const rooms = activeChats.get(userId) || new Set(); + rooms.add(teamId); + activeChats.set(userId, rooms); + }; + + const removeActiveChat = (userId: string, teamId: string) => { + const rooms = activeChats.get(userId); + if (!rooms) return; + rooms.delete(teamId); + if (rooms.size === 0) activeChats.delete(userId); + }; + + const clearActiveChats = (userId: string) => { + activeChats.delete(userId); + }; + + setRealtimeEmitter({ + emitToUser: (userId, event, payload) => { + io.to(userRoom(userId)).emit(event, payload); + }, + emitToRoom: (room, event, payload) => { + io.to(room).emit(event, payload); + }, + isViewingChat: (userId, teamId) => activeChats.get(userId)?.has(teamId) ?? false, + disconnectUser: (userId) => { + io.in(userRoom(userId)).disconnectSockets(true); + }, + }); + + io.use(async (socket, next) => { + const token = (socket.handshake.auth?.token as string | undefined) + || (socket.handshake.query?.token as string | undefined); + if (!token) return next(new Error('unauthorized')); + + const decoded = verifyToken(token); + if (!decoded) return next(new Error('unauthorized')); + + try { + const user = await prisma.user.findUnique({ + where: { id: decoded.id }, + select: { id: true, isBanned: true }, + }); + if (!user || user.isBanned) return next(new Error('unauthorized')); + socket.data.userId = user.id; + socket.join(userRoom(user.id)); + return next(); + } catch { + return next(new Error('unauthorized')); + } + }); + + io.on('connection', (socket) => { + const userId = socket.data.userId as string; + + socket.on('chat:join', async (payload: JoinPayload, ack?: Ack) => { + const teamId = payload?.teamId; + if (!teamId) { + ack?.({ ok: false, code: 'team_not_found', error: 'Team is required.' }); + return; + } + const { team, isMember } = await getTeamForMember(userId, teamId); + if (!team || !isMember) { + ack?.({ ok: false, code: 'not_member', error: 'Only team members can join this chat.' }); + return; + } + await socket.join(teamRoom(teamId)); + addActiveChat(userId, teamId); + ack?.({ ok: true }); + }); + + socket.on('chat:leave', (payload: JoinPayload) => { + const teamId = payload?.teamId; + if (!teamId) return; + socket.leave(teamRoom(teamId)); + removeActiveChat(userId, teamId); + }); + + socket.on('chat:message', async (payload: MessagePayload, ack?: Ack) => { + const teamId = payload?.teamId; + if (!teamId) { + ack?.({ ok: false, code: 'team_not_found', error: 'Team is required.' }); + return; + } + const result = await sendChatMessage(userId, teamId, payload?.content); + if (!result.ok) { + ack?.({ ok: false, code: result.code, error: result.error }); + socket.emit('chat:error', { teamId, code: result.code, error: result.error }); + return; + } + io.to(teamRoom(teamId)).emit('chat:new', { teamId, message: result.message }); + ack?.({ ok: true, message: result.message }); + }); + + socket.on('disconnect', () => { + clearActiveChats(userId); + }); + }); + + return io; +} diff --git a/backend/src/utils/formatters.ts b/backend/src/utils/formatters.ts index d050782..30ae8ae 100755 --- a/backend/src/utils/formatters.ts +++ b/backend/src/utils/formatters.ts @@ -19,6 +19,7 @@ export interface UserSummary { experience: string; isAvailable: boolean; hasAvatar: boolean; + role: string; updatedAt?: string; } @@ -35,11 +36,12 @@ export function formatUserSummary(user: any): UserSummary | null { experience: user.experience, isAvailable: user.isAvailable, hasAvatar: Boolean(user.hasAvatar), + role: user.role || 'user', updatedAt: user.updatedAt?.toISOString(), }; } -export function formatUserDetail(user: any, self = false) { +export function formatUserDetail(user: any, self = false, isFollowing = false) { const summary = formatUserSummary(user); if (!summary) return null; return { @@ -48,6 +50,9 @@ export function formatUserDetail(user: any, self = false) { githubUrl: user.githubUrl || '', linkedinUrl: user.linkedinUrl || '', portfolioUrl: user.portfolioUrl || '', + followerCount: user._count?.followers ?? 0, + followingCount: user._count?.following ?? 0, + isFollowing, createdAt: user.createdAt?.toISOString(), }; } @@ -61,16 +66,24 @@ export function formatHackathonSummary(hackathon: any) { organizer: hackathon.organizer, description: hackathon.description, date: hackathon.date, + endDate: hackathon.endDate || '', registrationDeadline: hackathon.registrationDeadline, location: hackathon.location, + city: hackathon.city || '', mode: hackathon.mode, prizePool: hackathon.prizePool, + websiteUrl: hackathon.websiteUrl || '', + registrationLink: hackathon.registrationLink || '', teamSize: { min: hackathon.minTeamSize, max: hackathon.maxTeamSize, }, tags: parseJsonArray(hackathon.tags), isActive: hackathon.isActive, + source: hackathon.source || '', + sourceUrl: hackathon.sourceUrl || '', + isExternal: Boolean(hackathon.isExternal), + isEditedByAdmin: Boolean(hackathon.isEditedByAdmin), }; } @@ -79,13 +92,41 @@ export function formatHackathonDetail(hackathon: any) { if (!summary) return null; return { ...summary, - registrationLink: hackathon.registrationLink || '', rules: hackathon.rules || '', createdAt: hackathon.createdAt?.toISOString(), updatedAt: hackathon.updatedAt?.toISOString(), }; } +export function formatNotification(notification: any) { + if (!notification) return null; + return { + _id: notification.id, + id: notification.id, + text: notification.text, + type: notification.type, + link: notification.link || '', + groupKey: notification.groupKey || '', + count: notification.count ?? 1, + isRead: notification.isRead, + createdAt: notification.createdAt?.toISOString(), + updatedAt: notification.updatedAt?.toISOString(), + }; +} + +export function formatChatMessage(message: any) { + if (!message) return null; + return { + _id: message.id, + id: message.id, + teamId: message.teamId, + sender: message.sender ? formatUserSummary(message.sender) : null, + content: message.content, + type: message.type, + createdAt: message.createdAt?.toISOString(), + }; +} + export function formatTeamSummary(team: any) { if (!team) return null; return { diff --git a/backend/src/utils/queries.ts b/backend/src/utils/queries.ts index 934ef7a..02c3161 100644 --- a/backend/src/utils/queries.ts +++ b/backend/src/utils/queries.ts @@ -8,6 +8,7 @@ export const userSummarySelect = { experience: true, isAvailable: true, hasAvatar: true, + role: true, updatedAt: true, } as const; @@ -26,14 +27,22 @@ export const hackathonSummarySelect = { organizer: true, description: true, date: true, + endDate: true, registrationDeadline: true, location: true, + city: true, mode: true, prizePool: true, minTeamSize: true, maxTeamSize: true, + websiteUrl: true, + registrationLink: true, tags: true, isActive: true, + source: true, + sourceUrl: true, + isExternal: true, + isEditedByAdmin: true, } as const; export const publicHackathonSelect = { @@ -61,3 +70,7 @@ export const requestInclude = { sender: { select: userSummarySelect }, team: { select: teamSummaryInclude }, } as const; + +export const chatMessageInclude = { + sender: { select: userSummarySelect }, +} as const; diff --git a/backend/src/utils/skills.ts b/backend/src/utils/skills.ts new file mode 100644 index 0000000..e840921 --- /dev/null +++ b/backend/src/utils/skills.ts @@ -0,0 +1,47 @@ +const SKILL_PATTERN = /^[\p{L}\p{N} +#.-]+$/u; + +export const MAX_SKILLS = 15; +export const MAX_SKILL_LENGTH = 30; + +export interface NormalizedSkills { + skills: string[]; + error?: string; +} + +/** + * Trim, collapse whitespace, enforce the shared character set, and merge + * case-insensitive duplicates while keeping the first spelling. + */ +export function normalizeSkills(input: unknown): NormalizedSkills { + if (input === undefined || input === null) return { skills: [] }; + if (!Array.isArray(input)) return { skills: [], error: 'Skills must be a list.' }; + + const skills: string[] = []; + const seen = new Set(); + + for (const raw of input) { + if (typeof raw !== 'string') return { skills: [], error: 'Each skill must be text.' }; + const skill = raw.trim().replace(/\s+/g, ' '); + if (!skill) continue; + if (skill.length > MAX_SKILL_LENGTH) { + return { skills: [], error: `Each skill must be ${MAX_SKILL_LENGTH} characters or fewer.` }; + } + if (!SKILL_PATTERN.test(skill)) { + return { skills: [], error: 'Skills can use letters, numbers, spaces, and + # . - only.' }; + } + const key = skill.toLowerCase(); + if (seen.has(key)) continue; + seen.add(key); + skills.push(skill); + } + + if (skills.length > MAX_SKILLS) { + return { skills: [], error: `Add up to ${MAX_SKILLS} skills.` }; + } + + return { skills }; +} + +export function normalizeSkillList(input: unknown): string[] { + return normalizeSkills(input).skills; +} diff --git a/backend/src/validation/schemas.ts b/backend/src/validation/schemas.ts index 64ed05c..4e65e47 100644 --- a/backend/src/validation/schemas.ts +++ b/backend/src/validation/schemas.ts @@ -13,6 +13,18 @@ const avatarValue = z message: 'Avatar must be a WEBP image under 150 KB.', }); +const skillValue = z + .string() + .trim() + .max(30, 'Each skill must be 30 characters or fewer.') + .regex(/^[\p{L}\p{N} +#.-]+$/u, 'Skills can use letters, numbers, spaces, and + # . - only.'); + +const skillList = z.array(skillValue).max(15, 'Add up to 15 skills.'); + +const isoDate = z + .string() + .regex(/^\d{4}-\d{2}-\d{2}$/, 'Use the YYYY-MM-DD date format.'); + export const registerSchema = z.object({ name: z.string().trim().min(2, 'Name must be at least 2 characters.').max(80), email: z.string().trim().toLowerCase().email('A valid email is required.').max(160), @@ -20,7 +32,7 @@ export const registerSchema = z.object({ college: z.string().trim().min(2, 'College is required.').max(120), branch: z.string().max(120).optional(), bio: z.string().max(500).optional(), - skills: z.array(z.string().max(40)).max(30).optional(), + skills: skillList.optional(), experience: z.enum(['beginner', 'intermediate', 'advanced']).optional(), githubUrl: urlOrEmpty, linkedinUrl: urlOrEmpty, @@ -38,7 +50,7 @@ export const updateProfileSchema = z.object({ branch: z.string().max(120).optional(), bio: z.string().max(500).optional(), avatar: avatarValue.optional(), - skills: z.array(z.string().max(40)).max(30).optional(), + skills: skillList.optional(), experience: z.enum(['beginner', 'intermediate', 'advanced']).optional(), githubUrl: urlOrEmpty, linkedinUrl: urlOrEmpty, @@ -53,7 +65,9 @@ export const paginationQuery = z.object({ skill: z.string().max(40).optional(), experience: z.enum(['beginner', 'intermediate', 'advanced']).optional(), available: z.string().optional(), + following: z.string().optional(), mode: z.enum(['online', 'offline', 'hybrid']).optional(), + city: z.string().max(80).optional(), tag: z.string().max(40).optional(), upcoming: z.string().optional(), hackathonId: z.string().uuid().optional(), @@ -68,7 +82,7 @@ export const publicHackathonQuery = z.object({ export const createTeamSchema = z.object({ teamName: z.string().trim().min(3, 'Team name must be at least 3 characters.').max(60), description: z.string().trim().min(10, 'Description must be at least 10 characters.').max(600), - requiredSkills: z.array(z.string().max(40)).max(20).optional(), + requiredSkills: skillList.optional(), maxSize: z.coerce.number().int().min(2).max(8).optional(), hackathonId: z.string().uuid().nullable().optional(), }); @@ -76,7 +90,7 @@ export const createTeamSchema = z.object({ export const updateTeamSchema = z.object({ teamName: z.string().trim().min(3).max(60).optional(), description: z.string().trim().min(10).max(600).optional(), - requiredSkills: z.array(z.string().max(40)).max(20).optional(), + requiredSkills: skillList.optional(), maxSize: z.coerce.number().int().min(2).max(8).optional(), status: z.enum(['open', 'full', 'closed']).optional(), hackathonId: z.string().uuid().nullable().optional(), @@ -98,3 +112,51 @@ export const respondRequestSchema = z.object({ export const idParam = z.object({ id: z.string().uuid('Invalid id.') }); export const teamIdOnlyParam = z.object({ teamId: z.string().uuid('Invalid team id.') }); + +export const notificationListQuery = z.object({ + page: z.coerce.number().int().min(1).max(1000).default(1), + limit: z.coerce.number().int().min(1).max(50).default(20), +}); + +export const chatHistoryQuery = z.object({ + before: z.string().uuid('Invalid message id.').optional(), + limit: z.coerce.number().int().min(1).max(50).default(50), +}); + +export const followListQuery = z.object({ + page: z.coerce.number().int().min(1).max(1000).default(1), + limit: z.coerce.number().int().min(1).max(50).default(12), +}); + +const adminHackathonBase = z.object({ + title: z.string().trim().min(2, 'Name is required.').max(140), + description: z.string().trim().min(10, 'Description is required.').max(2000), + date: isoDate, + endDate: z.string().trim().optional().or(z.literal('')), + registrationDeadline: isoDate, + mode: z.enum(['online', 'offline', 'hybrid']), + city: z.string().trim().max(80).optional().or(z.literal('')), + websiteUrl: z.string().trim().url('Use a valid website URL.').max(300).optional().or(z.literal('')), + tags: z.array(z.string().trim().min(1).max(30)).max(15).optional(), + prizePool: z.string().trim().max(80).optional(), + organizer: z.string().trim().max(120).optional(), + location: z.string().trim().max(160).optional(), + registrationLink: urlOrEmpty, + rules: z.string().max(1000).optional(), + minTeamSize: z.coerce.number().int().min(1).max(20).optional(), + maxTeamSize: z.coerce.number().int().min(1).max(20).optional(), + isActive: z.boolean().optional(), +}); + +const teamSizeOrder = (value: { minTeamSize?: number; maxTeamSize?: number }) => + !value.minTeamSize || !value.maxTeamSize || value.maxTeamSize >= value.minTeamSize; + +export const adminHackathonSchema = adminHackathonBase.refine(teamSizeOrder, { + message: 'Maximum team size must be at least the minimum.', + path: ['maxTeamSize'], +}); + +export const adminHackathonUpdateSchema = adminHackathonBase.partial().refine(teamSizeOrder, { + message: 'Maximum team size must be at least the minimum.', + path: ['maxTeamSize'], +}); diff --git a/backend/tests/admin.test.ts b/backend/tests/admin.test.ts new file mode 100644 index 0000000..0ebe2b7 --- /dev/null +++ b/backend/tests/admin.test.ts @@ -0,0 +1,379 @@ +import { describe, it, expect, beforeAll, afterAll, afterEach, vi } from 'vitest'; +import request from 'supertest'; +import { app, auth, login, ADMIN_EMAIL } from './helpers'; +import { prisma } from '../src/config/db'; +import { setRealtimeEmitter } from '../src/services/realtime'; + +const RANDOM_ID = '99999999-9999-4999-8999-999999999999'; + +const NEWCOMER = { + name: 'Admin Newcomer', + email: 'admin-newcomer@example.com', + password: 'Password123', + college: 'Test University', +}; + +const LEADER = { + name: 'Admin Team Leader', + email: 'admin-team-leader@example.com', + password: 'Password123', + college: 'Test University', +}; + +let adminToken = ''; +let adminId = ''; +let newcomerToken = ''; +let newcomerId = ''; +let leaderToken = ''; + +async function register(payload: typeof NEWCOMER) { + const response = await request(app).post('/api/auth/register').send(payload); + if (response.status !== 201) { + throw new Error(`Registration failed: ${response.status} ${JSON.stringify(response.body)}`); + } + return response.body.data as { token: string; user: { _id: string } }; +} + +const createdHackathonIds: string[] = []; +const createdSyncIds: string[] = []; + +beforeAll(async () => { + adminToken = await login(ADMIN_EMAIL); + const me = await request(app).get('/api/auth/me').set(auth(adminToken)); + adminId = me.body.data._id; + + const newcomer = await register(NEWCOMER); + newcomerToken = newcomer.token; + newcomerId = newcomer.user._id; + + leaderToken = (await register(LEADER)).token; +}); + +afterAll(async () => { + if (createdHackathonIds.length) { + await prisma.hackathon.deleteMany({ where: { id: { in: createdHackathonIds.splice(0) } } }); + } + if (createdSyncIds.length) { + await prisma.hackathon.deleteMany({ where: { id: { in: createdSyncIds.splice(0) } } }); + } + vi.unstubAllGlobals(); +}); + +afterEach(() => { + setRealtimeEmitter(null); +}); + +describe('admin authorization', () => { + it('requires authentication and rejects non-admins on every route', async () => { + expect((await request(app).get('/api/admin/users')).status).toBe(401); + + const requests: [string, string][] = [ + ['get', '/api/admin/hackathons'], + ['post', '/api/admin/hackathons'], + ['put', `/api/admin/hackathons/${RANDOM_ID}`], + ['delete', `/api/admin/hackathons/${RANDOM_ID}`], + ['post', '/api/admin/hackathons/sync'], + ['get', '/api/admin/hackathons/sync-status'], + ['get', '/api/admin/teams'], + ['delete', `/api/admin/teams/${RANDOM_ID}`], + ['get', '/api/admin/users'], + ['delete', `/api/admin/users/${RANDOM_ID}`], + ['post', `/api/admin/users/${RANDOM_ID}/promote`], + ['post', `/api/admin/users/${RANDOM_ID}/demote`], + ['get', '/api/admin/audit'], + ]; + + for (const [method, url] of requests) { + const response = await ( + method === 'get' + ? request(app).get(url) + : method === 'post' + ? request(app).post(url) + : method === 'put' + ? request(app).put(url) + : request(app).delete(url) + ).set(auth(newcomerToken)); + + expect(response.status, `${method.toUpperCase()} ${url}`).toBe(403); + } + }); + + it('checks the database role even with a valid token', async () => { + await prisma.user.update({ where: { id: newcomerId }, data: { role: 'admin' } }); + expect((await request(app).get('/api/admin/users').set(auth(newcomerToken))).status).toBe(200); + + await prisma.user.update({ where: { id: newcomerId }, data: { role: 'user' } }); + expect((await request(app).get('/api/admin/users').set(auth(newcomerToken))).status).toBe(403); + }); +}); + +describe('admin hackathons', () => { + it('creates, searches, updates, hides, and deletes a hackathon with audit entries', async () => { + const created = await request(app) + .post('/api/admin/hackathons') + .set(auth(adminToken)) + .send({ + title: 'Admin Created Summit', + description: 'A hackathon created through the admin panel for verification.', + date: '2027-08-01', + endDate: '2027-08-03', + registrationDeadline: '2027-07-20', + mode: 'hybrid', + city: 'Lisbon', + websiteUrl: 'https://example.com/admin-summit', + prizePool: '$5,000', + organizer: 'Admin Team', + tags: ['Test', 'Lisbon'], + isActive: true, + }); + expect(created.status).toBe(201); + expect(created.body.data).toMatchObject({ + title: 'Admin Created Summit', + city: 'Lisbon', + mode: 'hybrid', + isExternal: false, + isEditedByAdmin: true, + }); + const hackathonId = created.body.data._id as string; + createdHackathonIds.push(hackathonId); + + const search = await request(app) + .get('/api/admin/hackathons') + .set(auth(adminToken)) + .query({ search: 'Admin Created Summit' }); + expect(search.status).toBe(200); + expect(search.body.data.hackathons.map((item: { _id: string }) => item._id)).toContain(hackathonId); + + const updated = await request(app) + .put(`/api/admin/hackathons/${hackathonId}`) + .set(auth(adminToken)) + .send({ title: 'Admin Created Summit v2', isActive: false }); + expect(updated.status).toBe(200); + expect(updated.body.data.title).toBe('Admin Created Summit v2'); + expect(updated.body.data.isActive).toBe(false); + + const detail = await request(app).get(`/api/hackathons/${hackathonId}`).set(auth(adminToken)); + expect(detail.status).toBe(200); + expect(detail.body.data.isActive).toBe(false); + + const publicList = await request(app) + .get('/api/hackathons') + .set(auth(adminToken)) + .query({ search: 'Admin Created Summit v2' }); + expect(publicList.status).toBe(200); + expect(publicList.body.data.hackathons).toHaveLength(0); + + const adminList = await request(app) + .get('/api/admin/hackathons') + .set(auth(adminToken)) + .query({ search: 'Admin Created Summit v2' }); + expect(adminList.body.data.hackathons).toHaveLength(1); + expect(adminList.body.data.hackathons[0].isActive).toBe(false); + + const audit = await request(app).get('/api/admin/audit').set(auth(adminToken)); + expect(audit.status).toBe(200); + expect(audit.body.data.length).toBeLessThanOrEqual(50); + expect( + audit.body.data.some( + (entry: { action: string; targetId: string }) => + entry.action === 'hackathon.create' && entry.targetId === hackathonId + ) + ).toBe(true); + + const removed = await request(app) + .delete(`/api/admin/hackathons/${hackathonId}`) + .set(auth(adminToken)); + expect(removed.status).toBe(200); + createdHackathonIds.splice(createdHackathonIds.indexOf(hackathonId), 1); + expect((await request(app).get(`/api/hackathons/${hackathonId}`).set(auth(adminToken))).status).toBe(404); + }); + + it('validates hackathon payloads', async () => { + const invalid = await request(app) + .post('/api/admin/hackathons') + .set(auth(adminToken)) + .send({ title: 'x', description: 'short', date: 'nope', registrationDeadline: 'nope', mode: 'online' }); + expect(invalid.status).toBe(400); + }); + + it('runs "sync now", stores imported rows, and reports status', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async () => ({ + ok: true, + status: 200, + json: async () => [ + { + id: 'admin-sync-test-1', + name: 'Admin Sync Test Event', + start: '2027-09-01', + virtual: true, + }, + ], + })) + ); + + const sync = await request(app) + .post('/api/admin/hackathons/sync') + .set(auth(adminToken)); + expect(sync.status).toBe(200); + expect(sync.body.data.created).toBeGreaterThanOrEqual(1); + expect(sync.body.data.errors).toEqual([]); + expect(sync.body.data.status.lastSyncAt).toBeTruthy(); + + const imported = await prisma.hackathon.findFirst({ + where: { source: 'hackclub', externalId: 'admin-sync-test-1' }, + }); + expect(imported?.isExternal).toBe(true); + if (imported) createdSyncIds.push(imported.id); + + const status = await request(app) + .get('/api/admin/hackathons/sync-status') + .set(auth(adminToken)); + expect(status.status).toBe(200); + expect(status.body.data.lastSyncAt).toBeTruthy(); + + vi.unstubAllGlobals(); + }); +}); + +describe('admin teams and users', () => { + it('lists, searches, and deletes teams', async () => { + const team = await request(app) + .post('/api/teams') + .set(auth(leaderToken)) + .send({ + teamName: 'Admin Delete Team', + description: 'A team created so an admin can delete it during verification.', + maxSize: 4, + }); + expect(team.status).toBe(201); + const teamId = team.body.data._id as string; + + const search = await request(app) + .get('/api/admin/teams') + .set(auth(adminToken)) + .query({ search: 'Admin Delete Team' }); + expect(search.status).toBe(200); + expect(search.body.data.teams.map((item: { _id: string }) => item._id)).toContain(teamId); + + const removed = await request(app).delete(`/api/admin/teams/${teamId}`).set(auth(adminToken)); + expect(removed.status).toBe(200); + expect((await request(app).get(`/api/teams/${teamId}`).set(auth(leaderToken))).status).toBe(404); + + const audit = await request(app).get('/api/admin/audit').set(auth(adminToken)); + expect( + audit.body.data.some( + (entry: { action: string; targetId: string }) => + entry.action === 'team.delete' && entry.targetId === teamId + ) + ).toBe(true); + }); + + it('lists users with moderation fields', async () => { + const response = await request(app) + .get('/api/admin/users') + .set(auth(adminToken)) + .query({ search: NEWCOMER.email }); + expect(response.status).toBe(200); + expect(response.body.data.users).toHaveLength(1); + expect(response.body.data.users[0]).toMatchObject({ + _id: newcomerId, + email: NEWCOMER.email, + role: 'user', + }); + expect(response.body.data.users[0]).toHaveProperty('teamsLed'); + expect(response.body.data.users[0]).toHaveProperty('followerCount'); + }); + + it('enforces the last-admin rule for demote and delete', async () => { + const demoteSelf = await request(app) + .post(`/api/admin/users/${adminId}/demote`) + .set(auth(adminToken)); + expect(demoteSelf.status).toBe(400); + + const deleteSelf = await request(app) + .delete(`/api/admin/users/${adminId}`) + .set(auth(adminToken)); + expect(deleteSelf.status).toBe(400); + }); + + it('promotes and demotes users without ever removing the last admin', async () => { + const promote = await request(app) + .post(`/api/admin/users/${newcomerId}/promote`) + .set(auth(adminToken)); + expect(promote.status).toBe(200); + expect(promote.body.data.role).toBe('admin'); + + const demoteOriginal = await request(app) + .post(`/api/admin/users/${adminId}/demote`) + .set(auth(adminToken)); + expect(demoteOriginal.status).toBe(200); + + expect((await request(app).get('/api/admin/users').set(auth(adminToken))).status).toBe(403); + + const lastDemote = await request(app) + .post(`/api/admin/users/${newcomerId}/demote`) + .set(auth(newcomerToken)); + expect(lastDemote.status).toBe(400); + + const lastDelete = await request(app) + .delete(`/api/admin/users/${newcomerId}`) + .set(auth(newcomerToken)); + expect(lastDelete.status).toBe(400); + + const restore = await request(app) + .post(`/api/admin/users/${adminId}/promote`) + .set(auth(newcomerToken)); + expect(restore.status).toBe(200); + + const demoteNewcomer = await request(app) + .post(`/api/admin/users/${newcomerId}/demote`) + .set(auth(newcomerToken)); + expect(demoteNewcomer.status).toBe(200); + + expect((await request(app).get('/api/admin/users').set(auth(adminToken))).status).toBe(200); + expect((await request(app).get('/api/admin/users').set(auth(newcomerToken))).status).toBe(403); + + const audit = await request(app).get('/api/admin/audit').set(auth(adminToken)); + expect( + audit.body.data.some( + (entry: { action: string; targetId: string }) => + entry.action === 'user.promote' && entry.targetId === newcomerId + ) + ).toBe(true); + expect( + audit.body.data.some( + (entry: { action: string; targetId: string }) => + entry.action === 'user.demote' && entry.targetId === newcomerId + ) + ).toBe(true); + }); + + it('deletes a user and disconnects their open sockets', async () => { + const disconnected: string[] = []; + setRealtimeEmitter({ + emitToUser: () => undefined, + emitToRoom: () => undefined, + isViewingChat: () => false, + disconnectUser: (userId) => { + disconnected.push(userId); + }, + }); + + const removed = await request(app) + .delete(`/api/admin/users/${newcomerId}`) + .set(auth(adminToken)); + expect(removed.status).toBe(200); + expect(disconnected).toContain(newcomerId); + expect(await prisma.user.findUnique({ where: { id: newcomerId } })).toBeNull(); + + const audit = await request(app).get('/api/admin/audit').set(auth(adminToken)); + expect( + audit.body.data.some( + (entry: { action: string; targetId: string }) => + entry.action === 'user.delete' && entry.targetId === newcomerId + ) + ).toBe(true); + }); +}); diff --git a/backend/tests/chat.test.ts b/backend/tests/chat.test.ts new file mode 100644 index 0000000..5d1a271 --- /dev/null +++ b/backend/tests/chat.test.ts @@ -0,0 +1,307 @@ +import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest'; +import request from 'supertest'; +import { app, auth } from './helpers'; +import { prisma } from '../src/config/db'; +import { + MAX_MESSAGE_LENGTH, + RATE_LIMIT_MAX, + getChatHistory, + resetChatRateLimits, + sendChatMessage, +} from '../src/services/chatService'; +import { setRealtimeEmitter } from '../src/services/realtime'; + +const LEADER = { + name: 'Chat Leader', + email: 'chat-leader@example.com', + password: 'Password123', + college: 'Test University', +}; +const MEMBER = { + name: 'Chat Member', + email: 'chat-member@example.com', + password: 'Password123', + college: 'Test University', +}; +const OUTSIDER = { + name: 'Chat Outsider', + email: 'chat-outsider@example.com', + password: 'Password123', + college: 'Test University', +}; + +const RANDOM_ID = '99999999-9999-4999-8999-999999999999'; + +let leaderToken = ''; +let leaderId = ''; +let memberToken = ''; +let memberId = ''; +let outsiderToken = ''; +let teamId = ''; + +async function register(payload: typeof LEADER) { + const response = await request(app).post('/api/auth/register').send(payload); + if (response.status !== 201) { + throw new Error(`Registration failed: ${response.status} ${JSON.stringify(response.body)}`); + } + return response.body.data as { token: string; user: { _id: string } }; +} + +beforeAll(async () => { + const leader = await register(LEADER); + leaderToken = leader.token; + leaderId = leader.user._id; + + const member = await register(MEMBER); + memberToken = member.token; + memberId = member.user._id; + + outsiderToken = (await register(OUTSIDER)).token; + + const team = await request(app) + .post('/api/teams') + .set(auth(leaderToken)) + .send({ + teamName: 'Chat Test Team', + description: 'A team created to test the real-time chat service.', + maxSize: 4, + }); + expect(team.status).toBe(201); + teamId = team.body.data._id; + + await prisma.teamMember.create({ data: { teamId, userId: memberId } }); +}); + +beforeEach(() => { + resetChatRateLimits(); + setRealtimeEmitter(null); +}); + +afterEach(() => { + setRealtimeEmitter(null); +}); + +describe('chat service', () => { + it('rejects unknown teams, non-members, empty messages, and long messages', async () => { + await expect(sendChatMessage(leaderId, RANDOM_ID, 'Hello')).resolves.toMatchObject({ + ok: false, + code: 'team_not_found', + }); + + await expect(sendChatMessage(leaderId, teamId, ' ')).resolves.toMatchObject({ + ok: false, + code: 'empty', + }); + + await expect( + sendChatMessage(leaderId, teamId, 'x'.repeat(MAX_MESSAGE_LENGTH + 1)) + ).resolves.toMatchObject({ ok: false, code: 'too_long' }); + + const outsider = await register({ + name: 'Chat Outsider Two', + email: 'chat-outsider-two@example.com', + password: 'Password123', + college: 'Test University', + }); + await expect(sendChatMessage(outsider.user._id, teamId, 'Hello')).resolves.toMatchObject({ + ok: false, + code: 'not_member', + }); + }); + + it('persists trimmed messages for team members', async () => { + const result = await sendChatMessage(leaderId, teamId, ' Hello team '); + expect(result.ok).toBe(true); + if (!result.ok) return; + expect(result.message.content).toBe('Hello team'); + expect(result.message.sender?._id).toBe(leaderId); + expect(result.message.teamId).toBe(teamId); + + const stored = await prisma.message.findUnique({ where: { id: result.message._id } }); + expect(stored?.content).toBe('Hello team'); + }); + + it('rate limits a user after five messages in the window', async () => { + for (let index = 0; index < RATE_LIMIT_MAX; index += 1) { + const result = await sendChatMessage(memberId, teamId, `Message ${index}`); + expect(result.ok).toBe(true); + } + + const blocked = await sendChatMessage(memberId, teamId, 'One too many'); + expect(blocked).toMatchObject({ ok: false, code: 'rate_limit' }); + + resetChatRateLimits(); + const allowedAgain = await sendChatMessage(memberId, teamId, 'After reset'); + expect(allowedAgain.ok).toBe(true); + }); + + it('loads the newest page first and older messages before a cursor', async () => { + const historyTeam = await request(app) + .post('/api/teams') + .set(auth(leaderToken)) + .send({ + teamName: 'Chat History Team', + description: 'A separate team used to keep history assertions deterministic.', + maxSize: 4, + }); + expect(historyTeam.status).toBe(201); + const historyTeamId = historyTeam.body.data._id as string; + + resetChatRateLimits(); + for (let index = 0; index < RATE_LIMIT_MAX; index += 1) { + const result = await sendChatMessage(leaderId, historyTeamId, `History ${index}`); + expect(result.ok).toBe(true); + await new Promise((resolve) => setTimeout(resolve, 5)); + } + + const newest = await getChatHistory(leaderId, historyTeamId, undefined, 2); + expect('messages' in newest).toBe(true); + if (!('messages' in newest)) return; + expect(newest.messages).toHaveLength(2); + expect(newest.messages.map((message) => message.content)).toEqual(['History 3', 'History 4']); + expect(newest.hasMore).toBe(true); + + const older = await getChatHistory(leaderId, historyTeamId, newest.messages[0]._id, 50); + expect('messages' in older).toBe(true); + if (!('messages' in older)) return; + expect(older.messages.map((message) => message.content)).toEqual([ + 'History 0', + 'History 1', + 'History 2', + ]); + + const outsiderId = (await prisma.user.findUnique({ where: { email: 'chat-outsider@example.com' } }))?.id; + const denied = await getChatHistory(outsiderId || RANDOM_ID, historyTeamId); + expect(denied).toEqual({ error: 'not_member' }); + + const missing = await getChatHistory(leaderId, RANDOM_ID); + expect(missing).toEqual({ error: 'team_not_found' }); + }); + + it('creates a grouped chat notification for other members', async () => { + const groupKey = `team_chat:${teamId}`; + await prisma.notification.deleteMany({ where: { userId: leaderId, groupKey } }); + + const first = await sendChatMessage(memberId, teamId, 'First ping'); + const second = await sendChatMessage(memberId, teamId, 'Second ping'); + expect(first.ok && second.ok).toBe(true); + + const notifications = await prisma.notification.findMany({ where: { userId: leaderId, groupKey } }); + expect(notifications).toHaveLength(1); + expect(notifications[0].count).toBe(2); + expect(notifications[0].text).toBe('2 new messages in Chat Test Team'); + }); + + it('does not notify a member who is viewing the chat', async () => { + const groupKey = `team_chat:${teamId}`; + await prisma.notification.deleteMany({ where: { userId: leaderId, groupKey } }); + setRealtimeEmitter({ + emitToUser: () => undefined, + emitToRoom: () => undefined, + isViewingChat: (userId, viewedTeamId) => userId === leaderId && viewedTeamId === teamId, + }); + + const result = await sendChatMessage(memberId, teamId, 'While you were watching'); + expect(result.ok).toBe(true); + + const count = await prisma.notification.count({ where: { userId: leaderId, groupKey } }); + expect(count).toBe(0); + }); +}); + +describe('chat history API', () => { + it('requires authentication and membership', async () => { + expect((await request(app).get(`/api/teams/${teamId}/messages`)).status).toBe(401); + expect( + (await request(app).get(`/api/teams/${teamId}/messages`).set(auth(outsiderToken))).status + ).toBe(403); + expect( + (await request(app).get(`/api/teams/${teamId}/messages`).set(auth(leaderToken))).status + ).toBe(200); + expect( + (await request(app).get(`/api/teams/${RANDOM_ID}/messages`).set(auth(leaderToken))).status + ).toBe(404); + }); + + it('returns formatted messages for members', async () => { + const response = await request(app) + .get(`/api/teams/${teamId}/messages`) + .set(auth(memberToken)) + .query({ limit: 50 }); + expect(response.status).toBe(200); + expect(Array.isArray(response.body.data.messages)).toBe(true); + expect(response.body.data.messages.length).toBeGreaterThan(0); + expect(response.body.data.messages[0]).toMatchObject({ + teamId, + type: 'text', + }); + expect(response.body.data.messages[0].sender).toHaveProperty('name'); + }); + + it('broadcasts chat:removed when a leader disbands the team', async () => { + const team = await request(app) + .post('/api/teams') + .set(auth(leaderToken)) + .send({ + teamName: 'Chat Disband Team', + description: 'A short-lived team used to verify chat cleanup on disband.', + maxSize: 4, + }); + expect(team.status).toBe(201); + const disbandId = team.body.data._id as string; + + const events: { room: string; event: string; payload: unknown }[] = []; + setRealtimeEmitter({ + emitToUser: () => undefined, + emitToRoom: (room, event, payload) => { + events.push({ room, event, payload }); + }, + isViewingChat: () => false, + }); + + const removed = await request(app).delete(`/api/teams/${disbandId}`).set(auth(leaderToken)); + expect(removed.status).toBe(200); + expect(events).toContainEqual( + expect.objectContaining({ + room: `team:${disbandId}`, + event: 'chat:removed', + payload: expect.objectContaining({ teamId: disbandId }), + }) + ); + }); + + it('revokes chat access immediately when a member leaves', async () => { + const userEvents: { userId: string; event: string; payload: unknown }[] = []; + setRealtimeEmitter({ + emitToUser: (userId, event, payload) => { + userEvents.push({ userId, event, payload }); + }, + emitToRoom: () => undefined, + isViewingChat: () => false, + }); + + const left = await request(app).delete(`/api/teams/${teamId}/leave`).set(auth(memberToken)); + expect(left.status).toBe(200); + expect(userEvents).toContainEqual( + expect.objectContaining({ + userId: memberId, + event: 'chat:removed', + payload: expect.objectContaining({ teamId }), + }) + ); + + expect( + (await request(app).get(`/api/teams/${teamId}/messages`).set(auth(memberToken))).status + ).toBe(403); + await expect(sendChatMessage(memberId, teamId, 'After leaving')).resolves.toMatchObject({ + ok: false, + code: 'not_member', + }); + + const leaderLeave = await request(app) + .delete(`/api/teams/${teamId}/leave`) + .set(auth(leaderToken)); + expect(leaderLeave.status).toBe(400); + expect((await request(app).delete(`/api/teams/${teamId}/leave`).set(auth(outsiderToken))).status).toBe(400); + }); +}); diff --git a/backend/tests/follows.test.ts b/backend/tests/follows.test.ts new file mode 100644 index 0000000..a294552 --- /dev/null +++ b/backend/tests/follows.test.ts @@ -0,0 +1,158 @@ +import { describe, it, expect, beforeAll } from 'vitest'; +import request from 'supertest'; +import { app, auth } from './helpers'; +import { prisma } from '../src/config/db'; + +const RANDOM_ID = '99999999-9999-4999-8999-999999999999'; + +const FOLLOWER = { + name: 'Follow Follower', + email: 'follow-follower@example.com', + password: 'Password123', + college: 'Test University', + skills: ['React'], +}; +const TARGET = { + name: 'Follow Target', + email: 'follow-target@example.com', + password: 'Password123', + college: 'Test University', + skills: ['Python'], +}; +const OTHER = { + name: 'Follow Other', + email: 'follow-other@example.com', + password: 'Password123', + college: 'Test University', + skills: ['Go'], +}; + +let followerToken = ''; +let followerId = ''; +let targetToken = ''; +let targetId = ''; +let otherToken = ''; + +async function register(payload: typeof FOLLOWER) { + const response = await request(app).post('/api/auth/register').send(payload); + if (response.status !== 201) { + throw new Error(`Registration failed: ${response.status} ${JSON.stringify(response.body)}`); + } + return response.body.data as { token: string; user: { _id: string } }; +} + +beforeAll(async () => { + const follower = await register(FOLLOWER); + followerToken = follower.token; + followerId = follower.user._id; + + const target = await register(TARGET); + targetToken = target.token; + targetId = target.user._id; + + otherToken = (await register(OTHER)).token; +}); + +describe('follows', () => { + it('requires authentication for follow actions and lists', async () => { + expect((await request(app).post(`/api/users/${targetId}/follow`)).status).toBe(401); + expect((await request(app).delete(`/api/users/${targetId}/follow`)).status).toBe(401); + expect((await request(app).get(`/api/users/${targetId}/followers`)).status).toBe(401); + expect((await request(app).get(`/api/users/${targetId}/following`)).status).toBe(401); + }); + + it('rejects self-follows, unknown users, and duplicates', async () => { + const self = await request(app).post(`/api/users/${followerId}/follow`).set(auth(followerToken)); + expect(self.status).toBe(400); + + const missing = await request(app).post(`/api/users/${RANDOM_ID}/follow`).set(auth(followerToken)); + expect(missing.status).toBe(404); + + const first = await request(app).post(`/api/users/${targetId}/follow`).set(auth(followerToken)); + expect(first.status).toBe(201); + expect(first.body.data.isFollowing).toBe(true); + + const duplicate = await request(app).post(`/api/users/${targetId}/follow`).set(auth(followerToken)); + expect(duplicate.status).toBe(400); + }); + + it('updates follower counts and exposes paginated follower/following lists', async () => { + const targetProfile = await request(app).get(`/api/users/${targetId}`).set(auth(followerToken)); + expect(targetProfile.status).toBe(200); + expect(targetProfile.body.data.followerCount).toBe(1); + expect(targetProfile.body.data.isFollowing).toBe(true); + + const followerProfile = await request(app).get(`/api/users/${followerId}`).set(auth(followerToken)); + expect(followerProfile.body.data.followingCount).toBe(1); + expect(followerProfile.body.data.isFollowing).toBe(false); + + const followers = await request(app) + .get(`/api/users/${targetId}/followers`) + .set(auth(targetToken)) + .query({ page: 1, limit: 1 }); + expect(followers.status).toBe(200); + expect(followers.body.data.users).toHaveLength(1); + expect(followers.body.data.users[0]._id).toBe(followerId); + expect(followers.body.data.pagination).toMatchObject({ total: 1, page: 1, limit: 1, pages: 1 }); + + const following = await request(app) + .get(`/api/users/${followerId}/following`) + .set(auth(followerToken)); + expect(following.status).toBe(200); + expect(following.body.data.users.map((user: { _id: string }) => user._id)).toContain(targetId); + }); + + it('notifies the followed user', async () => { + const notifications = await request(app).get('/api/notifications').set(auth(targetToken)); + expect(notifications.status).toBe(200); + const follow = notifications.body.data.notifications.find( + (notification: { type: string }) => notification.type === 'follow' + ); + expect(follow).toBeTruthy(); + expect(follow.text).toContain(FOLLOWER.name); + expect(follow.link).toBe(`/profile/${followerId}`); + }); + + it('supports the people "only people I follow" filter', async () => { + const response = await request(app) + .get('/api/users') + .set(auth(followerToken)) + .query({ following: 'true', limit: 100 }); + expect(response.status).toBe(200); + const ids = response.body.data.users.map((user: { _id: string }) => user._id); + expect(ids).toContain(targetId); + expect(ids).not.toContain(followerId); + + const otherView = await request(app) + .get('/api/users') + .set(auth(otherToken)) + .query({ following: 'true', limit: 100 }); + expect(otherView.body.data.users).toHaveLength(0); + }); + + it('unfollows idempotently and updates counts', async () => { + const removed = await request(app).delete(`/api/users/${targetId}/follow`).set(auth(followerToken)); + expect(removed.status).toBe(200); + expect(removed.body.data).toEqual({ isFollowing: false, removed: true }); + + const again = await request(app).delete(`/api/users/${targetId}/follow`).set(auth(followerToken)); + expect(again.status).toBe(200); + expect(again.body.data.removed).toBe(false); + + const profile = await request(app).get(`/api/users/${targetId}`).set(auth(followerToken)); + expect(profile.body.data.followerCount).toBe(0); + expect(profile.body.data.isFollowing).toBe(false); + }); + + it('cascades follows when a user is deleted', async () => { + const created = await request(app).post(`/api/users/${targetId}/follow`).set(auth(otherToken)); + expect(created.status).toBe(201); + + await prisma.user.delete({ where: { id: targetId } }); + + const remaining = await prisma.follow.count({ + where: { OR: [{ followerId: targetId }, { followingId: targetId }] }, + }); + expect(remaining).toBe(0); + }); +}); diff --git a/backend/tests/hackathonSync.test.ts b/backend/tests/hackathonSync.test.ts new file mode 100644 index 0000000..d3125f8 --- /dev/null +++ b/backend/tests/hackathonSync.test.ts @@ -0,0 +1,287 @@ +import { describe, it, expect, afterEach, beforeAll } from 'vitest'; +import request from 'supertest'; +import { app, auth, login, PRIYA_EMAIL } from './helpers'; +import { prisma } from '../src/config/db'; +import { + SYNC_STATE_ID, + fetchHackClubEvents, + getHackathonNews, + getSyncStatus, + normalizeHackClubEvent, + storeExternalHackathons, + syncHackathons, + type FetchLike, + type NormalizedExternalHackathon, +} from '../src/services/hackathonSyncService'; + +const TEST_SOURCE = 'test-source'; +const createdIds: string[] = []; + +function externalItem(overrides: Partial = {}): NormalizedExternalHackathon { + return { + source: TEST_SOURCE, + externalId: 'test-event-1', + title: 'Test Event', + organizer: 'Test Org', + description: 'A test event used to exercise the sync service.', + date: '2027-03-01', + endDate: '2027-03-02', + registrationDeadline: '2027-02-20', + location: 'Test City', + city: 'Test City', + mode: 'offline', + prizePool: 'See official site', + tags: ['Hackathon', 'Test City'], + websiteUrl: 'https://example.com/event', + sourceUrl: 'https://example.com/source', + ...overrides, + }; +} + +function fakeFetch(payload: unknown, ok = true): FetchLike { + return async () => ({ + ok, + status: ok ? 200 : 500, + json: async () => payload, + }); +} + +afterEach(async () => { + if (createdIds.length) { + await prisma.hackathon.deleteMany({ where: { id: { in: createdIds.splice(0) } } }); + } +}); + +describe('hackathon normalizer', () => { + it('normalizes a virtual Hack Club event', () => { + const event = normalizeHackClubEvent({ + id: 'virtual-1', + name: ' Virtual Build Weekend ', + start: '2027-03-01T12:00:00.000Z', + end: '2027-03-03T12:00:00.000Z', + virtual: true, + website: 'https://example.com/virtual', + }); + expect(event).toMatchObject({ + source: 'hackclub', + externalId: 'virtual-1', + title: 'Virtual Build Weekend', + date: '2027-03-01', + endDate: '2027-03-03', + location: 'Online', + city: 'Online', + mode: 'online', + websiteUrl: 'https://example.com/virtual', + }); + expect(event?.tags).toContain('Online'); + }); + + it('normalizes a hybrid event with a city', () => { + const event = normalizeHackClubEvent({ + id: 'hybrid-1', + name: 'Hybrid Hack', + start: '2027-04-01', + hybrid: true, + city: 'Berlin', + state: 'Berlin', + country: 'Germany', + }); + expect(event).toMatchObject({ + mode: 'hybrid', + location: 'Berlin, Germany', + city: 'Berlin', + websiteUrl: '', + }); + }); + + it('rejects events without an id, name, or valid date', () => { + expect(normalizeHackClubEvent(null)).toBeNull(); + expect(normalizeHackClubEvent({ id: 'x', name: 'No date' })).toBeNull(); + expect(normalizeHackClubEvent({ name: 'No id', start: '2027-01-01' })).toBeNull(); + expect(normalizeHackClubEvent({ id: 'x', name: 'Bad date', start: 'not-a-date' })).toBeNull(); + }); + + it('parses the Hack Club payload and ignores invalid rows', async () => { + const events = await fetchHackClubEvents( + fakeFetch([ + { id: 'a', name: 'Good Event', start: '2027-01-01' }, + { id: 'b', name: 'Bad Event', start: 'not-a-date' }, + ]) + ); + expect(events).toHaveLength(1); + expect(events[0].externalId).toBe('a'); + }); + + it('reports a non-200 source response', async () => { + await expect(fetchHackClubEvents(fakeFetch({}, false))).rejects.toThrow('HTTP 500'); + }); +}); + +describe('hackathon import and edit protection', () => { + it('dedupes by source and external id', async () => { + const first = await storeExternalHackathons([externalItem()]); + expect(first).toEqual({ created: 1, updated: 0, skipped: 0 }); + + const rows = await prisma.hackathon.findMany({ + where: { source: TEST_SOURCE, externalId: 'test-event-1' }, + }); + expect(rows).toHaveLength(1); + createdIds.push(rows[0].id); + + const second = await storeExternalHackathons([ + externalItem({ title: 'Test Event Updated', tags: ['Hackathon', 'Updated'] }), + ]); + expect(second).toEqual({ created: 0, updated: 1, skipped: 0 }); + + const updated = await prisma.hackathon.findUnique({ where: { id: rows[0].id } }); + expect(updated?.title).toBe('Test Event Updated'); + expect(updated?.isExternal).toBe(true); + expect(updated?.source).toBe(TEST_SOURCE); + expect(updated?.externalId).toBe('test-event-1'); + }); + + it('never overwrites a hackathon an admin created or edited', async () => { + const adminRow = await prisma.hackathon.create({ + data: { + title: 'Admin Owned Event', + organizer: 'HackMatch', + description: 'Created by an admin and must not be overwritten by a sync.', + date: '2027-03-01', + registrationDeadline: '2027-02-20', + location: 'Test City', + city: 'Test City', + mode: 'offline', + prizePool: 'See official site', + tags: '[]', + source: TEST_SOURCE, + externalId: 'admin-owned-1', + isExternal: true, + isEditedByAdmin: true, + }, + }); + createdIds.push(adminRow.id); + + const result = await storeExternalHackathons([ + externalItem({ externalId: 'admin-owned-1', title: 'Overwritten Title' }), + ]); + expect(result).toEqual({ created: 0, updated: 0, skipped: 1 }); + + const stored = await prisma.hackathon.findUnique({ where: { id: adminRow.id } }); + expect(stored?.title).toBe('Admin Owned Event'); + }); + + it('isolates a failing source and still records sync status', async () => { + const result = await syncHackathons({ + fetchImpl: async () => { + throw new Error('source offline'); + }, + }); + expect(result.created).toBe(0); + expect(result.errors[0]).toContain('Hack Club'); + expect(result.errors[0]).toContain('source offline'); + + const status = await getSyncStatus(); + expect(status.lastSyncAt).toBeTruthy(); + expect(status.lastError).toContain('source offline'); + }); + + it('syncs successfully through the shared fetch path', async () => { + const result = await syncHackathons({ + fetchImpl: fakeFetch([ + { + id: 'sync-test-1', + name: 'Sync Test Event', + start: '2027-05-01', + end: '2027-05-02', + virtual: true, + website: 'https://example.com/sync', + }, + ]), + }); + expect(result.errors).toEqual([]); + expect(result.created).toBeGreaterThanOrEqual(1); + + const rows = await prisma.hackathon.findMany({ + where: { source: 'hackclub', externalId: 'sync-test-1' }, + }); + expect(rows).toHaveLength(1); + createdIds.push(rows[0].id); + expect(rows[0].isExternal).toBe(true); + expect(rows[0].sourceUrl).toBe('https://hackathons.hackclub.com/'); + + const status = await prisma.syncState.findUnique({ where: { id: SYNC_STATE_ID } }); + expect(status?.lastError).toBeNull(); + }); +}); + +describe('hackathon news', () => { + it('maps verified dev.to articles and filters invalid rows', async () => { + const items = await getHackathonNews({ + force: true, + fetchImpl: fakeFetch([ + { title: 'First article', url: 'https://dev.to/one', published_timestamp: '2027-01-01T00:00:00Z' }, + { title: 'Missing url' }, + { title: 'Bad url', url: 'javascript:alert(1)' }, + { title: 'Second article', url: 'https://dev.to/two', published_timestamp: '' }, + ]), + }); + expect(items).toHaveLength(2); + expect(items[0]).toMatchObject({ title: 'First article', source: 'DEV Community' }); + }); + + it('returns an empty list when the news source fails', async () => { + const items = await getHackathonNews({ + force: true, + fetchImpl: async () => { + throw new Error('news offline'); + }, + }); + expect(items).toEqual([]); + }); +}); + +describe('hackathon filters', () => { + let token = ''; + beforeAll(async () => { + token = await login(PRIYA_EMAIL); + }); + + it('filters by mode, city, and search', async () => { + const online = await request(app) + .get('/api/hackathons') + .set(auth(token)) + .query({ mode: 'online', limit: 100 }); + expect(online.status).toBe(200); + expect(online.body.data.hackathons.length).toBeGreaterThan(0); + expect(online.body.data.hackathons.every((item: { mode: string }) => item.mode === 'online')).toBe(true); + + const berlin = await request(app) + .get('/api/hackathons') + .set(auth(token)) + .query({ city: 'Berlin, Germany', limit: 100 }); + expect(berlin.status).toBe(200); + expect(berlin.body.data.hackathons.length).toBeGreaterThanOrEqual(2); + expect( + berlin.body.data.hackathons.every((item: { city: string }) => item.city === 'Berlin, Germany') + ).toBe(true); + + const search = await request(app) + .get('/api/hackathons') + .set(auth(token)) + .query({ search: 'NovaHack', limit: 100 }); + expect(search.status).toBe(200); + expect(search.body.data.hackathons).toHaveLength(1); + expect(search.body.data.hackathons[0].title).toBe('NovaHack 2027'); + }); + + it('exposes city options and hides news gracefully', async () => { + const cities = await request(app).get('/api/hackathons/cities'); + expect(cities.status).toBe(200); + expect(cities.body.data.cities).toContain('Berlin, Germany'); + expect(cities.body.data.cities).toContain('Online'); + + const news = await request(app).get('/api/hackathons/news'); + expect(news.status).toBe(200); + expect(Array.isArray(news.body.data.items)).toBe(true); + }); +}); diff --git a/backend/tests/helpers.ts b/backend/tests/helpers.ts index 3f70ea7..466b424 100644 --- a/backend/tests/helpers.ts +++ b/backend/tests/helpers.ts @@ -7,6 +7,7 @@ export const DEMO_PASSWORD = 'Demo1234!'; export const AISHA_EMAIL = 'aisha.rahman@hackmatch.dev'; export const PRIYA_EMAIL = 'priya.menon@example.com'; export const MARCUS_EMAIL = 'marcus.lee@example.com'; +export const ADMIN_EMAIL = 'admin@hackmatch.dev'; export async function login(email: string, password: string = DEMO_PASSWORD): Promise { const response = await request(app).post('/api/auth/login').send({ email, password }); diff --git a/backend/tests/notifications.test.ts b/backend/tests/notifications.test.ts new file mode 100644 index 0000000..f4237e1 --- /dev/null +++ b/backend/tests/notifications.test.ts @@ -0,0 +1,228 @@ +import { describe, it, expect, beforeAll, afterEach } from 'vitest'; +import request from 'supertest'; +import { app, auth } from './helpers'; +import { prisma } from '../src/config/db'; +import { createNotification, notifyTeamChat } from '../src/services/notificationService'; +import { setRealtimeEmitter } from '../src/services/realtime'; + +const OWNER = { + name: 'Notification Owner', + email: 'notification-owner@example.com', + password: 'Password123', + college: 'Test University', +}; +const STRANGER = { + name: 'Notification Stranger', + email: 'notification-stranger@example.com', + password: 'Password123', + college: 'Test University', +}; + +let ownerToken = ''; +let ownerId = ''; +let strangerToken = ''; + +async function register(payload: typeof OWNER) { + const response = await request(app).post('/api/auth/register').send(payload); + if (response.status !== 201) { + throw new Error(`Registration failed: ${response.status} ${JSON.stringify(response.body)}`); + } + return response.body.data as { token: string; user: { _id: string } }; +} + +beforeAll(async () => { + const owner = await register(OWNER); + ownerToken = owner.token; + ownerId = owner.user._id; + strangerToken = (await register(STRANGER)).token; +}); + +afterEach(() => { + setRealtimeEmitter(null); +}); + +describe('notifications', () => { + it('requires authentication', async () => { + expect((await request(app).get('/api/notifications')).status).toBe(401); + expect((await request(app).get('/api/notifications/unread-count')).status).toBe(401); + expect((await request(app).put('/api/notifications/read-all')).status).toBe(401); + }); + + it('only returns the owner notifications', async () => { + const notification = await createNotification({ + userId: ownerId, + type: 'join_request', + text: 'Someone asked to join your team.', + link: '/teams/33333333-3333-4333-8333-333333333331', + }); + + const ownerView = await request(app).get('/api/notifications').set(auth(ownerToken)); + expect(ownerView.status).toBe(200); + expect(ownerView.body.data.notifications.map((item: { _id: string }) => item._id)).toContain( + notification.id + ); + expect(ownerView.body.data.unreadCount).toBe(1); + expect(ownerView.body.data.pagination).toMatchObject({ total: 1, page: 1, limit: 20, pages: 1 }); + + const strangerView = await request(app).get('/api/notifications').set(auth(strangerToken)); + expect(strangerView.status).toBe(200); + expect(strangerView.body.data.notifications).toHaveLength(0); + + const strangerCount = await request(app) + .get('/api/notifications/unread-count') + .set(auth(strangerToken)); + expect(strangerCount.body.data.unreadCount).toBe(0); + }); + + it('prevents other users from marking a notification read', async () => { + await request(app).put('/api/notifications/read-all').set(auth(ownerToken)); + + const notification = await createNotification({ + userId: ownerId, + type: 'follow', + text: 'Someone started following you.', + }); + + const stranger = await request(app) + .put(`/api/notifications/${notification.id}/read`) + .set(auth(strangerToken)); + expect(stranger.status).toBe(404); + + const owner = await request(app) + .put(`/api/notifications/${notification.id}/read`) + .set(auth(ownerToken)); + expect(owner.status).toBe(200); + expect(owner.body.data.isRead).toBe(true); + + const count = await request(app).get('/api/notifications/unread-count').set(auth(ownerToken)); + expect(count.body.data.unreadCount).toBe(0); + }); + + it('marks all notifications read and reports the updated count', async () => { + await createNotification({ userId: ownerId, type: 'follow', text: 'First.' }); + await createNotification({ userId: ownerId, type: 'follow', text: 'Second.' }); + + const response = await request(app).put('/api/notifications/read-all').set(auth(ownerToken)); + expect(response.status).toBe(200); + expect(response.body.data.unreadCount).toBe(0); + expect(response.body.data.updated).toBeGreaterThanOrEqual(2); + + const count = await request(app).get('/api/notifications/unread-count').set(auth(ownerToken)); + expect(count.body.data.unreadCount).toBe(0); + }); + + it('paginates the full notifications page', async () => { + for (let index = 0; index < 3; index += 1) { + await createNotification({ userId: ownerId, type: 'follow', text: `Paged ${index}` }); + } + + const first = await request(app) + .get('/api/notifications') + .set(auth(ownerToken)) + .query({ page: 1, limit: 2 }); + expect(first.status).toBe(200); + expect(first.body.data.notifications).toHaveLength(2); + expect(first.body.data.pagination.pages).toBeGreaterThanOrEqual(2); + }); + + it('groups team chat notifications per team and increments the count', async () => { + const teamId = '33333333-3333-4333-8333-333333333331'; + const groupKey = `team_chat:${teamId}`; + + await prisma.notification.deleteMany({ where: { userId: ownerId, groupKey } }); + await notifyTeamChat({ teamId, teamName: 'Neural Sync', recipientIds: [ownerId] }); + await notifyTeamChat({ teamId, teamName: 'Neural Sync', recipientIds: [ownerId] }); + + const notifications = await prisma.notification.findMany({ + where: { userId: ownerId, groupKey }, + }); + expect(notifications).toHaveLength(1); + expect(notifications[0].count).toBe(2); + expect(notifications[0].text).toBe('2 new messages in Neural Sync'); + expect(notifications[0].link).toBe(`/teams/${teamId}?tab=chat`); + }); + + it('skips team chat notifications while the recipient is viewing that chat', async () => { + const teamId = '33333333-3333-4333-8333-333333333332'; + const groupKey = `team_chat:${teamId}`; + + await prisma.notification.deleteMany({ where: { userId: ownerId, groupKey } }); + setRealtimeEmitter({ + emitToUser: () => undefined, + emitToRoom: () => undefined, + isViewingChat: () => true, + }); + + await notifyTeamChat({ teamId, teamName: 'GreenLoop', recipientIds: [ownerId] }); + + const count = await prisma.notification.count({ where: { userId: ownerId, groupKey } }); + expect(count).toBe(0); + }); + + it('creates notifications for join requests and responses', async () => { + const team = await request(app) + .post('/api/teams') + .set(auth(ownerToken)) + .send({ + teamName: 'Notification Request Team', + description: 'A team created to verify join-request notifications.', + maxSize: 4, + }); + expect(team.status).toBe(201); + const teamId = team.body.data._id as string; + + const joinRequest = await request(app) + .post('/api/requests') + .set(auth(strangerToken)) + .send({ teamId, message: 'I would like to join.' }); + expect(joinRequest.status).toBe(201); + + const leaderNotifications = await request(app).get('/api/notifications').set(auth(ownerToken)); + const joinNotification = leaderNotifications.body.data.notifications.find( + (item: { type: string; link: string }) => + item.type === 'join_request' && item.link === `/teams/${teamId}` + ); + expect(joinNotification).toBeTruthy(); + expect(joinNotification.text).toContain(STRANGER.name); + + const accepted = await request(app) + .put(`/api/requests/${joinRequest.body.data._id}/respond`) + .set(auth(ownerToken)) + .send({ action: 'accept' }); + expect(accepted.status).toBe(200); + + const applicantNotifications = await request(app).get('/api/notifications').set(auth(strangerToken)); + const acceptedNotification = applicantNotifications.body.data.notifications.find( + (item: { type: string }) => item.type === 'request_accepted' + ); + expect(acceptedNotification).toBeTruthy(); + expect(acceptedNotification.link).toBe(`/teams/${teamId}`); + + const secondTeam = await request(app) + .post('/api/teams') + .set(auth(ownerToken)) + .send({ + teamName: 'Notification Decline Team', + description: 'A second team created to verify declined request notifications.', + maxSize: 4, + }); + const declinedRequest = await request(app) + .post('/api/requests') + .set(auth(strangerToken)) + .send({ teamId: secondTeam.body.data._id }); + expect(declinedRequest.status).toBe(201); + + const declined = await request(app) + .put(`/api/requests/${declinedRequest.body.data._id}/respond`) + .set(auth(ownerToken)) + .send({ action: 'reject' }); + expect(declined.status).toBe(200); + + const afterDecline = await request(app).get('/api/notifications').set(auth(strangerToken)); + expect( + afterDecline.body.data.notifications.some( + (item: { type: string }) => item.type === 'request_rejected' + ) + ).toBe(true); + }); +}); diff --git a/backend/tests/seed.test.ts b/backend/tests/seed.test.ts index 25752d7..4c6cbf2 100644 --- a/backend/tests/seed.test.ts +++ b/backend/tests/seed.test.ts @@ -14,6 +14,8 @@ async function counts() { return { users, hackathons, teams, requests, members, registrations }; } +const NEURAL_TEAM_ID = '33333333-3333-4333-8333-333333333331'; + describe('seed script', () => { it('is idempotent and never duplicates seeded rows', async () => { const before = await counts(); @@ -35,4 +37,21 @@ describe('seed script', () => { expect(after.requests).toBeGreaterThanOrEqual(12); expect(after.members).toBeGreaterThanOrEqual(24); }); + + it('never overwrites edits made to seeded records', async () => { + const original = await prisma.team.findUniqueOrThrow({ where: { id: NEURAL_TEAM_ID } }); + const changedName = `${original.teamName} (edited after seed)`; + + await prisma.team.update({ where: { id: NEURAL_TEAM_ID }, data: { teamName: changedName } }); + try { + await seedDatabase(); + const stored = await prisma.team.findUniqueOrThrow({ where: { id: NEURAL_TEAM_ID } }); + expect(stored.teamName).toBe(changedName); + } finally { + await prisma.team.update({ + where: { id: NEURAL_TEAM_ID }, + data: { teamName: original.teamName }, + }); + } + }); }); diff --git a/backend/tests/skills.test.ts b/backend/tests/skills.test.ts new file mode 100644 index 0000000..49d0491 --- /dev/null +++ b/backend/tests/skills.test.ts @@ -0,0 +1,99 @@ +import { describe, it, expect } from 'vitest'; +import request from 'supertest'; +import { app, auth } from './helpers'; +import { MAX_SKILLS, MAX_SKILL_LENGTH, normalizeSkills } from '../src/utils/skills'; + +const USER = { + name: 'Skill Tester', + email: 'skills-tester@example.com', + password: 'Password123', + college: 'Test University', + skills: ['React'], +}; + +describe('skill normalization', () => { + it('trims, collapses whitespace, and keeps the first spelling', () => { + expect(normalizeSkills([' React ', 'react', 'Node JS', 'Node JS '])).toEqual({ + skills: ['React', 'Node JS'], + }); + }); + + it('allows letters, numbers, spaces, and + # . -', () => { + expect(normalizeSkills(['C++', 'C#', 'Node.js', 'UI Design', 'Go-lang'])).toEqual({ + skills: ['C++', 'C#', 'Node.js', 'UI Design', 'Go-lang'], + }); + }); + + it('rejects unsupported characters and overly long skills', () => { + expect(normalizeSkills(['React!']).error).toBeTypeOf('string'); + expect(normalizeSkills(['x'.repeat(MAX_SKILL_LENGTH + 1)]).error).toBeTypeOf('string'); + expect(normalizeSkills([42]).error).toBeTypeOf('string'); + expect(normalizeSkills('React').error).toBeTypeOf('string'); + }); + + it('caps the list at 15 skills', () => { + const tooMany = Array.from({ length: MAX_SKILLS + 1 }, (_, index) => `Skill ${index}`); + expect(normalizeSkills(tooMany).error).toBeTypeOf('string'); + + const exact = Array.from({ length: MAX_SKILLS }, (_, index) => `Skill ${index}`); + expect(normalizeSkills(exact).skills).toHaveLength(MAX_SKILLS); + }); + + it('drops empty entries and ignores non-array input', () => { + expect(normalizeSkills(['React', ' ', '']).skills).toEqual(['React']); + expect(normalizeSkills(undefined).skills).toEqual([]); + }); +}); + +describe('custom skills through the API', () => { + it('normalizes profile skills and rejects invalid values', async () => { + const registration = await request(app).post('/api/auth/register').send(USER); + expect(registration.status).toBe(201); + const token = registration.body.data.token as string; + + const updated = await request(app) + .put('/api/users/profile') + .set(auth(token)) + .send({ skills: [' Rust ', 'rust', 'Node JS', 'C++'] }); + expect(updated.status).toBe(200); + expect(updated.body.data.skills).toEqual(['Rust', 'Node JS', 'C++']); + + const invalid = await request(app) + .put('/api/users/profile') + .set(auth(token)) + .send({ skills: ['React!'] }); + expect(invalid.status).toBe(400); + + const tooMany = await request(app) + .put('/api/users/profile') + .set(auth(token)) + .send({ skills: Array.from({ length: MAX_SKILLS + 1 }, (_, index) => `Skill ${index}`) }); + expect(tooMany.status).toBe(400); + }); + + it('normalizes required skills on team create and edit', async () => { + const registration = await request(app).post('/api/auth/register').send({ + ...USER, + email: 'skills-team-owner@example.com', + }); + const token = registration.body.data.token as string; + + const created = await request(app) + .post('/api/teams') + .set(auth(token)) + .send({ + teamName: 'Skillful Builders', + description: 'A team built to test custom skill normalization.', + requiredSkills: [' Figma ', 'figma', 'Public Speaking'], + }); + expect(created.status).toBe(201); + expect(created.body.data.requiredSkills).toEqual(['Figma', 'Public Speaking']); + + const updated = await request(app) + .put(`/api/teams/${created.body.data._id}`) + .set(auth(token)) + .send({ requiredSkills: ['C++', 'c++', 'Graphic Design'] }); + expect(updated.status).toBe(200); + expect(updated.body.data.requiredSkills).toEqual(['C++', 'Graphic Design']); + }); +}); diff --git a/client/package-lock.json b/client/package-lock.json index afda50b..a42cb7d 100755 --- a/client/package-lock.json +++ b/client/package-lock.json @@ -13,6 +13,7 @@ "react": "^19.2.6", "react-dom": "^19.2.6", "react-router-dom": "^7.16.0", + "socket.io-client": "^4.8.4", "zustand": "^5.0.14" }, "devDependencies": { @@ -1616,6 +1617,12 @@ "win32" ] }, + "node_modules/@socket.io/component-emitter": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz", + "integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==", + "license": "MIT" + }, "node_modules/@tailwindcss/node": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.0.tgz", @@ -3094,6 +3101,28 @@ "dev": true, "license": "MIT" }, + "node_modules/engine.io-client": { + "version": "6.6.8", + "resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-6.6.8.tgz", + "integrity": "sha512-DPN6+2uNi3A2cbSR3gqJepLVOnSQmbaJT4USgU+TgGPczEqLQT0i6t05jHrf4TT6rcxABrGp/1As0FyqwIZlGg==", + "license": "MIT", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.4.1", + "engine.io-parser": "~5.2.1", + "ws": "~8.21.0", + "xmlhttprequest-ssl": "~2.1.1" + } + }, + "node_modules/engine.io-parser": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.3.tgz", + "integrity": "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + } + }, "node_modules/enhanced-resolve": { "version": "5.22.1", "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.22.1.tgz", @@ -5181,6 +5210,34 @@ "url": "https://github.com/sponsors/isaacs" } }, + "node_modules/socket.io-client": { + "version": "4.8.4", + "resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-4.8.4.tgz", + "integrity": "sha512-7wjKAvVXYOJsbmUgkWbnhPD4bFpkqrUR0++XOjpGFmqDqsqV1CI93VTraeExLxpjxEqrWgFoSRZu1ihjLWfkAA==", + "license": "MIT", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.4.1", + "engine.io-client": "~6.6.1", + "socket.io-parser": "~4.2.4" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/socket.io-parser": { + "version": "4.2.7", + "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.7.tgz", + "integrity": "sha512-IH/iSeO9T6gz1KkFleGDWkG9N3dl4jXVYUtMhIqH10Md0ttMer8nUNWiP1DKuNrybD2xBrixLJdCC9J6ECoYkg==", + "license": "MIT", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.4.1" + }, + "engines": { + "node": ">=10.0.0" + } + }, "node_modules/source-map-js": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.3.0.tgz", @@ -5982,7 +6039,6 @@ "version": "8.21.3", "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz", "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==", - "dev": true, "license": "MIT", "engines": { "node": ">=10.0.0" @@ -6017,6 +6073,14 @@ "dev": true, "license": "MIT" }, + "node_modules/xmlhttprequest-ssl": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-2.1.2.tgz", + "integrity": "sha512-TEU+nJVUUnA4CYJFLvK5X9AOeH4KvDvhIfm0vV1GaQRtchnG0hgK5p8hw/xjv8cunWYCsiPCSDzObPyhEwq3KQ==", + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/yallist": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", diff --git a/client/package.json b/client/package.json index c2e7c27..2ad6505 100755 --- a/client/package.json +++ b/client/package.json @@ -18,6 +18,7 @@ "react": "^19.2.6", "react-dom": "^19.2.6", "react-router-dom": "^7.16.0", + "socket.io-client": "^4.8.4", "zustand": "^5.0.14" }, "devDependencies": { diff --git a/client/src/App.tsx b/client/src/App.tsx index 76d1942..1cbfcf8 100755 --- a/client/src/App.tsx +++ b/client/src/App.tsx @@ -1,6 +1,8 @@ import React, { Suspense, lazy, useEffect } from 'react'; import { BrowserRouter as Router, Navigate, Route, Routes, useLocation } from 'react-router-dom'; import { useAuthStore } from './store/authStore'; +import { startNotifications, stopNotifications } from './store/notificationStore'; +import { disconnectSocket } from './lib/socket'; import Navbar from './components/Navbar'; import ServerStatusBanner from './components/ServerStatusBanner'; import Toaster from './components/Toaster'; @@ -19,6 +21,8 @@ const TeamsPage = lazy(() => import('./pages/TeamsPage')); const TeamDetailPage = lazy(() => import('./pages/TeamDetailPage')); const CreateTeamPage = lazy(() => import('./pages/CreateTeamPage')); const PeoplePage = lazy(() => import('./pages/PeoplePage')); +const NotificationsPage = lazy(() => import('./pages/NotificationsPage')); +const AdminPage = lazy(() => import('./pages/AdminPage')); const SessionExpiryRedirect: React.FC = () => { const expiredPath = useAuthStore((state) => state.expiredPath); @@ -33,11 +37,21 @@ const SessionExpiryRedirect: React.FC = () => { const App: React.FC = () => { const fetchCurrentUser = useAuthStore((state) => state.fetchCurrentUser); + const isAuthenticated = useAuthStore((state) => state.isAuthenticated); useEffect(() => { fetchCurrentUser(); }, [fetchCurrentUser]); + useEffect(() => { + if (isAuthenticated) { + startNotifications(); + return; + } + stopNotifications(); + disconnectSocket(); + }, [isAuthenticated]); + return (
@@ -91,6 +105,22 @@ const App: React.FC = () => { } /> + + + + } + /> + + + + } + /> = ({ teamId }) => { + const [messages, setMessages] = useState([]); + const [loading, setLoading] = useState(true); + const [loadingOlder, setLoadingOlder] = useState(false); + const [hasMore, setHasMore] = useState(false); + const [connected, setConnected] = useState(false); + const [socketReady, setSocketReady] = useState(false); + const [draft, setDraft] = useState(''); + const [sending, setSending] = useState(false); + const [error, setError] = useState(''); + const [notice, setNotice] = useState(''); + + const listRef = useRef(null); + const shouldStickToBottom = useRef(true); + + const scrollToBottom = useCallback((behavior: ScrollBehavior = 'auto') => { + const node = listRef.current; + if (!node) return; + node.scrollTo?.({ top: node.scrollHeight, behavior }); + }, []); + + const loadInitial = useCallback(async () => { + setLoading(true); + setError(''); + try { + const response = await api.get(`/teams/${teamId}/messages`, { params: { limit: 50 } }); + setMessages(response.data.data.messages); + setHasMore(Boolean(response.data.data.hasMore)); + shouldStickToBottom.current = true; + } catch (loadError) { + const status = (loadError as { response?: { status?: number } }).response?.status; + setError(status === 403 ? 'Only team members can read this chat.' : 'Could not load this chat.'); + } finally { + setLoading(false); + } + }, [teamId]); + + useEffect(() => { + void loadInitial(); + }, [loadInitial]); + + useEffect(() => { + if (!loading && shouldStickToBottom.current) { + scrollToBottom(); + } + }, [messages, loading, scrollToBottom]); + + useEffect(() => { + let active = true; + let attached: Socket | null = null; + + const emitJoin = (socket: Socket) => { + setConnected(true); + socket.emit('chat:join', { teamId }); + }; + + const onConnect = () => { + if (attached) emitJoin(attached); + }; + const onDisconnect = () => setConnected(false); + + const onNew = (payload: { teamId: string; message: ChatMessage }) => { + if (payload.teamId !== teamId) return; + setMessages((current) => + current.some((message) => message._id === payload.message._id) + ? current + : [...current, payload.message] + ); + }; + + const onError = (payload: { error?: string }) => { + setError(payload.error || 'Could not send that message.'); + }; + + const onRemoved = (payload: { teamId: string; reason?: string }) => { + if (payload.teamId !== teamId) return; + setError(payload.reason || 'This chat is no longer available.'); + setConnected(false); + }; + + connectSocket().then((socket) => { + if (!active) return; + if (!socket) { + setSocketReady(false); + return; + } + attached = socket; + setSocketReady(true); + + socket.on('connect', onConnect); + socket.on('disconnect', onDisconnect); + socket.on('chat:new', onNew); + socket.on('chat:error', onError); + socket.on('chat:removed', onRemoved); + + if (socket.connected) { + emitJoin(socket); + } else { + socket.connect(); + } + }); + + return () => { + active = false; + const socket = attached || getSocket(); + if (socket) { + socket.emit('chat:leave', { teamId }); + socket.off('connect', onConnect); + socket.off('disconnect', onDisconnect); + socket.off('chat:new', onNew); + socket.off('chat:error', onError); + socket.off('chat:removed', onRemoved); + } + }; + }, [teamId]); + + const onScroll = () => { + const node = listRef.current; + if (!node) return; + shouldStickToBottom.current = node.scrollHeight - node.scrollTop - node.clientHeight < 80; + + if (node.scrollTop > 40 || !hasMore || loadingOlder || messages.length === 0) return; + + const previousHeight = node.scrollHeight; + setLoadingOlder(true); + api + .get(`/teams/${teamId}/messages`, { params: { limit: 50, before: messages[0]._id } }) + .then((response) => { + const older = response.data.data.messages as ChatMessage[]; + setHasMore(Boolean(response.data.data.hasMore)); + setMessages((current) => { + const seen = new Set(current.map((message) => message._id)); + return [...older.filter((message) => !seen.has(message._id)), ...current]; + }); + requestAnimationFrame(() => { + if (listRef.current) { + listRef.current.scrollTop = listRef.current.scrollHeight - previousHeight; + } + }); + }) + .catch(() => setNotice('Could not load older messages.')) + .finally(() => setLoadingOlder(false)); + }; + + const send = (event: React.FormEvent) => { + event.preventDefault(); + const content = draft.trim(); + if (!content) { + setError('Message cannot be empty.'); + return; + } + if (content.length > MAX_LENGTH) { + setError(`Messages can be up to ${MAX_LENGTH} characters.`); + return; + } + + const socket = getSocket(); + if (!socket || !connected) { + setError('You are offline. Reconnect before sending a message.'); + return; + } + + setSending(true); + setError(''); + socket.emit('chat:message', { teamId, content }, (response: AckResponse) => { + setSending(false); + if (!response?.ok) { + setError(response?.error || 'Could not send that message.'); + return; + } + setDraft(''); + shouldStickToBottom.current = true; + }); + }; + + return ( +
+
+

+ {!socketReady + ? 'Connecting to chat…' + : connected + ? 'Live chat' + : 'Offline, retrying…'} +

+ + +
+ +
+ {loading ? ( +
+
+
+
+
+ ) : messages.length === 0 ? ( +

+ No messages yet. Say hello to your team. +

+ ) : ( + <> + {loadingOlder &&

Loading older messages…

} + {messages.map((message) => { + const sender = message.sender; + return ( +
+ {sender ? ( + + ) : ( +
+ ); + })} + + )} +
+ + {error && ( +

+ {error} +

+ )} + {notice && ( +

+ {notice} +

+ )} + +
+ +
+