diff --git a/.dockerignore b/.dockerignore deleted file mode 100644 index 79297ed5..00000000 --- a/.dockerignore +++ /dev/null @@ -1,4 +0,0 @@ -Dockerfile -.dockerignore -node_modules -.git diff --git a/.env.example b/.env.example deleted file mode 100644 index 932b9f1e..00000000 --- a/.env.example +++ /dev/null @@ -1,5 +0,0 @@ -PORT=4000 -DATABASE_URL="?schema=prisma" -SHADOW_DATABASE_URL="?schema=shadow" -JWT_SECRET="somesecurestring" -JWT_EXPIRY="24h" \ No newline at end of file diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 56cddc0a..1e2ff854 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,9 +1,5 @@ name: CI on: [push, pull_request] -env: - DATABASE_URL: ${{ secrets.DATABASE_URL }} - JWT_TOKEN: ${{ secrets.JWT_TOKEN }} - JWT_EXPIRY: ${{ secrets.JWT_EXPIRY }} jobs: test: runs-on: ubuntu-latest @@ -14,4 +10,3 @@ jobs: node-version: 'lts/*' - run: npm ci - run: npx eslint src - - run: npx prisma migrate reset --force --skip-seed diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml deleted file mode 100644 index 471052aa..00000000 --- a/.github/workflows/deploy.yml +++ /dev/null @@ -1,21 +0,0 @@ -name: Fly Deploy -on: - push: - branches: - - main -env: - FLY_API_TOKEN: ${{ secrets.FLY_API_TOKEN }} - DATABASE_URL: ${{ secrets.DATABASE_URL }} - JWT_SECRET: ${{ secrets.JWT_SECRET }} - JWT_EXPIRY: ${{ secrets.JWT_EXPIRY }} -jobs: - deploy: - name: Deploy app to fly.io - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - uses: superfly/flyctl-actions/setup-flyctl@master - - run: echo DATABASE_URL=$DATABASE_URL >> .env - - run: echo JWT_SECRET=$JWT_SECRET >> .env - - run: echo JWT_EXPIRY=$JWT_EXPIRY >> .env - - run: flyctl deploy --remote-only diff --git a/.husky/pre-commit b/.husky/pre-commit deleted file mode 100644 index a41979b3..00000000 --- a/.husky/pre-commit +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/sh -. "$(dirname "$0")/_/husky.sh" - -npx eslint src \ No newline at end of file diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index b0c8ba77..00000000 --- a/Dockerfile +++ /dev/null @@ -1,36 +0,0 @@ -FROM debian:bullseye as builder - -ARG NODE_VERSION=18.12.1 - -RUN apt-get update; apt install -y curl -RUN curl https://get.volta.sh | bash -ENV VOLTA_HOME /root/.volta -ENV PATH /root/.volta/bin:$PATH -RUN volta install node@${NODE_VERSION} - -####################################################################### - -RUN mkdir /app -WORKDIR /app - -# NPM will not install any package listed in "devDependencies" when NODE_ENV is set to "production", -# to install all modules: "npm install --production=false". -# Ref: https://docs.npmjs.com/cli/v9/commands/npm-install#description - -ENV NODE_ENV production - -COPY . . - -RUN npm install -FROM debian:bullseye - -LABEL fly_launch_runtime="nodejs" - -COPY --from=builder /root/.volta /root/.volta -COPY --from=builder /app /app - -WORKDIR /app -ENV NODE_ENV production -ENV PATH /root/.volta/bin:$PATH - -CMD [ "npm", "run", "start" ] diff --git a/docs/openapi.yml b/docs/openapi.yml index 5f2a05f2..c9e16a4c 100644 --- a/docs/openapi.yml +++ b/docs/openapi.yml @@ -2,10 +2,10 @@ openapi: 3.0.3 info: title: Team Dev Server API description: |- - version: 1.0 + version: '1.0' servers: - - url: http://localhost:4000/ + - url: 'http://localhost:4000/' tags: - name: user - name: post @@ -32,6 +32,12 @@ paths: application/json: schema: $ref: '#/components/schemas/CreatedUser' + '400': + description: Invalid email/password supplied + content: + application/json: + schema: + $ref: '#/components/schemas/Error' get: tags: - user @@ -85,10 +91,8 @@ paths: application/json: schema: $ref: '#/components/schemas/loginRes' - '400': description: Invalid username/password supplied - /users/{id}: get: tags: @@ -117,7 +121,6 @@ paths: type: string data: $ref: '#/components/schemas/User' - '400': description: fail content: @@ -164,6 +167,12 @@ paths: application/json: schema: $ref: '#/components/schemas/Error' + '400': + description: Invalid email/password/profile information supplied + content: + application/json: + schema: + $ref: '#/components/schemas/Error' /posts: post: tags: @@ -189,8 +198,14 @@ paths: application/json: schema: $ref: '#/components/schemas/Post' - 400: - description: fail + 401: + description: Unauthorised + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '500': + description: Internal server error content: application/json: schema: @@ -211,7 +226,140 @@ paths: schema: $ref: '#/components/schemas/Posts' '401': - description: fail + description: Unauthorised + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '500': + description: Internal server error + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /posts/{id}: + get: + tags: + - post + summary: Get a post by id + description: get a post + operationId: getPostById + security: + - bearerAuth: [] + parameters: + - name: id + in: path + description: 'The post id that needs to be updated' + required: true + schema: + type: integer + responses: + '200': + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Posts' + '401': + description: Unauthorised + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '404': + description: Not Found + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '500': + description: Server error + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + patch: + tags: + - post + summary: Patch a post by id + description: patch a post + operationId: updatePostById + security: + - bearerAuth: [] + parameters: + - name: id + in: path + description: 'The post id that needs to be updated' + required: true + schema: + type: integer + requestBody: + description: The post description + content: + application/json: + schema: + $ref: '#/components/schemas/UpdatePost' + responses: + '200': + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Posts' + '401': + description: Unauthorised + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '404': + description: Not Found + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '500': + description: Server error + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + delete: + tags: + - post + summary: Delete a post by id + description: delete a post + operationId: deletePostById + security: + - bearerAuth: [] + parameters: + - name: id + in: path + description: 'The post id that needs to be updated' + required: true + schema: + type: integer + responses: + '200': + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Posts' + '401': + description: Unauthorised + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '404': + description: Not Found + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '500': + description: Server error content: application/json: schema: @@ -265,6 +413,11 @@ paths: operationId: createCohort security: - bearerAuth: [] + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/UpdateCohort' responses: 201: description: success @@ -285,6 +438,276 @@ paths: application/json: schema: $ref: '#/components/schemas/Error' + get: + tags: + - cohort + summary: Get all cohorts + operationId: getAllCohorts + security: + - bearerAuth: [] + responses: + '201': + description: success + content: + application/json: + schema: + type: object + properties: + status: + type: string + data: + properties: + cohort: + $ref: '#/components/schemas/Cohort' + '401': + description: fail + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '500': + description: Server error + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /cohorts/{id}: + get: + tags: + - cohort + summary: Get a cohort by id + operationId: getCohortById + security: + - bearerAuth: [] + parameters: + - name: id + in: path + description: 'The cohort id' + required: true + schema: + type: integer + responses: + '201': + description: success + content: + application/json: + schema: + type: object + properties: + status: + type: string + data: + properties: + cohort: + $ref: '#/components/schemas/Cohort' + '401': + description: Unautorized + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '404': + description: Not Found + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '500': + description: Server error + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + patch: + tags: + - cohort + summary: Patch a cohort by id + description: This can only be done by the logged in user with role TEACHER. + operationId: updateCohortById + security: + - bearerAuth: [] + parameters: + - name: id + in: path + required: true + schema: + type: integer + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/UpdateCohort' + responses: + '200': + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Posts' + '401': + description: Unauthorised + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '404': + description: Not Found + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '500': + description: Server error + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + delete: + tags: + - cohort + summary: Delete a cohort by id + description: This can only be done by the logged in user with role TEACHER. + operationId: deleteCohortById + security: + - bearerAuth: [] + parameters: + - name: id + in: path + required: true + schema: + type: integer + responses: + '200': + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Posts' + '401': + description: Unauthorised + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '404': + description: Not Found + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '500': + description: Server error + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + + /comments: + post: + tags: + - comment + summary: Create a comment + description: Create a new comment on a post + operationId: createComment + security: + - bearerAuth: [] + requestBody: + description: Comment details + content: + application/json: + schema: + $ref: '#/components/schemas/CreateComment' + responses: + '201': + description: Created + content: + application/json: + schema: + $ref: '#/components/schemas/Comment' + '400': + description: Invalid input + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /comments/{commentId}: + patch: + tags: + - comment + summary: Update a comment + description: Update an existing comment + operationId: updateComment + security: + - bearerAuth: [] + parameters: + - name: commentId + in: path + description: The ID of the comment to update + required: true + schema: + type: integer + requestBody: + description: Updated comment details + required: true + content: + application/json: + schema: + type: object + properties: + content: + type: string + userId: + type: integer + required: + - content + - userId + responses: + '200': + description: Updated + content: + application/json: + schema: + $ref: '#/components/schemas/Comment' + '400': + description: Invalid input + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '404': + description: Comment not found + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + delete: + tags: + - comment + summary: Delete a comment + description: Delete an existing comment + operationId: deleteComment + security: + - bearerAuth: [] + parameters: + - name: commentId + in: path + description: The ID of the comment to delete + required: true + schema: + type: integer + responses: + '200': + description: Deleted + content: + application/json: + schema: + $ref: '#/components/schemas/Success' + '404': + description: Comment not found + content: + application/json: + schema: + $ref: '#/components/schemas/Error' components: securitySchemes: @@ -312,12 +735,30 @@ components: properties: id: type: integer + cohortName: + type: string createdAt: type: string - format: string + format: date-time updatedAt: type: string - format: string + format: date-time + users: + type: array + items: + $ref: '#/components/schemas/User' + + UpdateCohort: + type: object + properties: + cohortName: + type: string + startDate: + type: string + format: date-time + endDate: + type: string + format: date-time AllUsers: type: object @@ -351,6 +792,20 @@ components: type: string githubUrl: type: string + username: + type: string + mobile: + type: string + specialism: + type: string + startDate: + type: string + format: date-time + endDate: + type: string + format: date-time + profileImage: + type: string CreateUser: type: object @@ -365,8 +820,22 @@ components: type: string githubUrl: type: string + username: + type: string + mobile: + type: string + specialism: + type: string + startDate: + type: string + format: date-time + endDate: + type: string + format: date-time password: type: string + profileImage: + type: string UpdateUser: type: object @@ -387,6 +856,20 @@ components: type: string githubUrl: type: string + username: + type: string + mobile: + type: string + specialism: + type: string + startDate: + type: string + format: date-time + endDate: + type: string + format: date-time + profileImage: + type: string Posts: type: object @@ -407,10 +890,10 @@ components: type: string createdAt: type: string - format: string + format: date-time updatedAt: type: string - format: string + format: date-time author: type: object properties: @@ -428,9 +911,27 @@ components: type: string githubUrl: type: string - profileImageUrl: + username: + type: string + mobile: + type: string + specialism: type: string - + startDate: + type: string + format: date-time + endDate: + type: string + format: date-time + profileImage: + type: string + + UpdatePost: + type: object + properties: + content: + type: string + CreatedUser: type: object properties: @@ -457,6 +958,21 @@ components: type: string githubUrl: type: string + username: + type: string + mobile: + type: string + specialism: + type: string + startDate: + type: string + format: date-time + endDate: + type: string + format: date-time + profileImage: + type: string + login: type: object properties: @@ -492,6 +1008,21 @@ components: type: string githubUrl: type: string + username: + type: string + mobile: + type: string + specialism: + type: string + startDate: + type: string + format: date-time + endDate: + type: string + format: date-time + profileImage: + type: string + Error: type: object properties: @@ -535,3 +1066,38 @@ components: type: integer content: type: string + Comment: + type: object + properties: + id: + type: integer + content: + type: string + userId: + type: integer + postId: + type: integer + CreateComment: + type: object + properties: + content: + type: string + postId: + type: integer + userId: + type: integer + UpdateComment: + type: object + properties: + content: + type: string + userId: + type: integer + required: + - content + - userId + Success: + type: object + properties: + message: + type: string \ No newline at end of file diff --git a/fly.toml b/fly.toml deleted file mode 100644 index eac058e7..00000000 --- a/fly.toml +++ /dev/null @@ -1,42 +0,0 @@ -# fly.toml file generated for team-dev-backend-api on 2022-11-30T11:30:34Z - -app = "team-dev-backend-api" -kill_signal = "SIGINT" -kill_timeout = 5 -processes = [] - -[env] - PORT = "8080" - -[experimental] - allowed_public_ports = [] - auto_rollback = true - -[deploy] - release_command = "npx prisma migrate deploy" - -[[services]] - http_checks = [] - internal_port = 8080 - processes = ["app"] - protocol = "tcp" - script_checks = [] - [services.concurrency] - hard_limit = 25 - soft_limit = 20 - type = "connections" - - [[services.ports]] - force_https = true - handlers = ["http"] - port = 80 - - [[services.ports]] - handlers = ["tls", "http"] - port = 443 - - [[services.tcp_checks]] - grace_period = "1s" - interval = "15s" - restart_limit = 0 - timeout = "2s" diff --git a/package.json b/package.json index b5997d22..3021b44f 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,6 @@ "scripts": { "start": "node src/index.js", "dev": "nodemon src/index.js", - "prepare": "husky install", "db-reset": "prisma migrate reset", "lint": "eslint .", "lint:fix": "eslint --fix", @@ -36,7 +35,6 @@ "eslint-plugin-node": "^11.1.0", "eslint-plugin-prettier": "^4.0.0", "eslint-plugin-promise": "^5.1.0", - "husky": "^7.0.4", "nodemon": "^2.0.15", "prettier": "^2.6.2", "prisma": "^3.12.0" diff --git a/prisma/migrations/20241029082651_add_profile_fields/migration.sql b/prisma/migrations/20241029082651_add_profile_fields/migration.sql new file mode 100644 index 00000000..4ca11f21 --- /dev/null +++ b/prisma/migrations/20241029082651_add_profile_fields/migration.sql @@ -0,0 +1,6 @@ +-- AlterTable +ALTER TABLE "Profile" ADD COLUMN "endDate" TIMESTAMP(3), +ADD COLUMN "mobile" TEXT NOT NULL DEFAULT E'', +ADD COLUMN "specialism" TEXT NOT NULL DEFAULT E'', +ADD COLUMN "startDate" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, +ADD COLUMN "username" TEXT NOT NULL DEFAULT E''; diff --git a/prisma/migrations/20241029090014_add_profile_image/migration.sql b/prisma/migrations/20241029090014_add_profile_image/migration.sql new file mode 100644 index 00000000..b47489b4 --- /dev/null +++ b/prisma/migrations/20241029090014_add_profile_image/migration.sql @@ -0,0 +1,2 @@ +-- AlterTable +ALTER TABLE "Profile" ADD COLUMN "profileImage" TEXT; diff --git a/prisma/migrations/20241029124851_added_comments_table/migration.sql b/prisma/migrations/20241029124851_added_comments_table/migration.sql new file mode 100644 index 00000000..1c5829f7 --- /dev/null +++ b/prisma/migrations/20241029124851_added_comments_table/migration.sql @@ -0,0 +1,15 @@ +-- CreateTable +CREATE TABLE "Comment" ( + "id" SERIAL NOT NULL, + "content" TEXT NOT NULL, + "userId" INTEGER NOT NULL, + "postId" INTEGER NOT NULL, + + CONSTRAINT "Comment_pkey" PRIMARY KEY ("id") +); + +-- AddForeignKey +ALTER TABLE "Comment" ADD CONSTRAINT "Comment_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Comment" ADD CONSTRAINT "Comment_postId_fkey" FOREIGN KEY ("postId") REFERENCES "Post"("id") ON DELETE RESTRICT ON UPDATE CASCADE; diff --git a/prisma/migrations/20241030083020_new_user_values/migration.sql b/prisma/migrations/20241030083020_new_user_values/migration.sql new file mode 100644 index 00000000..af5102c8 --- /dev/null +++ b/prisma/migrations/20241030083020_new_user_values/migration.sql @@ -0,0 +1 @@ +-- This is an empty migration. \ No newline at end of file diff --git a/prisma/migrations/20241030125841_add_created_updated_at_columns_to_post/migration.sql b/prisma/migrations/20241030125841_add_created_updated_at_columns_to_post/migration.sql new file mode 100644 index 00000000..d19aa2d3 --- /dev/null +++ b/prisma/migrations/20241030125841_add_created_updated_at_columns_to_post/migration.sql @@ -0,0 +1,3 @@ +-- AlterTable +ALTER TABLE "Post" ADD COLUMN "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, +ADD COLUMN "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP; diff --git a/prisma/migrations/20241031081436_add_cohort_and_seeding/migration.sql b/prisma/migrations/20241031081436_add_cohort_and_seeding/migration.sql new file mode 100644 index 00000000..4f3056d0 --- /dev/null +++ b/prisma/migrations/20241031081436_add_cohort_and_seeding/migration.sql @@ -0,0 +1,10 @@ +/* + Warnings: + + - Added the required column `cohortName` to the `Cohort` table without a default value. This is not possible if the table is not empty. + +*/ +-- AlterTable +ALTER TABLE "Cohort" ADD COLUMN "cohortName" TEXT NOT NULL, +ADD COLUMN "endDate" TIMESTAMP(3), +ADD COLUMN "startDate" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 72ec5632..e8977058 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -26,6 +26,7 @@ model User { cohort Cohort? @relation(fields: [cohortId], references: [id]) posts Post[] deliveryLogs DeliveryLog[] + comments Comment[] } model Profile { @@ -36,12 +37,21 @@ model Profile { lastName String bio String? githubUrl String? + username String @default("") + mobile String @default("") + specialism String @default("") + startDate DateTime @default(now()) + endDate DateTime? + profileImage String? } model Cohort { id Int @id @default(autoincrement()) - users User[] - deliveryLogs DeliveryLog[] + cohortName String + startDate DateTime @default(now()) + endDate DateTime? + students User[] + deliveryLogs DeliveryLog[] } model Post { @@ -49,6 +59,19 @@ model Post { content String userId Int user User @relation(fields: [userId], references: [id]) + comments Comment[] + createdAt DateTime @default(now()) + updatedAt DateTime @default(now()) +} + +model Comment { + id Int @id @default(autoincrement()) + content String + userId Int + user User @relation(fields: [userId], references: [id]) + postId Int + post Post @relation(fields: [postId], references: [id]) + } model DeliveryLog { diff --git a/prisma/seed.js b/prisma/seed.js index 21684795..26e90042 100644 --- a/prisma/seed.js +++ b/prisma/seed.js @@ -3,30 +3,50 @@ import bcrypt from 'bcrypt' const prisma = new PrismaClient() async function seed() { - const cohort = await createCohort() + const cohort = await createCohort( + 'Boolean 2024', + new Date('2024-08-08'), + new Date('2024-11-01') + ) const student = await createUser( 'student@test.com', - 'Testpassword1!', cohort.id, 'Joe', 'Bloggs', 'Hello, world!', - 'student1' + 'student1@github.com', + 'student1', + '123-456-7890', // mobile + 'Software Engineering', // specialism + new Date('2023-01-01'), // startDate + new Date('2023-12-31'), + null, + 'STUDENT', + 'Testpassword1!' ) const teacher = await createUser( 'teacher@test.com', - 'Testpassword1!', null, 'Rick', 'Sanchez', 'Hello there!', + 'teacher1@git.com', 'teacher1', - 'TEACHER' + '987-654-3210', + 'Teaching', + new Date('2022-01-01'), + new Date('2022-12-31'), + null, + 'TEACHER', + 'Testpassword1!' ) - await createPost(student.id, 'My first post!') - await createPost(teacher.id, 'Hello, students') + const post1 = await createPost(student.id, 'My first post!') + const post2 = await createPost(teacher.id, 'Hello, students') + await createComment(student.id, post1.id, 'Nice post!') + await createComment(teacher.id, post1.id, 'Thank you!') + await createComment(student.id, post2.id, 'Hello, teacher!') process.exit(0) } @@ -47,25 +67,51 @@ async function createPost(userId, content) { return post } -async function createCohort() { - const cohort = await prisma.cohort.create({ - data: {} +async function createComment(userId, postId, content) { + const comment = await prisma.comment.create({ + data: { + userId, + postId, + content + }, + include: { + user: true, + post: true + } }) - console.info('Cohort created', cohort) + console.info('Comment created', comment) + return comment +} + +async function createCohort(cohortName, startDate, endDate) { + const cohort = await prisma.cohort.create({ + data: { + cohortName, + startDate, + endDate + } + }) + console.info('Cohort created', cohort) return cohort } async function createUser( email, - password, cohortId, firstName, lastName, bio, githubUrl, - role = 'STUDENT' + username, + mobile, + specialism, + startDate, + endDate, + profileImage, + role = 'STUDENT', + password ) { const user = await prisma.user.create({ data: { @@ -78,7 +124,13 @@ async function createUser( firstName, lastName, bio, - githubUrl + githubUrl, + profileImage, + username, + mobile, + specialism, + startDate: new Date(startDate), + endDate: new Date(endDate) } } }, diff --git a/src/controllers/cohort.js b/src/controllers/cohort.js index cc39365b..3435a989 100644 --- a/src/controllers/cohort.js +++ b/src/controllers/cohort.js @@ -1,12 +1,67 @@ -import { createCohort } from '../domain/cohort.js' -import { sendDataResponse, sendMessageResponse } from '../utils/responses.js' - -export const create = async (req, res) => { - try { - const createdCohort = await createCohort() - - return sendDataResponse(res, 201, createdCohort) - } catch (e) { - return sendMessageResponse(res, 500, 'Unable to create cohort') - } -} +import { sendDataResponse, sendMessageResponse } from '../utils/responses.js' +import Cohort from '../domain/cohort.js' + +export const create = async (req, res) => { + const cohort = await Cohort.fromJson(req.body) + try { + const createdCohort = await cohort.save() + + return sendDataResponse(res, 201, { cohort: createdCohort }) + } catch (e) { + return sendMessageResponse(res, 500, `Unable to create cohort ${e}`) + } +} + +export const getAll = async (req, res) => { + const cohorts = await Cohort.getAllCohorts() + if (!cohorts) { + return sendMessageResponse(res, 500, 'Internal server error') + } + + return sendDataResponse(res, 200, cohorts) +} + +export const getById = async (req, res) => { + const { id } = req.params + const cohort = await Cohort.getCohortById(Number(id)) + + if (!cohort) { + return sendMessageResponse(res, 404, `Cohort with id ${id} not found`) + } + + return sendDataResponse(res, 200, cohort) +} + +export const updateById = async (req, res) => { + const { id } = req.params + const { cohortName, startDate, endDate } = req.body + + try { + const cohort = await Cohort.getCohortById(Number(id)) + if (cohort) { + const content = { cohortName, startDate, endDate } + const updatedCohort = await Cohort.updateById(Number(id), content) + return sendDataResponse(res, 200, updatedCohort.toJSON()) + } else { + return sendMessageResponse(res, 404, `Cohort with id ${id} not found`) + } + } catch (error) { + return sendDataResponse(res, 500, `Internal server error ${error}`) + } +} + +export const deleteById = async (req, res) => { + const { id } = req.params + + try { + const cohort = await Cohort.getCohortById(Number(id)) + if (cohort) { + const deletedCohort = await Cohort.deleteById(Number(id)) + return sendDataResponse(res, 200, deletedCohort) + } else { + return sendMessageResponse(res, 404, `Cohort with id ${id} not found`) + } + } catch (error) { + return sendMessageResponse(res, 500, 'Internal server error') + } +} diff --git a/src/controllers/comment.js b/src/controllers/comment.js new file mode 100644 index 00000000..d12b7079 --- /dev/null +++ b/src/controllers/comment.js @@ -0,0 +1,84 @@ +import { sendDataResponse, sendMessageResponse } from '../utils/responses.js' +import Comment from '../domain/comment.js' +import User from '../domain/user.js' + +// Create a new comment +export const create = async (req, res) => { + const { content, postId } = req.body + const user = await User.findById(req.user.id) + + if (!content || !postId) { + return sendDataResponse(res, 400, { + error: 'Must provide content, postId, and userId' + }) + } + + try { + const createdComment = await Comment.createComment(content, user, postId) + if (!createdComment) { + return sendDataResponse(res, 404, { id: 'Comment not found' }) + } + + return sendDataResponse(res, 201, createdComment) + } catch (error) { + console.error('Error creating comment:', error) + return sendMessageResponse(res, 500, 'Unable to create comment') + } +} + +// Update an existing comment +export const update = async (req, res) => { + const { content, userId } = req.body + const { id } = req.params + const commentIdInt = parseInt(id, 10) + + if (!content) { + return sendDataResponse(res, 400, { error: 'Must provide content' }) + } + + if (isNaN(commentIdInt)) { + return sendDataResponse(res, 400, { error: 'Invalid comment ID' }) + } + + try { + const comment = await Comment.getCommentById(commentIdInt) + + if (!comment) { + return sendDataResponse(res, 404, { error: 'Comment not found' }) + } + + const updatedComment = await Comment.updateContentById( + commentIdInt, + content, + userId + ) + return sendDataResponse(res, 200, { comment: updatedComment }) + } catch (error) { + console.error('Error updating comment:', error) + return sendDataResponse(res, 500, { error: 'Internal Server Error' }) + } +} + +// Delete an existing comment +export const remove = async (req, res) => { + const { id } = req.params + const commentIdInt = parseInt(id, 10) + + if (isNaN(commentIdInt)) { + return sendDataResponse(res, 400, { error: 'Invalid comment ID' }) + } + + try { + const comment = await Comment.getCommentById(commentIdInt) + + if (!comment) { + return res.status(404).json({ error: 'Comment not found' }) + } + + await Comment.deleteCommentById(commentIdInt) + return res.status(200).json({ message: 'Comment deleted successfully' }) + } catch (error) { + console.error('Error deleting comment:', error) + return res.status(500).json({ error: 'Internal Server Error' }) + } +} diff --git a/src/controllers/post.js b/src/controllers/post.js index 7b168039..4500634e 100644 --- a/src/controllers/post.js +++ b/src/controllers/post.js @@ -1,28 +1,89 @@ import { sendDataResponse } from '../utils/responses.js' +import Post from '../domain/post.js' +import User from '../domain/user.js' export const create = async (req, res) => { const { content } = req.body + const user = await User.findById(req.user.id) if (!content) { return sendDataResponse(res, 400, { content: 'Must provide content' }) } - return sendDataResponse(res, 201, { post: { id: 1, content } }) + try { + const post = await Post.createPost(content, user) + if (post) { + return sendDataResponse(res, 201, { post }) + } else { + return sendDataResponse(res, 500, { content: 'Failed to create post' }) + } + } catch (error) { + return sendDataResponse(res, 500, { content: 'Internal server error' }) + } } export const getAll = async (req, res) => { - return sendDataResponse(res, 200, { - posts: [ - { - id: 1, - content: 'Hello world!', - author: { ...req.user } - }, - { - id: 2, - content: 'Hello from the void!', - author: { ...req.user } - } - ] - }) + const postsUnformatted = await Post.getAllPosts() + if (!postsUnformatted) { + return sendDataResponse(res, 500, { + content: 'Internal server error' + }) + } + + const posts = postsUnformatted.map((post) => post.toJSON()) + return sendDataResponse(res, 200, { posts }) +} + +export const getById = async (req, res) => { + const { id } = req.params + const post = await Post.getPostById(Number(id)) + + if (!post) { + return sendDataResponse(res, 404, { + content: `Post with id ${id} not found` + }) + } + + return sendDataResponse(res, 200, { post: post.toJSON() }) +} + +export const updateById = async (req, res) => { + const { id } = req.params + const { content } = req.body + + try { + const post = await Post.getPostById(Number(id)) + if (post) { + const updatedPost = await Post.updateContentById(Number(id), content) + return sendDataResponse(res, 200, { post: updatedPost }) + } else { + return sendDataResponse(res, 404, { + content: `Post with id ${id} not found` + }) + } + } catch (error) { + return sendDataResponse(res, 500, { + content: 'Internal server error' + }) + } +} + +export const deleteById = async (req, res) => { + const { id } = req.params + + try { + const post = await Post.getPostById(Number(id)) + if (post) { + const deletedPost = await Post.deletePostById(Number(id)) + return sendDataResponse(res, 200, { post: deletedPost }) + } else { + return sendDataResponse(res, 404, { + content: `Post with id ${id} not found` + }) + } + } catch (error) { + return sendDataResponse(res, 500, { + content: 'Internal server error' + }) + } } diff --git a/src/controllers/user.js b/src/controllers/user.js index 40ff0f1c..72421118 100644 --- a/src/controllers/user.js +++ b/src/controllers/user.js @@ -1,10 +1,11 @@ import User from '../domain/user.js' import { sendDataResponse, sendMessageResponse } from '../utils/responses.js' +/* CREATES A NEW USER */ export const create = async (req, res) => { - const userToCreate = await User.fromJson(req.body) - try { + const userToCreate = await User.fromJson(req.body) + const existingUser = await User.findByEmail(userToCreate.email) if (existingUser) { @@ -15,10 +16,11 @@ export const create = async (req, res) => { return sendDataResponse(res, 201, createdUser) } catch (error) { + console.error('Error creating user:', error) return sendMessageResponse(res, 500, 'Unable to create new user') } } - +/* GETS A USER BY ID */ export const getById = async (req, res) => { const id = parseInt(req.params.id) @@ -35,6 +37,7 @@ export const getById = async (req, res) => { } } +/* GETS ALL USERS */ export const getAll = async (req, res) => { // eslint-disable-next-line camelcase const { first_name: firstName } = req.query @@ -55,13 +58,30 @@ export const getAll = async (req, res) => { return sendDataResponse(res, 200, { users: formattedUsers }) } +/* Updates a user by ID */ export const updateById = async (req, res) => { - const { cohort_id: cohortId } = req.body + const id = parseInt(req.params.id) + const userToUpdate = await User.fromJson(req.body) - if (!cohortId) { - return sendDataResponse(res, 400, { cohort_id: 'Cohort ID is required' }) - } + // Add id, cohortId and role (could be done in the domain) + userToUpdate.id = id + userToUpdate.cohortId = req.body.cohortId + userToUpdate.role = req.body.role + + console.log(userToUpdate) - return sendDataResponse(res, 201, { user: { cohort_id: cohortId } }) + try { + if (!userToUpdate.cohortId) { + return sendDataResponse(res, 400, { cohort_id: 'Cohort ID is required' }) + } + const updatedUser = await userToUpdate.update() + + return sendDataResponse(res, 201, updatedUser) + } catch (error) { + console.log(error) + return sendMessageResponse(res, 500, 'Unable to update user') + } } + +/* Test Commit statement */ diff --git a/src/domain/cohort.js b/src/domain/cohort.js index abdda73b..9380def1 100644 --- a/src/domain/cohort.js +++ b/src/domain/cohort.js @@ -1,27 +1,114 @@ import dbClient from '../utils/dbClient.js' +import User from './user.js' -/** - * Create a new Cohort in the database - * @returns {Cohort} - */ -export async function createCohort() { - const createdCohort = await dbClient.cohort.create({ - data: {} - }) +export default class Cohort { + static fromDb(cohort) { + return new Cohort( + cohort.id, + cohort.cohortName, + cohort.startDate, + cohort.endDate, + cohort.students + ? cohort.students.map((student) => User.fromDb(student)) + : [] + ) + } - return new Cohort(createdCohort.id) -} + static async fromJson(json) { + const { cohortId, cohortName, startDate, endDate, students } = json + return new Cohort( + cohortId, + cohortName, + startDate, + endDate, + students ? students.map((student) => User.fromJson(student)) : [] + ) + } -export class Cohort { - constructor(id = null) { + constructor(id, cohortName, startDate, endDate = null, students = []) { this.id = id + this.cohortName = cohortName + this.startDate = startDate + this.endDate = endDate + this.students = students } toJSON() { return { cohort: { - id: this.id + id: this.id, + cohortName: this.cohortName, + startDate: this.startDate, + endDate: this.endDate, + students: this.students.map((student) => student.toJSON()) } } } + + async save() { + const data = { + cohortName: this.cohortName, + startDate: this.startDate, + endDate: this.endDate !== undefined ? this.endDate : null + } + + const createdCohort = await dbClient.cohort.create({ data }) + return Cohort.fromDb(createdCohort) + } + + async update() { + const updatedCohort = await dbClient.cohort.update({ + where: { + id: this.id + }, + data: { + cohortName: this.cohortName, + startDate: this.startDate, + endDate: this.endDate + } + }) + + return Cohort.fromDb(updatedCohort) + } + + static async getAllCohorts() { + const cohorts = await dbClient.cohort.findMany({ + include: { + students: true + } + }) + return cohorts.map((cohort) => Cohort.fromDb(cohort)) + } + + static async getCohortById(id) { + const cohort = await dbClient.cohort.findUnique({ + where: { id }, + include: { + students: true + } + }) + return cohort ? Cohort.fromDb(cohort) : null + } + + static async updateById(id, cohort) { + const data = {} + if (cohort.cohortName !== undefined) data.cohortName = cohort.cohortName + if (cohort.startDate !== undefined) data.startDate = cohort.startDate + if (cohort.endDate !== undefined) data.endDate = cohort.endDate + + return this.fromDb( + await dbClient.cohort.update({ + where: { id }, + data + }) + ) + } + + static async deleteById(id) { + return this.fromDb( + await dbClient.cohort.delete({ + where: { id } + }) + ) + } } diff --git a/src/domain/comment.js b/src/domain/comment.js new file mode 100644 index 00000000..171005a3 --- /dev/null +++ b/src/domain/comment.js @@ -0,0 +1,165 @@ +import dbClient from '../utils/dbClient.js' + +export default class Comment { + /** + * Converts a database comment object to a Comment instance + * @param { { id: int, content: string, userId: int, postId: int, user: object, post: object } } comment + * @returns {Comment} + */ + static fromDb(comment) { + return new Comment( + comment.id, + comment.content, + comment.userId, + comment.postId, + comment.post + ) + } + + constructor({ + id = null, + content, + user = null, + post = null, + userId, + postId + }) { + this.id = id + this.content = content + this.userId = userId + this.user = user + this.post = post + this.postId = postId + } + + toJSON() { + return { + comment: { + id: this.id, + content: this.content, + userId: this.userId, + postId: this.postId, + user: this.user, + post: this.post + } + } + } + + /** + * Saves the comment to the database + * @param {string} content + * @param {object} user + * @param {int} postId + * @returns {Comment} + */ + static async createComment(content, user, postId) { + return dbClient.Comment.create({ + data: { + content, + userId: user.id, + postId + } + }) + } + + /** + * Gets a comment by its ID + * @param {int} id + * @returns {Comment} + */ + static async getCommentById(id) { + const comment = await dbClient.comment.findUnique({ + where: { id }, + include: { + user: true, + post: true + } + }) + return comment + ? new Comment({ + id: comment.id, + content: comment.content, + userId: comment.userId, + postId: comment.postId + }) + : null + } + + /** + * Updates the content of a comment by its ID + * @param {int} id + * @param {string} content + * @returns {Comment} + */ + static async updateContentById(id, content, userId) { + return dbClient.comment.update({ + where: { id }, + data: { content, userId } + }) + } + + /** + * Deletes a comment by its ID + * @param {int} id + * @returns {Comment} + */ + static async deleteCommentById(id) { + return dbClient.comment.delete({ + where: { id } + }) + } + + /** + * Finds a comment by its ID + * @param {int} id + * @returns {Comment} + */ + static async findById(id) { + console.log(id) + if (!id || isNaN(id)) { + throw new Error('Invalid comment ID') + } + const comment = await dbClient.comment.findUnique({ + where: { id: parseInt(id, 10) }, + include: { + user: { + include: { profile: true } + }, + post: true + } + }) + + return comment + ? new Comment({ + id: comment.id, + content: comment.content, + userId: comment.userId, + postId: comment.postId, + user: comment.user, + post: comment.post + }) + : null + } + + /** + * Finds comments by post ID + * @param {int} postId + * @returns {Comment[]} + */ + static async findByPostId(postId) { + try { + const foundComments = await dbClient.comment.findMany({ + where: { postId }, + include: { + user: true, + post: true + } + }) + + return foundComments.map((comment) => Comment.fromDb(comment)) + } catch (error) { + console.error('Error finding comments by post ID:', error) + throw new Error('Error finding comments by post ID') + } + } +} diff --git a/src/domain/post.js b/src/domain/post.js new file mode 100644 index 00000000..53a2016d --- /dev/null +++ b/src/domain/post.js @@ -0,0 +1,110 @@ +import dbClient from '../utils/dbClient.js' + +export default class Post { + constructor( + id = null, + content = '', + user = null, + createdAt = null, + updatedAt = null, + comments = [] + ) { + this.id = id + this.content = content + this.user = user + this.createdAt = createdAt + this.updatedAt = updatedAt + this.comments = comments + } + + toJSON() { + return { + id: this.id, + content: this.content, + createdAt: this.createdAt, + updatedAt: this.updatedAt, + author: { + id: this.user.id, + cohortId: this.user.cohortId, + role: this.user.role, + firstName: this.user.profile.firstName, + lastName: this.user.profile.lastName, + bio: this.user.profile.bio, + githubUrl: this.user.profile.githubUrl, + username: this.user.profile.username, + mobile: this.user.profile.mobile, + specialism: this.user.profile.specialism, + startDate: this.user.profile.startDate, + endDate: this.user.profile.endDate, + profileImage: this.user.profile.profileImage + }, + comments: this.comments.map((comment) => ({ + id: comment.id, + content: comment.content + })) + } + } + + static async createPost(content, user) { + return dbClient.post.create({ + data: { content: content, userId: user.id } + }) + } + + static async getAllPosts() { + const posts = await dbClient.post.findMany({ + include: { + user: { + include: { profile: true } + }, + comments: true + } + }) + return posts.map( + (post) => + new Post( + post.id, + post.content, + post.user, + post.createdAt, + post.updatedAt, + post.comments + ) + ) + } + + static async getPostById(id) { + const post = await dbClient.post.findUnique({ + where: { id }, + include: { + user: { + include: { profile: true } + }, + comments: true + } + }) + return post + ? new Post( + post.id, + post.content, + post.user, + post.createdAt, + post.updatedAt, + post.comments + ) + : null + } + + static async updateContentById(id, content) { + return dbClient.post.update({ + where: { id: id }, + data: { content: content } + }) + } + + static async deletePostById(id) { + return dbClient.post.delete({ + where: { id: id } + }) + } +} diff --git a/src/domain/testComment.js b/src/domain/testComment.js new file mode 100644 index 00000000..b0540746 --- /dev/null +++ b/src/domain/testComment.js @@ -0,0 +1,16 @@ +const Comment = require('./path/to/comment') // Adjust the path as necessary + +async function testComment() { + // Create a new comment instance + const comment = new Comment({ + id: 1, + content: 'Initial content', + userId: 1, + postId: 1 + }) + + // Update the comment content + await comment.update('Updated content') +} + +testComment().catch(console.error) diff --git a/src/domain/user.js b/src/domain/user.js index fd7734c7..56f49526 100644 --- a/src/domain/user.js +++ b/src/domain/user.js @@ -7,7 +7,7 @@ export default class User { * take as inputs, what types they return, and other useful information that JS doesn't have built in * @tutorial https://www.valentinog.com/blog/jsdoc * - * @param { { id: int, cohortId: int, email: string, profile: { firstName: string, lastName: string, bio: string, githubUrl: string } } } user + * @param { { id: int, cohortId: int, email: string, role: string, profile: { firstName: string, lastName: string, bio: string, githubUrl: string, username:string, mobile, profileImage: string } } } user * @returns {User} */ static fromDb(user) { @@ -19,38 +19,73 @@ export default class User { user.email, user.profile?.bio, user.profile?.githubUrl, + user.profile?.username, + user.profile?.mobile, + user.profile?.specialism, + user.profile?.startDate, + user.profile?.endDate, user.password, + user.profile?.profileImage, user.role ) } static async fromJson(json) { // eslint-disable-next-line camelcase - const { firstName, lastName, email, biography, githubUrl, password } = json + const { + cohortId, + firstName, + lastName, + email, + bio, + githubUrl, + username, + mobile, + specialism, + startDate, + endDate, + password, + profileImage + } = json - const passwordHash = await bcrypt.hash(password, 8) + let passwordHash = null + if (password) { + passwordHash = await bcrypt.hash(password, 8) + } return new User( null, - null, + cohortId, firstName, lastName, email, - biography, + bio, githubUrl, - passwordHash + username, + mobile, + specialism, + startDate, + endDate, + passwordHash, + profileImage ) } constructor( id, - cohortId, + cohortId = 1, firstName, lastName, email, bio, githubUrl, + username, + mobile, + specialism = 'Software Developer', + startDate = new Date('2023-01-01'), + endDate = new Date('2023-06-30'), passwordHash = null, + profileImage = null, role = 'STUDENT' ) { this.id = id @@ -60,8 +95,14 @@ export default class User { this.email = email this.bio = bio this.githubUrl = githubUrl + this.username = username + this.mobile = mobile + this.specialism = specialism + this.startDate = startDate + this.endDate = endDate this.passwordHash = passwordHash this.role = role + this.profileImage = profileImage } toJSON() { @@ -73,8 +114,14 @@ export default class User { firstName: this.firstName, lastName: this.lastName, email: this.email, - biography: this.bio, - githubUrl: this.githubUrl + bio: this.bio, + githubUrl: this.githubUrl, + profileImage: this.profileImage, + username: this.username, + mobile: this.mobile, + specialism: this.specialism, + startDate: this.startDate, + endDate: this.endDate } } } @@ -87,16 +134,18 @@ export default class User { const data = { email: this.email, password: this.passwordHash, - role: this.role + role: this.role, + cohortId: this.cohortId } - if (this.cohortId) { + // This will break the code currently, needs a fix if you want to include cohort as its own table + /* if (this.cohortId) { data.cohort = { connectOrCreate: { id: this.cohortId } } - } + } */ if (this.firstName && this.lastName) { data.profile = { @@ -104,7 +153,28 @@ export default class User { firstName: this.firstName, lastName: this.lastName, bio: this.bio, - githubUrl: this.githubUrl + githubUrl: this.githubUrl, + profileImage: this.profileImage, + username: this.username, + mobile: this.mobile, + specialism: this.specialism, + startDate: this.startDate, + endDate: this.endDate + } + } + } else { + data.profile = { + create: { + firstName: '', + lastName: '', + bio: this.bio, + githubUrl: this.githubUrl, + profileImage: this.profileImage, + username: this.username, + mobile: this.mobile, + specialism: this.specialism, + startDate: this.startDate, + endDate: this.endDate } } } @@ -118,6 +188,48 @@ export default class User { return User.fromDb(createdUser) } + /** + * @returns {User} + * A user instance containing the updated user data + */ + async update() { + const data = { + email: this.email, + role: this.role, + cohortId: this.cohortId, + profile: { + update: { + firstName: this.firstName, + lastName: this.lastName, + bio: this.bio, + githubUrl: this.githubUrl, + profileImage: this.profileImage, + username: this.username, + mobile: this.mobile, + specialism: this.specialism, + startDate: this.startDate, + endDate: this.endDate + } + } + } + + if (this.passwordHash) { + data.password = this.passwordHash + } + + const updatedUser = await dbClient.user.update({ + where: { + id: this.id + }, + data, + include: { + profile: true + } + }) + + return User.fromDb(updatedUser) + } + static async findByEmail(email) { return User._findByUnique('email', email) } diff --git a/src/middleware/auth.js b/src/middleware/auth.js index baffff47..449ba393 100644 --- a/src/middleware/auth.js +++ b/src/middleware/auth.js @@ -4,6 +4,9 @@ import jwt from 'jsonwebtoken' import User from '../domain/user.js' export async function validateTeacherRole(req, res, next) { + if (res.locals.skipTeacherValidation) { + return next() + } if (!req.user) { return sendMessageResponse(res, 500, 'Unable to verify user') } @@ -17,6 +20,34 @@ export async function validateTeacherRole(req, res, next) { next() } +// Function that checks if the currently logged in user is the same +// one that is being requested, if so, we skip the teacher validation +export async function validateLoggedInUser(req, res, next) { + if (!req.user) { + return sendMessageResponse(res, 500, 'Unable to verify user') + } + + if (req.user.id === parseInt(req.params.id)) { + // Skip teacher validation if the user is updating their own profile + res.locals.skipTeacherValidation = true + + // Overwrite the request body with pre-existing values for cohortId and role, + // if the logged in user is a STUDENT + if (req.user.role === 'STUDENT') { + const existingUser = await User.findById(parseInt(req.params.id)) + req.body.cohortId = existingUser.cohortId + req.body.role = existingUser.role + } + } + + // If no password was supplied, skip the password validation + if (!req.body.password) { + res.locals.skipPasswordValidation = true + } + + next() +} + export async function validateAuthentication(req, res, next) { const header = req.header('authorization') diff --git a/src/middleware/post.js b/src/middleware/post.js new file mode 100644 index 00000000..f2d189c6 --- /dev/null +++ b/src/middleware/post.js @@ -0,0 +1,41 @@ +import { sendDataResponse } from '../utils/responses.js' +import Post from '../domain/post.js' + +export async function validatePostOwnership(req, res, next) { + const { id: postId } = req.params + const { id: userId, role: userRole } = req.user + + try { + const post = await Post.getPostById(Number(postId)) + if (!post) { + return sendDataResponse(res, 404, { content: 'Post not found' }) + } + + if (post.user.id === userId || userRole === 'TEACHER') { + return next() + } + + return sendDataResponse(res, 401, { content: 'Unauthorized' }) + } catch (error) { + return sendDataResponse(res, 500, { content: 'Internal server error' }) + } +} + +export async function validatePostContent(req, res, next) { + const { content } = req.body + const maxLength = 200 + + if (!content || content.trim() === '') { + return sendDataResponse(res, 400, { + content: 'Content cannot be empty or null' + }) + } + + if (content.length > maxLength) { + return sendDataResponse(res, 400, { + content: `Content cannot exceed ${maxLength} characters` + }) + } + + next() +} diff --git a/src/middleware/user.js b/src/middleware/user.js new file mode 100644 index 00000000..5658c201 --- /dev/null +++ b/src/middleware/user.js @@ -0,0 +1,88 @@ +import { sendDataResponse } from '../utils/responses.js' + +export async function validateUser(req, res, next) { + const validateEmail = (email) => { + if ( + email.length < 7 || + email.indexOf('@') <= 0 || + email.slice(-4) !== '.com' || + (email.match(/@/g) || []).length > 1 || + email.charAt(email.length - 5) === '@' + ) { + return 'Email is invalid' + } + return null + } + + const emailError = validateEmail(req.body.email) + if (emailError) { + return sendDataResponse(res, 400, { email: emailError }) + } + + if (res.locals.skipPasswordValidation) { + return next() + } + + const validatePassword = (password) => { + const minLength = 8 + const hasUpperCase = /[A-Z]/.test(password) + const hasNumber = /\d/.test(password) + const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(password) + + if (password.length < minLength) { + return 'Password must be at least 8 characters long' + } + if (!hasUpperCase) { + return 'Password must contain at least one uppercase letter' + } + if (!hasNumber) { + return 'Password must contain at least one number' + } + if (!hasSpecialChar) { + return 'Password must contain at least one special character' + } + return null + } + + const passwordError = validatePassword(req.body.password) + if (passwordError) { + return sendDataResponse(res, 400, { password: passwordError }) + } + + next() +} + +export async function validateProfile(req, res, next) { + if (!req.body.firstName) { + return sendDataResponse(res, 400, { firstName: 'First name is required' }) + } + if (!req.body.lastName) { + return sendDataResponse(res, 400, { lastName: 'Last name is required' }) + } + if (!req.body.username) { + return sendDataResponse(res, 400, { username: 'Username is required' }) + } + if (!req.body.githubUrl) { + return sendDataResponse(res, 400, { githubUrl: 'Github URL is required' }) + } + if (!req.body.mobile) { + return sendDataResponse(res, 400, { mobile: 'Mobile is required' }) + } + if (!req.body.specialism) { + return sendDataResponse(res, 400, { specialism: 'Specialism is required' }) + } + if (!req.body.startDate) { + return sendDataResponse(res, 400, { startDate: 'Start date is required' }) + } + if (!req.body.endDate) { + return sendDataResponse(res, 400, { endDate: 'End date is required' }) + } + if (!req.body.role && req.user.role === 'TEACHER') { + return sendDataResponse(res, 400, { role: 'Role is required' }) + } + if (!req.body.cohortId && req.user.role === 'TEACHER') { + return sendDataResponse(res, 400, { cohortId: 'Cohort ID is required' }) + } + + next() +} diff --git a/src/routes/cohort.js b/src/routes/cohort.js index 3cc7813d..dcb40dde 100644 --- a/src/routes/cohort.js +++ b/src/routes/cohort.js @@ -1,5 +1,11 @@ import { Router } from 'express' -import { create } from '../controllers/cohort.js' +import { + create, + getAll, + getById, + updateById, + deleteById +} from '../controllers/cohort.js' import { validateAuthentication, validateTeacherRole @@ -8,5 +14,9 @@ import { const router = Router() router.post('/', validateAuthentication, validateTeacherRole, create) +router.get('/', validateAuthentication, getAll) +router.get('/:id', validateAuthentication, getById) +router.patch('/:id', validateAuthentication, validateTeacherRole, updateById) +router.delete('/:id', validateAuthentication, validateTeacherRole, deleteById) export default router diff --git a/src/routes/comment.js b/src/routes/comment.js new file mode 100644 index 00000000..2e6b8948 --- /dev/null +++ b/src/routes/comment.js @@ -0,0 +1,11 @@ +import { Router } from 'express' +import { create, remove, update } from '../controllers/comment.js' +import { validateAuthentication } from '../middleware/auth.js' + +const router = Router() + +router.post('/', validateAuthentication, create) +router.patch('/:id', validateAuthentication, update) +router.delete('/:id', validateAuthentication, remove) + +export default router diff --git a/src/routes/post.js b/src/routes/post.js index a7fbbfb3..90e42261 100644 --- a/src/routes/post.js +++ b/src/routes/post.js @@ -1,10 +1,23 @@ import { Router } from 'express' -import { create, getAll } from '../controllers/post.js' +import { + create, + getAll, + updateById, + getById, + deleteById +} from '../controllers/post.js' import { validateAuthentication } from '../middleware/auth.js' +import { + validatePostOwnership, + validatePostContent +} from '../middleware/post.js' const router = Router() -router.post('/', validateAuthentication, create) +router.post('/', validateAuthentication, validatePostContent, create) router.get('/', validateAuthentication, getAll) +router.get('/:id', validateAuthentication, getById) +router.patch('/:id', validateAuthentication, validatePostOwnership, updateById) +router.delete('/:id', validateAuthentication, validatePostOwnership, deleteById) export default router diff --git a/src/routes/user.js b/src/routes/user.js index 9f63d162..5f616892 100644 --- a/src/routes/user.js +++ b/src/routes/user.js @@ -2,14 +2,24 @@ import { Router } from 'express' import { create, getById, getAll, updateById } from '../controllers/user.js' import { validateAuthentication, - validateTeacherRole + validateTeacherRole, + validateLoggedInUser } from '../middleware/auth.js' +import { validateProfile, validateUser } from '../middleware/user.js' const router = Router() -router.post('/', create) +router.post('/', validateUser, create) router.get('/', validateAuthentication, getAll) router.get('/:id', validateAuthentication, getById) -router.patch('/:id', validateAuthentication, validateTeacherRole, updateById) +router.patch( + '/:id', + validateAuthentication, + validateLoggedInUser, + validateUser, + validateProfile, + validateTeacherRole, + updateById +) export default router diff --git a/src/server.js b/src/server.js index a3f67eeb..2f89075e 100644 --- a/src/server.js +++ b/src/server.js @@ -7,6 +7,7 @@ import cors from 'cors' import userRouter from './routes/user.js' import postRouter from './routes/post.js' import authRouter from './routes/auth.js' +import commentRouter from './routes/comment.js' import cohortRouter from './routes/cohort.js' import deliveryLogRouter from './routes/deliveryLog.js' @@ -24,6 +25,7 @@ app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDoc)) app.use('/users', userRouter) app.use('/posts', postRouter) app.use('/cohorts', cohortRouter) +app.use('/comments', commentRouter) app.use('/logs', deliveryLogRouter) app.use('/', authRouter)