From 1456682805d2b970291938804e70e08077cd4155 Mon Sep 17 00:00:00 2001 From: devnaldo <188571010+devnaldo@users.noreply.github.com> Date: Fri, 4 Dec 2026 07:38:20 +0000 Subject: [PATCH 1/5] feat(schema): add follows, audit log, sync state, and feed fields --- .../20261205000000_features_v3/migration.sql | 83 +++++++++++++++++++ .../migration.sql | 9 ++ backend/prisma/schema.prisma | 57 ++++++++++++- 3 files changed, 148 insertions(+), 1 deletion(-) create mode 100644 backend/prisma/migrations/20261205000000_features_v3/migration.sql create mode 100644 backend/prisma/migrations/20261205001000_backfill_hackathon_location/migration.sql 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 { From 8c9ccbdc8263ca97e3dbc2e28889430d271c04c4 Mon Sep 17 00:00:00 2001 From: devnaldo <188571010+devnaldo@users.noreply.github.com> Date: Fri, 4 Dec 2026 07:38:25 +0000 Subject: [PATCH 2/5] feat(backend): add admin, notifications, chat, follows, skills, and hackathon sync --- backend/package-lock.json | 221 +++++++++- backend/package.json | 4 + backend/src/app.ts | 6 +- backend/src/controllers/adminController.ts | 377 ++++++++++++++++++ backend/src/controllers/authController.ts | 8 +- backend/src/controllers/chatController.ts | 32 ++ backend/src/controllers/followController.ts | 126 ++++++ .../src/controllers/hackathonController.ts | 56 ++- .../src/controllers/notificationController.ts | 102 +++++ backend/src/controllers/requestController.ts | 18 +- backend/src/controllers/teamController.ts | 62 ++- backend/src/controllers/userController.ts | 49 ++- backend/src/middleware/auth.ts | 42 +- backend/src/routes/adminRoutes.ts | 47 +++ backend/src/routes/hackathonRoutes.ts | 4 + backend/src/routes/notificationRoutes.ts | 21 + backend/src/routes/teamRoutes.ts | 7 +- backend/src/routes/userRoutes.ts | 8 +- backend/src/scripts/make-admin.ts | 31 ++ backend/src/seed.ts | 164 +++++++- backend/src/server.ts | 34 +- backend/src/services/chatService.ts | 119 ++++++ backend/src/services/hackathonSyncService.ts | 283 +++++++++++++ backend/src/services/notificationService.ts | 117 ++++++ backend/src/services/realtime.ts | 36 ++ backend/src/socket.ts | 131 ++++++ backend/src/utils/formatters.ts | 45 ++- backend/src/utils/queries.ts | 13 + backend/src/utils/skills.ts | 47 +++ backend/src/validation/schemas.ts | 70 +++- 30 files changed, 2223 insertions(+), 57 deletions(-) create mode 100644 backend/src/controllers/adminController.ts create mode 100644 backend/src/controllers/chatController.ts create mode 100644 backend/src/controllers/followController.ts create mode 100644 backend/src/controllers/notificationController.ts create mode 100644 backend/src/routes/adminRoutes.ts create mode 100644 backend/src/routes/notificationRoutes.ts create mode 100644 backend/src/scripts/make-admin.ts create mode 100644 backend/src/services/chatService.ts create mode 100644 backend/src/services/hackathonSyncService.ts create mode 100644 backend/src/services/notificationService.ts create mode 100644 backend/src/services/realtime.ts create mode 100644 backend/src/socket.ts create mode 100644 backend/src/utils/skills.ts 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/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'], +}); From 5d4f505b86033c6b98e26fa04d26b76ff27b8c57 Mon Sep 17 00:00:00 2001 From: devnaldo <188571010+devnaldo@users.noreply.github.com> Date: Fri, 4 Dec 2026 07:38:29 +0000 Subject: [PATCH 3/5] feat(client): add admin panel, notifications, chat, follows, custom skills, and feed filters --- client/package-lock.json | 66 +- client/package.json | 1 + client/src/App.tsx | 30 + client/src/components/ChatPanel.tsx | 300 +++++++ client/src/components/FollowListModal.tsx | 130 +++ client/src/components/HackathonCard.tsx | 37 +- client/src/components/Navbar.tsx | 19 +- client/src/components/NotificationBell.tsx | 172 ++++ client/src/components/SkillSelector.tsx | 82 +- client/src/lib/socket.ts | 48 ++ client/src/pages/AdminPage.tsx | 941 +++++++++++++++++++++ client/src/pages/HackathonDetailPage.tsx | 17 + client/src/pages/HackathonsPage.tsx | 114 ++- client/src/pages/NotificationsPage.tsx | 159 ++++ client/src/pages/PeoplePage.tsx | 23 +- client/src/pages/TeamDetailPage.tsx | 178 +++- client/src/pages/UserProfilePage.tsx | 67 +- client/src/store/notificationStore.ts | 151 ++++ client/src/types/index.ts | 56 +- client/src/utils/format.ts | 32 + client/src/utils/skills.ts | 46 + 21 files changed, 2627 insertions(+), 42 deletions(-) create mode 100644 client/src/components/ChatPanel.tsx create mode 100644 client/src/components/FollowListModal.tsx create mode 100644 client/src/components/NotificationBell.tsx create mode 100644 client/src/lib/socket.ts create mode 100644 client/src/pages/AdminPage.tsx create mode 100644 client/src/pages/NotificationsPage.tsx create mode 100644 client/src/store/notificationStore.ts create mode 100644 client/src/utils/skills.ts 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} +

+ )} + +
+ +
+