From 587456017459a0ecc5edb3bfb7a9a564c1d8fb34 Mon Sep 17 00:00:00 2001 From: Carlo M Date: Mon, 21 Oct 2024 06:42:24 -0600 Subject: [PATCH 01/32] Tweaked CICD, removed husky, removed deployment --- .dockerignore | 4 ---- .github/workflows/ci.yml | 5 ----- .github/workflows/deploy.yml | 21 ------------------ .husky/pre-commit | 4 ---- DB_SETUP.md | 18 ---------------- Dockerfile | 36 ------------------------------- fly.toml | 42 ------------------------------------ package.json | 2 -- 8 files changed, 132 deletions(-) delete mode 100644 .dockerignore delete mode 100644 .github/workflows/deploy.yml delete mode 100644 .husky/pre-commit delete mode 100644 DB_SETUP.md delete mode 100644 Dockerfile delete mode 100644 fly.toml 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/.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/DB_SETUP.md b/DB_SETUP.md deleted file mode 100644 index 5a966b81..00000000 --- a/DB_SETUP.md +++ /dev/null @@ -1,18 +0,0 @@ -## Creating your databases with ElephantSQL - -1. [Sign in to ElephantSQL](https://customer.elephantsql.com/login) using your GitHub account - - If it asks you to create a team, create one with any name - -2. When logged in, click the green *Create New Instance* button in the top right -![](./assets/db-setup/1.PNG) - -3. Enter a name for your new database instance and choose the *Tiny Turtle (Free)* plan. **This will be your PRIMARY database** -![](./assets/db-setup/2.PNG) - -4. Repeat the same steps to create a second database, this time give it the same name but add `-shadow` to the end. **This will be your SHADOW database** - -5. In your shadow instance: - - click the *Browser* menu item on the left side of the screen - - in the SQL Browser text input, enter `CREATE SCHEMA shadow;` - - click the *Execute* button -![](./assets/db-setup/3.PNG) \ 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/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 41e19e5e..4efc3e40 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" }, "prisma": { @@ -33,7 +32,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" From 2326cca4000c002f8a9a536c2f6480944a88a8d9 Mon Sep 17 00:00:00 2001 From: Muzea001 Date: Mon, 28 Oct 2024 15:48:10 +0100 Subject: [PATCH 02/32] initialCommit --- .env.example | 5 ----- src/controllers/user.js | 6 ++++++ 2 files changed, 6 insertions(+), 5 deletions(-) delete mode 100644 .env.example 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/src/controllers/user.js b/src/controllers/user.js index 40ff0f1c..24388420 100644 --- a/src/controllers/user.js +++ b/src/controllers/user.js @@ -1,6 +1,7 @@ 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) @@ -19,6 +20,7 @@ export const create = async (req, res) => { } } +/* 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,6 +58,7 @@ 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 @@ -65,3 +69,5 @@ export const updateById = async (req, res) => { return sendDataResponse(res, 201, { user: { cohort_id: cohortId } }) } + +/* Test Commit statement */ From b9d122d356d20a1d51c9e1f59297c1f9f98d3099 Mon Sep 17 00:00:00 2001 From: Ingeborg Brommeland Austeid Date: Mon, 28 Oct 2024 15:51:47 +0100 Subject: [PATCH 03/32] first commit --- src/controllers/user.js | 136 ++++++++++++++++++++-------------------- 1 file changed, 69 insertions(+), 67 deletions(-) diff --git a/src/controllers/user.js b/src/controllers/user.js index 40ff0f1c..944ab9eb 100644 --- a/src/controllers/user.js +++ b/src/controllers/user.js @@ -1,67 +1,69 @@ -import User from '../domain/user.js' -import { sendDataResponse, sendMessageResponse } from '../utils/responses.js' - -export const create = async (req, res) => { - const userToCreate = await User.fromJson(req.body) - - try { - const existingUser = await User.findByEmail(userToCreate.email) - - if (existingUser) { - return sendDataResponse(res, 400, { email: 'Email already in use' }) - } - - const createdUser = await userToCreate.save() - - return sendDataResponse(res, 201, createdUser) - } catch (error) { - return sendMessageResponse(res, 500, 'Unable to create new user') - } -} - -export const getById = async (req, res) => { - const id = parseInt(req.params.id) - - try { - const foundUser = await User.findById(id) - - if (!foundUser) { - return sendDataResponse(res, 404, { id: 'User not found' }) - } - - return sendDataResponse(res, 200, foundUser) - } catch (e) { - return sendMessageResponse(res, 500, 'Unable to get user') - } -} - -export const getAll = async (req, res) => { - // eslint-disable-next-line camelcase - const { first_name: firstName } = req.query - - let foundUsers - - if (firstName) { - foundUsers = await User.findManyByFirstName(firstName) - } else { - foundUsers = await User.findAll() - } - - const formattedUsers = foundUsers.map((user) => { - return { - ...user.toJSON().user - } - }) - - return sendDataResponse(res, 200, { users: formattedUsers }) -} - -export const updateById = async (req, res) => { - const { cohort_id: cohortId } = req.body - - if (!cohortId) { - return sendDataResponse(res, 400, { cohort_id: 'Cohort ID is required' }) - } - - return sendDataResponse(res, 201, { user: { cohort_id: cohortId } }) -} +import User from '../domain/user.js' +import { sendDataResponse, sendMessageResponse } from '../utils/responses.js' + +export const create = async (req, res) => { + const userToCreate = await User.fromJson(req.body) + + // Add password validation + + try { + const existingUser = await User.findByEmail(userToCreate.email) + + if (existingUser) { + return sendDataResponse(res, 400, { email: 'Email already in use' }) + } + + const createdUser = await userToCreate.save() + + return sendDataResponse(res, 201, createdUser) + } catch (error) { + return sendMessageResponse(res, 500, 'Unable to create new user') + } +} + +export const getById = async (req, res) => { + const id = parseInt(req.params.id) + + try { + const foundUser = await User.findById(id) + + if (!foundUser) { + return sendDataResponse(res, 404, { id: 'User not found' }) + } + + return sendDataResponse(res, 200, foundUser) + } catch (e) { + return sendMessageResponse(res, 500, 'Unable to get user') + } +} + +export const getAll = async (req, res) => { + // eslint-disable-next-line camelcase + const { first_name: firstName } = req.query + + let foundUsers + + if (firstName) { + foundUsers = await User.findManyByFirstName(firstName) + } else { + foundUsers = await User.findAll() + } + + const formattedUsers = foundUsers.map((user) => { + return { + ...user.toJSON().user + } + }) + + return sendDataResponse(res, 200, { users: formattedUsers }) +} + +export const updateById = async (req, res) => { + const { cohort_id: cohortId } = req.body + + if (!cohortId) { + return sendDataResponse(res, 400, { cohort_id: 'Cohort ID is required' }) + } + + return sendDataResponse(res, 201, { user: { cohort_id: cohortId } }) +} From 354ac4544335d0bf3172cd672d6f56e422ccae91 Mon Sep 17 00:00:00 2001 From: Tuva Aarseth Date: Mon, 28 Oct 2024 15:59:50 +0100 Subject: [PATCH 04/32] First commit --- src/controllers/cohort.js | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/controllers/cohort.js b/src/controllers/cohort.js index cc39365b..818f14d4 100644 --- a/src/controllers/cohort.js +++ b/src/controllers/cohort.js @@ -1,12 +1,12 @@ -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 { 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') + } +} From f0cc81577efa09e3c08b4340aacbc2df43608f64 Mon Sep 17 00:00:00 2001 From: Ingeborg Brommeland Austeid Date: Tue, 29 Oct 2024 09:38:06 +0100 Subject: [PATCH 05/32] adds password validation --- src/controllers/user.js | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/src/controllers/user.js b/src/controllers/user.js index 944ab9eb..69298ba5 100644 --- a/src/controllers/user.js +++ b/src/controllers/user.js @@ -1,10 +1,34 @@ import User from '../domain/user.js' import { sendDataResponse, sendMessageResponse } from '../utils/responses.js' +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 +} + export const create = async (req, res) => { - const userToCreate = await User.fromJson(req.body) + const passwordError = validatePassword(req.body.password) + if (passwordError) { + return sendDataResponse(res, 400, { password: passwordError }) + } - // Add password validation + const userToCreate = await User.fromJson(req.body) try { const existingUser = await User.findByEmail(userToCreate.email) From b1e5ec30bd62bcaf6225fcf4b60b0a20b0ff1c4b Mon Sep 17 00:00:00 2001 From: Tuva Aarseth Date: Tue, 29 Oct 2024 09:52:35 +0100 Subject: [PATCH 06/32] Updated openapi.yml with profileImage --- docs/openapi.yml | 1084 +++++++++++++++++++++++----------------------- 1 file changed, 547 insertions(+), 537 deletions(-) diff --git a/docs/openapi.yml b/docs/openapi.yml index 5f2a05f2..d4deb04d 100644 --- a/docs/openapi.yml +++ b/docs/openapi.yml @@ -1,537 +1,547 @@ -openapi: 3.0.3 -info: - title: Team Dev Server API - description: |- - version: 1.0 - -servers: - - url: http://localhost:4000/ -tags: - - name: user - - name: post - - name: cohort - - name: log -paths: - /users: - post: - tags: - - user - summary: Create user - description: Create new user - operationId: createUser - requestBody: - description: User registration details - content: - application/json: - schema: - $ref: '#/components/schemas/CreateUser' - responses: - '201': - description: Created - content: - application/json: - schema: - $ref: '#/components/schemas/CreatedUser' - get: - tags: - - user - summary: Get all users by first name if provided - description: '' - operationId: getAllUsers - security: - - bearerAuth: [] - parameters: - - name: firstName - in: query - description: Search all users by first name if provided (case-sensitive and exact string matches only) - schema: - type: string - responses: - '200': - description: successful operation - content: - application/json: - schema: - $ref: '#/components/schemas/AllUsers' - '400': - description: fail - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - '404': - description: fail - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - /login: - post: - tags: - - user - summary: Localhost Login - description: '' - operationId: loginUser - requestBody: - description: User login information - content: - application/json: - schema: - $ref: '#/components/schemas/login' - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/loginRes' - - '400': - description: Invalid username/password supplied - - /users/{id}: - get: - tags: - - user - summary: Get user by user id - description: '' - operationId: getUserByID - security: - - bearerAuth: [] - parameters: - - name: id - in: path - description: 'The name that needs to be fetched. Use user1 for testing. ' - required: true - schema: - type: string - responses: - '200': - description: successful operation - content: - application/json: - schema: - type: object - properties: - status: - type: string - data: - $ref: '#/components/schemas/User' - - '400': - description: fail - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - '404': - description: fail - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - patch: - tags: - - user - summary: Update a user - description: Only users with a TEACHER role can update the cohortId or role. Users with Students role can only update their own details. - operationId: userUpdate - security: - - bearerAuth: [] - parameters: - - name: id - in: path - description: 'The user id that needs to be updated' - required: true - schema: - type: string - requestBody: - description: The profile info - content: - application/json: - schema: - $ref: '#/components/schemas/UpdateUser' - responses: - '201': - description: Successful operation - content: - application/json: - schema: - $ref: '#/components/schemas/CreatedUser' - '401': - description: fail - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - /posts: - post: - tags: - - post - summary: Create post - description: This can only be done by the logged in user. - operationId: createPost - security: - - bearerAuth: [] - requestBody: - description: Created post object - content: - application/json: - schema: - type: object - properties: - content: - type: string - responses: - 201: - description: success - content: - application/json: - schema: - $ref: '#/components/schemas/Post' - 400: - description: fail - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - get: - tags: - - post - summary: Get all posts - description: get all posts - operationId: getPosts - security: - - bearerAuth: [] - responses: - '200': - description: Successful operation - content: - application/json: - schema: - $ref: '#/components/schemas/Posts' - '401': - description: fail - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - /logs: - post: - tags: - - log - summary: Create delivery log - description: This can only be done by an authorised teacher user. - operationId: createLog - security: - - bearerAuth: [] - requestBody: - description: Created log object - content: - application/json: - schema: - type: object - properties: - date: - type: string - cohortId: - type: integer - lines: - type: array - items: - type: object - properties: - content: - type: string - responses: - 201: - description: success - content: - application/json: - schema: - $ref: '#/components/schemas/Log' - '401': - description: Unauthorised - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - /cohorts: - post: - tags: - - cohort - summary: Create a cohort - description: This can only be done by the logged in user with role TEACHER. - operationId: createCohort - security: - - bearerAuth: [] - responses: - 201: - description: success - content: - application/json: - schema: - type: object - properties: - status: - type: string - data: - properties: - cohort: - $ref: '#/components/schemas/Cohort' - 400: - description: fail - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - -components: - securitySchemes: - bearerAuth: - type: http - scheme: bearer - bearerFormat: JWT - schemas: - Post: - type: object - properties: - status: - type: string - data: - properties: - post: - properties: - id: - type: integer - content: - type: string - - Cohort: - type: object - properties: - id: - type: integer - createdAt: - type: string - format: string - updatedAt: - type: string - format: string - - AllUsers: - type: object - properties: - status: - type: string - data: - type: object - properties: - users: - type: array - items: - $ref: '#/components/schemas/User' - - User: - type: object - properties: - id: - type: integer - email: - type: string - role: - type: string - cohortId: - type: integer - firstName: - type: string - lastName: - type: string - bio: - type: string - githubUrl: - type: string - - CreateUser: - type: object - properties: - firstName: - type: string - lastName: - type: string - email: - type: string - bio: - type: string - githubUrl: - type: string - password: - type: string - - UpdateUser: - type: object - properties: - email: - type: string - password: - type: string - cohortId: - type: integer - role: - type: string - firstName: - type: string - lastName: - type: string - bio: - type: string - githubUrl: - type: string - - Posts: - type: object - properties: - status: - type: string - data: - type: object - properties: - posts: - type: array - items: - type: object - properties: - id: - type: integer - content: - type: string - createdAt: - type: string - format: string - updatedAt: - type: string - format: string - author: - type: object - properties: - id: - type: integer - cohortId: - type: integer - role: - type: string - firstName: - type: string - lastName: - type: string - bio: - type: string - githubUrl: - type: string - profileImageUrl: - type: string - - CreatedUser: - type: object - properties: - status: - type: string - example: success - data: - properties: - user: - properties: - id: - type: integer - email: - type: string - cohortId: - type: integer - role: - type: string - firstName: - type: string - lastName: - type: string - bio: - type: string - githubUrl: - type: string - login: - type: object - properties: - email: - type: string - password: - type: string - - loginRes: - type: object - properties: - status: - type: string - data: - properties: - token: - type: string - user: - properties: - id: - type: integer - email: - type: string - cohortId: - type: integer - role: - type: string - firstName: - type: string - lastName: - type: string - bio: - type: string - githubUrl: - type: string - Error: - type: object - properties: - status: - type: string - data: - properties: - error: - type: string - - Log: - type: object - properties: - status: - type: string - data: - properties: - log: - properties: - id: - type: integer - cohortId: - type: integer - date: - type: string - author: - type: object - properties: - id: - type: integer - firstName: - type: string - lastName: - type: string - lines: - type: array - items: - type: object - properties: - id: - type: integer - content: - type: string +openapi: 3.0.3 +info: + title: Team Dev Server API + description: |- + version: "1.0" + +servers: + - url: "http://localhost:4000/" +tags: + - name: user + - name: post + - name: cohort + - name: log +paths: + /users: + post: + tags: + - user + summary: Create user + description: Create new user + operationId: createUser + requestBody: + description: User registration details + content: + application/json: + schema: + $ref: '#/components/schemas/CreateUser' + responses: + '201': + description: Created + content: + application/json: + schema: + $ref: '#/components/schemas/CreatedUser' + get: + tags: + - user + summary: Get all users by first name if provided + description: '' + operationId: getAllUsers + security: + - bearerAuth: [] + parameters: + - name: firstName + in: query + description: Search all users by first name if provided (case-sensitive and exact string matches only) + schema: + type: string + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/AllUsers' + '400': + description: fail + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '404': + description: fail + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /login: + post: + tags: + - user + summary: Localhost Login + description: '' + operationId: loginUser + requestBody: + description: User login information + content: + application/json: + schema: + $ref: '#/components/schemas/login' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/loginRes' + + '400': + description: Invalid username/password supplied + + /users/{id}: + get: + tags: + - user + summary: Get user by user id + description: '' + operationId: getUserByID + security: + - bearerAuth: [] + parameters: + - name: id + in: path + description: 'The name that needs to be fetched. Use user1 for testing. ' + required: true + schema: + type: string + responses: + '200': + description: successful operation + content: + application/json: + schema: + type: object + properties: + status: + type: string + data: + $ref: '#/components/schemas/User' + + '400': + description: fail + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '404': + description: fail + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + patch: + tags: + - user + summary: Update a user + description: Only users with a TEACHER role can update the cohortId or role. Users with Students role can only update their own details. + operationId: userUpdate + security: + - bearerAuth: [] + parameters: + - name: id + in: path + description: 'The user id that needs to be updated' + required: true + schema: + type: string + requestBody: + description: The profile info + content: + application/json: + schema: + $ref: '#/components/schemas/UpdateUser' + responses: + '201': + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/CreatedUser' + '401': + description: fail + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /posts: + post: + tags: + - post + summary: Create post + description: This can only be done by the logged in user. + operationId: createPost + security: + - bearerAuth: [] + requestBody: + description: Created post object + content: + application/json: + schema: + type: object + properties: + content: + type: string + responses: + 201: + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/Post' + 400: + description: fail + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + get: + tags: + - post + summary: Get all posts + description: get all posts + operationId: getPosts + security: + - bearerAuth: [] + responses: + '200': + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Posts' + '401': + description: fail + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /logs: + post: + tags: + - log + summary: Create delivery log + description: This can only be done by an authorised teacher user. + operationId: createLog + security: + - bearerAuth: [] + requestBody: + description: Created log object + content: + application/json: + schema: + type: object + properties: + date: + type: string + cohortId: + type: integer + lines: + type: array + items: + type: object + properties: + content: + type: string + responses: + 201: + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/Log' + '401': + description: Unauthorised + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /cohorts: + post: + tags: + - cohort + summary: Create a cohort + description: This can only be done by the logged in user with role TEACHER. + operationId: createCohort + security: + - bearerAuth: [] + responses: + 201: + description: success + content: + application/json: + schema: + type: object + properties: + status: + type: string + data: + properties: + cohort: + $ref: '#/components/schemas/Cohort' + 400: + description: fail + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + +components: + securitySchemes: + bearerAuth: + type: http + scheme: bearer + bearerFormat: JWT + schemas: + Post: + type: object + properties: + status: + type: string + data: + properties: + post: + properties: + id: + type: integer + content: + type: string + + Cohort: + type: object + properties: + id: + type: integer + createdAt: + type: string + format: string + updatedAt: + type: string + format: string + + AllUsers: + type: object + properties: + status: + type: string + data: + type: object + properties: + users: + type: array + items: + $ref: '#/components/schemas/User' + + User: + type: object + properties: + id: + type: integer + email: + type: string + role: + type: string + cohortId: + type: integer + firstName: + type: string + lastName: + type: string + bio: + type: string + githubUrl: + type: string + profileImage: + type: string + + CreateUser: + type: object + properties: + firstName: + type: string + lastName: + type: string + email: + type: string + bio: + type: string + githubUrl: + type: string + password: + type: string + profileImage: + type: string + + UpdateUser: + type: object + properties: + email: + type: string + password: + type: string + cohortId: + type: integer + role: + type: string + firstName: + type: string + lastName: + type: string + bio: + type: string + githubUrl: + type: string + profileImage: + type: string + + Posts: + type: object + properties: + status: + type: string + data: + type: object + properties: + posts: + type: array + items: + type: object + properties: + id: + type: integer + content: + type: string + createdAt: + type: string + format: string + updatedAt: + type: string + format: string + author: + type: object + properties: + id: + type: integer + cohortId: + type: integer + role: + type: string + firstName: + type: string + lastName: + type: string + bio: + type: string + githubUrl: + type: string + profileImage: + type: string + + CreatedUser: + type: object + properties: + status: + type: string + example: success + data: + properties: + user: + properties: + id: + type: integer + email: + type: string + cohortId: + type: integer + role: + type: string + firstName: + type: string + lastName: + type: string + bio: + type: string + githubUrl: + type: string + profileImage: + type: string + login: + type: object + properties: + email: + type: string + password: + type: string + + loginRes: + type: object + properties: + status: + type: string + data: + properties: + token: + type: string + user: + properties: + id: + type: integer + email: + type: string + cohortId: + type: integer + role: + type: string + firstName: + type: string + lastName: + type: string + bio: + type: string + githubUrl: + type: string + profileImage: + type: string + Error: + type: object + properties: + status: + type: string + data: + properties: + error: + type: string + + Log: + type: object + properties: + status: + type: string + data: + properties: + log: + properties: + id: + type: integer + cohortId: + type: integer + date: + type: string + author: + type: object + properties: + id: + type: integer + firstName: + type: string + lastName: + type: string + lines: + type: array + items: + type: object + properties: + id: + type: integer + content: + type: string From 2034c1368810359ca749dd6b35c73e46a48b9678 Mon Sep 17 00:00:00 2001 From: Tuva Aarseth Date: Tue, 29 Oct 2024 10:10:46 +0100 Subject: [PATCH 07/32] Added profileImage to prisma schema and seed.js --- .../migration.sql | 2 + .../migration.sql | 1 + prisma/schema.prisma | 139 ++++++------ prisma/seed.js | 203 +++++++++--------- 4 files changed, 177 insertions(+), 168 deletions(-) create mode 100644 prisma/migrations/20241029090014_add_profile_image/migration.sql create mode 100644 prisma/migrations/20241029090826_edited_profile_image/migration.sql 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/20241029090826_edited_profile_image/migration.sql b/prisma/migrations/20241029090826_edited_profile_image/migration.sql new file mode 100644 index 00000000..af5102c8 --- /dev/null +++ b/prisma/migrations/20241029090826_edited_profile_image/migration.sql @@ -0,0 +1 @@ +-- This is an empty migration. \ No newline at end of file diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 72ec5632..3a3b150f 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -1,69 +1,70 @@ -// This is your Prisma schema file, -// learn more about it in the docs: https://pris.ly/d/prisma-schema - -generator client { - provider = "prisma-client-js" -} - -datasource db { - provider = "postgresql" - url = env("DATABASE_URL") - shadowDatabaseUrl = env("SHADOW_DATABASE_URL") -} - -enum Role { - STUDENT - TEACHER -} - -model User { - id Int @id @default(autoincrement()) - email String @unique - password String - role Role @default(STUDENT) - profile Profile? - cohortId Int? - cohort Cohort? @relation(fields: [cohortId], references: [id]) - posts Post[] - deliveryLogs DeliveryLog[] -} - -model Profile { - id Int @id @default(autoincrement()) - userId Int @unique - user User @relation(fields: [userId], references: [id]) - firstName String - lastName String - bio String? - githubUrl String? -} - -model Cohort { - id Int @id @default(autoincrement()) - users User[] - deliveryLogs DeliveryLog[] -} - -model Post { - id Int @id @default(autoincrement()) - content String - userId Int - user User @relation(fields: [userId], references: [id]) -} - -model DeliveryLog { - id Int @id @default(autoincrement()) - date DateTime - userId Int - user User @relation(fields: [userId], references: [id]) - cohortId Int - cohort Cohort @relation(fields: [cohortId], references: [id]) - lines DeliveryLogLine[] -} - -model DeliveryLogLine { - id Int @id @default(autoincrement()) - content String - logId Int - log DeliveryLog @relation(fields: [logId], references: [id]) -} +// This is your Prisma schema file, +// learn more about it in the docs: https://pris.ly/d/prisma-schema + +generator client { + provider = "prisma-client-js" +} + +datasource db { + provider = "postgresql" + url = env("DATABASE_URL") + shadowDatabaseUrl = env("SHADOW_DATABASE_URL") +} + +enum Role { + STUDENT + TEACHER +} + +model User { + id Int @id @default(autoincrement()) + email String @unique + password String + role Role @default(STUDENT) + profile Profile? + cohortId Int? + cohort Cohort? @relation(fields: [cohortId], references: [id]) + posts Post[] + deliveryLogs DeliveryLog[] +} + +model Profile { + id Int @id @default(autoincrement()) + userId Int @unique + user User @relation(fields: [userId], references: [id]) + firstName String + lastName String + bio String? + githubUrl String? + profileImage String? +} + +model Cohort { + id Int @id @default(autoincrement()) + users User[] + deliveryLogs DeliveryLog[] +} + +model Post { + id Int @id @default(autoincrement()) + content String + userId Int + user User @relation(fields: [userId], references: [id]) +} + +model DeliveryLog { + id Int @id @default(autoincrement()) + date DateTime + userId Int + user User @relation(fields: [userId], references: [id]) + cohortId Int + cohort Cohort @relation(fields: [cohortId], references: [id]) + lines DeliveryLogLine[] +} + +model DeliveryLogLine { + id Int @id @default(autoincrement()) + content String + logId Int + log DeliveryLog @relation(fields: [logId], references: [id]) +} diff --git a/prisma/seed.js b/prisma/seed.js index 21684795..7892170a 100644 --- a/prisma/seed.js +++ b/prisma/seed.js @@ -1,99 +1,104 @@ -import { PrismaClient } from '@prisma/client' -import bcrypt from 'bcrypt' -const prisma = new PrismaClient() - -async function seed() { - const cohort = await createCohort() - - const student = await createUser( - 'student@test.com', - 'Testpassword1!', - cohort.id, - 'Joe', - 'Bloggs', - 'Hello, world!', - 'student1' - ) - const teacher = await createUser( - 'teacher@test.com', - 'Testpassword1!', - null, - 'Rick', - 'Sanchez', - 'Hello there!', - 'teacher1', - 'TEACHER' - ) - - await createPost(student.id, 'My first post!') - await createPost(teacher.id, 'Hello, students') - - process.exit(0) -} - -async function createPost(userId, content) { - const post = await prisma.post.create({ - data: { - userId, - content - }, - include: { - user: true - } - }) - - console.info('Post created', post) - - return post -} - -async function createCohort() { - const cohort = await prisma.cohort.create({ - data: {} - }) - - console.info('Cohort created', cohort) - - return cohort -} - -async function createUser( - email, - password, - cohortId, - firstName, - lastName, - bio, - githubUrl, - role = 'STUDENT' -) { - const user = await prisma.user.create({ - data: { - email, - password: await bcrypt.hash(password, 8), - role, - cohortId, - profile: { - create: { - firstName, - lastName, - bio, - githubUrl - } - } - }, - include: { - profile: true - } - }) - - console.info(`${role} created`, user) - - return user -} - -seed().catch(async (e) => { - console.error(e) - await prisma.$disconnect() - process.exit(1) -}) +import { PrismaClient } from '@prisma/client' +import bcrypt from 'bcrypt' +const prisma = new PrismaClient() + +async function seed() { + const cohort = await createCohort() + + const student = await createUser( + 'student@test.com', + 'Testpassword1!', + cohort.id, + 'Joe', + 'Bloggs', + 'Hello, world!', + 'student1', + null, + 'STUDENT' + ) + const teacher = await createUser( + 'teacher@test.com', + 'Testpassword1!', + null, + 'Rick', + 'Sanchez', + 'Hello there!', + 'teacher1', + null, + 'TEACHER' + ) + + await createPost(student.id, 'My first post!') + await createPost(teacher.id, 'Hello, students') + + process.exit(0) +} + +async function createPost(userId, content) { + const post = await prisma.post.create({ + data: { + userId, + content + }, + include: { + user: true + } + }) + + console.info('Post created', post) + + return post +} + +async function createCohort() { + const cohort = await prisma.cohort.create({ + data: {} + }) + + console.info('Cohort created', cohort) + + return cohort +} + +async function createUser( + email, + password, + cohortId, + firstName, + lastName, + bio, + githubUrl, + profileImage, + role = 'STUDENT' +) { + const user = await prisma.user.create({ + data: { + email, + password: await bcrypt.hash(password, 8), + role, + cohortId, + profile: { + create: { + firstName, + lastName, + bio, + githubUrl, + profileImage + } + } + }, + include: { + profile: true + } + }) + + console.info(`${role} created`, user) + + return user +} + +seed().catch(async (e) => { + console.error(e) + await prisma.$disconnect() + process.exit(1) +}) From 9c21e2b1b877a20b840b7ce71752297cf2b4ce40 Mon Sep 17 00:00:00 2001 From: Tuva Aarseth Date: Tue, 29 Oct 2024 10:11:38 +0100 Subject: [PATCH 08/32] Removed failed migration --- .../migrations/20241029090826_edited_profile_image/migration.sql | 1 - 1 file changed, 1 deletion(-) delete mode 100644 prisma/migrations/20241029090826_edited_profile_image/migration.sql diff --git a/prisma/migrations/20241029090826_edited_profile_image/migration.sql b/prisma/migrations/20241029090826_edited_profile_image/migration.sql deleted file mode 100644 index af5102c8..00000000 --- a/prisma/migrations/20241029090826_edited_profile_image/migration.sql +++ /dev/null @@ -1 +0,0 @@ --- This is an empty migration. \ No newline at end of file From 3f8c12ce72b17f43ca7a0a3b11e8f5fa9cd3ca54 Mon Sep 17 00:00:00 2001 From: tvaltn Date: Tue, 29 Oct 2024 10:51:57 +0100 Subject: [PATCH 09/32] added user patch functionality --- src/controllers/user.js | 33 ++++++++++++++++++++++++++++----- src/domain/user.js | 33 ++++++++++++++++++++++++++++++++- 2 files changed, 60 insertions(+), 6 deletions(-) diff --git a/src/controllers/user.js b/src/controllers/user.js index 40ff0f1c..a177bee5 100644 --- a/src/controllers/user.js +++ b/src/controllers/user.js @@ -57,11 +57,34 @@ export const getAll = async (req, res) => { } export const updateById = async (req, res) => { - const { cohort_id: cohortId } = req.body - - if (!cohortId) { - return sendDataResponse(res, 400, { cohort_id: 'Cohort ID is required' }) + const id = parseInt(req.params.id) + const userToUpdate = await User.fromJson(req.body) + userToUpdate.id = id + + // Update cohortId and role to userToUpdate (only if logged in role is Teacher) + // otherwise, keep the existing values of the user + if (req.user.role === 'TEACHER') { + userToUpdate.cohortId = parseInt(req.body.cohortId) + const roleId = parseInt(req.body.role) + if (roleId === 1) { + userToUpdate.role = 'STUDENT' + } else if (roleId === 2) { + userToUpdate.role = 'TEACHER' + } + } else { + const existingUser = await User.findById(id) + userToUpdate.cohortId = existingUser.cohortId + userToUpdate.role = existingUser.role } - return sendDataResponse(res, 201, { user: { cohort_id: cohortId } }) + try { + if (!userToUpdate.cohortId) { + return sendDataResponse(res, 400, { cohort_id: userToUpdate }) + } + const updatedUser = await userToUpdate.update() + + return sendDataResponse(res, 201, updatedUser) + } catch (error) { + return sendMessageResponse(res, 500, 'Unable to update user') + } } diff --git a/src/domain/user.js b/src/domain/user.js index fd7734c7..be0b437f 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 } } } user * @returns {User} */ static fromDb(user) { @@ -118,6 +118,37 @@ export default class User { return User.fromDb(createdUser) } + /** + * @returns {User} + * A user instance containing the updated user data + */ + async update() { + const updatedUser = await dbClient.user.update({ + where: { + id: this.id + }, + data: { + email: this.email, + password: this.passwordHash, + role: this.role, + cohortId: this.cohortId, + profile: { + update: { + firstName: this.firstName, + lastName: this.lastName, + bio: this.bio, + githubUrl: this.githubUrl + } + } + }, + include: { + profile: true + } + }) + + return User.fromDb(updatedUser) + } + static async findByEmail(email) { return User._findByUnique('email', email) } From dc3132b00bc867eabcc890f248c80ade2b356a9c Mon Sep 17 00:00:00 2001 From: Muzea001 Date: Tue, 29 Oct 2024 11:26:57 +0100 Subject: [PATCH 10/32] added relevant fields, changed class structure to match newly created fields --- docs/openapi.yml | 87 +++++++++++++++++-- .../migration.sql | 6 ++ prisma/schema.prisma | 5 ++ prisma/seed.js | 32 +++++-- src/controllers/user.js | 6 +- src/domain/user.js | 54 ++++++++++-- 6 files changed, 167 insertions(+), 23 deletions(-) create mode 100644 prisma/migrations/20241029082651_add_profile_fields/migration.sql diff --git a/docs/openapi.yml b/docs/openapi.yml index 5f2a05f2..d4b9b148 100644 --- a/docs/openapi.yml +++ b/docs/openapi.yml @@ -85,10 +85,8 @@ paths: application/json: schema: $ref: '#/components/schemas/loginRes' - '400': description: Invalid username/password supplied - /users/{id}: get: tags: @@ -117,7 +115,6 @@ paths: type: string data: $ref: '#/components/schemas/User' - '400': description: fail content: @@ -314,10 +311,10 @@ components: type: integer createdAt: type: string - format: string + format: date-time updatedAt: type: string - format: string + format: date-time AllUsers: type: object @@ -351,6 +348,18 @@ 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 CreateUser: type: object @@ -365,6 +374,18 @@ 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 @@ -387,6 +408,18 @@ 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 Posts: type: object @@ -407,10 +440,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,6 +461,18 @@ 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 profileImageUrl: type: string @@ -457,6 +502,19 @@ 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 + login: type: object properties: @@ -492,6 +550,19 @@ 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 + Error: type: object properties: @@ -534,4 +605,4 @@ components: id: type: integer content: - type: string + type: string \ No newline at end of file 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/schema.prisma b/prisma/schema.prisma index 72ec5632..372a6029 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -36,6 +36,11 @@ model Profile { lastName String bio String? githubUrl String? + username String @default("") + mobile String @default("") + specialism String @default("") + startDate DateTime @default(now()) + endDate DateTime? } model Cohort { diff --git a/prisma/seed.js b/prisma/seed.js index 21684795..a42ec86b 100644 --- a/prisma/seed.js +++ b/prisma/seed.js @@ -12,7 +12,12 @@ async function seed() { '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') // endDate ) const teacher = await createUser( 'teacher@test.com', @@ -21,7 +26,12 @@ async function seed() { 'Rick', 'Sanchez', 'Hello there!', + 'teacher1@git.com', 'teacher1', + '987-654-3210', + 'Teaching', + new Date('2022-01-01'), + new Date('2022-12-31'), 'TEACHER' ) @@ -58,14 +68,19 @@ async function createCohort() { } async function createUser( - email, - password, - cohortId, firstName, lastName, + email, bio, githubUrl, - role = 'STUDENT' + username, + mobile, + specialism, + startDate, + endDate, + password, + role = 'STUDENT', + cohortId = null ) { const user = await prisma.user.create({ data: { @@ -78,7 +93,12 @@ async function createUser( firstName, lastName, bio, - githubUrl + githubUrl, + username, + mobile, + specialism, + startDate: new Date(startDate), + endDate: new Date(endDate) } } }, diff --git a/src/controllers/user.js b/src/controllers/user.js index 24388420..43742c07 100644 --- a/src/controllers/user.js +++ b/src/controllers/user.js @@ -3,9 +3,9 @@ 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) { @@ -16,10 +16,10 @@ 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) diff --git a/src/domain/user.js b/src/domain/user.js index fd7734c7..34ab4b7f 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, profile: { firstName: string, lastName: string, bio: string, githubUrl: string, username:string, mobile } } } user * @returns {User} */ static fromDb(user) { @@ -19,6 +19,11 @@ 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.role ) @@ -26,7 +31,19 @@ export default class User { static async fromJson(json) { // eslint-disable-next-line camelcase - const { firstName, lastName, email, biography, githubUrl, password } = json + const { + firstName, + lastName, + email, + bio, + githubUrl, + username, + mobile, + specialism, + startDate, + endDate, + password + } = json const passwordHash = await bcrypt.hash(password, 8) @@ -36,8 +53,13 @@ export default class User { firstName, lastName, email, - biography, + bio, githubUrl, + username, + mobile, + specialism, + startDate, + endDate, passwordHash ) } @@ -50,6 +72,11 @@ export default class User { email, bio, githubUrl, + username, + mobile, + specialism, + startDate, + endDate, passwordHash = null, role = 'STUDENT' ) { @@ -60,6 +87,11 @@ 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 } @@ -73,8 +105,13 @@ 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, + username: this.username, + mobile: this.mobile, + specialism: this.specialism, + startDate: this.startDate, + endDate: this.endDate } } } @@ -104,7 +141,12 @@ export default class User { firstName: this.firstName, lastName: this.lastName, bio: this.bio, - githubUrl: this.githubUrl + githubUrl: this.githubUrl, + username: this.username, + mobile: this.mobile, + specialism: this.specialism, + startDate: this.startDate, + endDate: this.endDate } } } From dbc91b2bdcc7b5d25a9888b3114c5e2e82ec0e39 Mon Sep 17 00:00:00 2001 From: Ingeborg Brommeland Austeid Date: Tue, 29 Oct 2024 11:27:07 +0100 Subject: [PATCH 11/32] adds validateUser function in middleware\user.js with the password validation --- src/controllers/user.js | 52 ++++++++++++----------------------------- src/middleware/user.js | 31 ++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 37 deletions(-) create mode 100644 src/middleware/user.js diff --git a/src/controllers/user.js b/src/controllers/user.js index 69298ba5..9101e852 100644 --- a/src/controllers/user.js +++ b/src/controllers/user.js @@ -1,49 +1,27 @@ import User from '../domain/user.js' +import { validateUser } from '../middleware/user.js' import { sendDataResponse, sendMessageResponse } from '../utils/responses.js' -const validatePassword = (password) => { - const minLength = 8 - const hasUpperCase = /[A-Z]/.test(password) - const hasNumber = /\d/.test(password) - const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(password) +export const create = [ + validateUser, + async (req, res) => { + const userToCreate = await User.fromJson(req.body) - 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 -} + try { + const existingUser = await User.findByEmail(userToCreate.email) -export const create = async (req, res) => { - const passwordError = validatePassword(req.body.password) - if (passwordError) { - return sendDataResponse(res, 400, { password: passwordError }) - } + if (existingUser) { + return sendDataResponse(res, 400, { email: 'Email already in use' }) + } - const userToCreate = await User.fromJson(req.body) + const createdUser = await userToCreate.save() - try { - const existingUser = await User.findByEmail(userToCreate.email) - - if (existingUser) { - return sendDataResponse(res, 400, { email: 'Email already in use' }) + return sendDataResponse(res, 201, createdUser) + } catch (error) { + return sendMessageResponse(res, 500, 'Unable to create new user') } - - const createdUser = await userToCreate.save() - - return sendDataResponse(res, 201, createdUser) - } catch (error) { - return sendMessageResponse(res, 500, 'Unable to create new user') } -} +] export const getById = async (req, res) => { const id = parseInt(req.params.id) diff --git a/src/middleware/user.js b/src/middleware/user.js new file mode 100644 index 00000000..756db248 --- /dev/null +++ b/src/middleware/user.js @@ -0,0 +1,31 @@ +import { sendDataResponse } from '../utils/responses.js' + +export async function validateUser(req, res, 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() +} From 04b4a9af77fabf37a3d0bcebb0254a3365bad635 Mon Sep 17 00:00:00 2001 From: Ingeborg Brommeland Austeid Date: Tue, 29 Oct 2024 11:46:49 +0100 Subject: [PATCH 12/32] adds in routes\user.js instead of in controllers\user.js --- src/controllers/user.js | 28 ++++++++++++---------------- src/routes/user.js | 37 ++++++++++++++++++++++--------------- 2 files changed, 34 insertions(+), 31 deletions(-) diff --git a/src/controllers/user.js b/src/controllers/user.js index 9101e852..5829b8ba 100644 --- a/src/controllers/user.js +++ b/src/controllers/user.js @@ -1,27 +1,23 @@ import User from '../domain/user.js' -import { validateUser } from '../middleware/user.js' import { sendDataResponse, sendMessageResponse } from '../utils/responses.js' -export const create = [ - validateUser, - async (req, res) => { - const userToCreate = await User.fromJson(req.body) +export const create = async (req, res) => { + const userToCreate = await User.fromJson(req.body) - try { - const existingUser = await User.findByEmail(userToCreate.email) + try { + const existingUser = await User.findByEmail(userToCreate.email) - if (existingUser) { - return sendDataResponse(res, 400, { email: 'Email already in use' }) - } + if (existingUser) { + return sendDataResponse(res, 400, { email: 'Email already in use' }) + } - const createdUser = await userToCreate.save() + const createdUser = await userToCreate.save() - return sendDataResponse(res, 201, createdUser) - } catch (error) { - return sendMessageResponse(res, 500, 'Unable to create new user') - } + return sendDataResponse(res, 201, createdUser) + } catch (error) { + return sendMessageResponse(res, 500, 'Unable to create new user') } -] +} export const getById = async (req, res) => { const id = parseInt(req.params.id) diff --git a/src/routes/user.js b/src/routes/user.js index 9f63d162..c17edb74 100644 --- a/src/routes/user.js +++ b/src/routes/user.js @@ -1,15 +1,22 @@ -import { Router } from 'express' -import { create, getById, getAll, updateById } from '../controllers/user.js' -import { - validateAuthentication, - validateTeacherRole -} from '../middleware/auth.js' - -const router = Router() - -router.post('/', create) -router.get('/', validateAuthentication, getAll) -router.get('/:id', validateAuthentication, getById) -router.patch('/:id', validateAuthentication, validateTeacherRole, updateById) - -export default router +import { Router } from 'express' +import { create, getById, getAll, updateById } from '../controllers/user.js' +import { + validateAuthentication, + validateTeacherRole +} from '../middleware/auth.js' +import { validateUser } from '../middleware/user.js' + +const router = Router() + +router.post('/', validateUser, create) +router.get('/', validateAuthentication, getAll) +router.get('/:id', validateAuthentication, getById) +router.patch( + '/:id', + validateAuthentication, + validateUser, + validateTeacherRole, + updateById +) + +export default router From 6aa6abdc950c3914d531f0b63b57f40c9028a020 Mon Sep 17 00:00:00 2001 From: tvaltn Date: Tue, 29 Oct 2024 11:54:24 +0100 Subject: [PATCH 13/32] added logged in user routing --- src/controllers/user.js | 3 ++- src/middleware/auth.js | 18 ++++++++++++++++++ src/routes/user.js | 11 +++++++++-- 3 files changed, 29 insertions(+), 3 deletions(-) diff --git a/src/controllers/user.js b/src/controllers/user.js index a177bee5..437d8a40 100644 --- a/src/controllers/user.js +++ b/src/controllers/user.js @@ -79,12 +79,13 @@ export const updateById = async (req, res) => { try { if (!userToUpdate.cohortId) { - return sendDataResponse(res, 400, { cohort_id: userToUpdate }) + 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') } } diff --git a/src/middleware/auth.js b/src/middleware/auth.js index baffff47..1e3f6f10 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,21 @@ 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)) { + return next() + } + + res.locals.skipTeacherValidation = true + next() +} + export async function validateAuthentication(req, res, next) { const header = req.header('authorization') diff --git a/src/routes/user.js b/src/routes/user.js index 9f63d162..371a669d 100644 --- a/src/routes/user.js +++ b/src/routes/user.js @@ -2,7 +2,8 @@ import { Router } from 'express' import { create, getById, getAll, updateById } from '../controllers/user.js' import { validateAuthentication, - validateTeacherRole + validateTeacherRole, + validateLoggedInUser } from '../middleware/auth.js' const router = Router() @@ -10,6 +11,12 @@ const router = Router() router.post('/', create) router.get('/', validateAuthentication, getAll) router.get('/:id', validateAuthentication, getById) -router.patch('/:id', validateAuthentication, validateTeacherRole, updateById) +router.patch( + '/:id', + validateAuthentication, + validateLoggedInUser, + validateTeacherRole, + updateById +) export default router From 647caa2c56eb7290ee76e3a7711072e19acad6b4 Mon Sep 17 00:00:00 2001 From: Tuva Aarseth Date: Tue, 29 Oct 2024 11:54:54 +0100 Subject: [PATCH 14/32] Added profileImage to user.js domain --- src/domain/user.js | 362 +++++++++++++++++++++++---------------------- 1 file changed, 189 insertions(+), 173 deletions(-) diff --git a/src/domain/user.js b/src/domain/user.js index fd7734c7..b8605698 100644 --- a/src/domain/user.js +++ b/src/domain/user.js @@ -1,173 +1,189 @@ -import dbClient from '../utils/dbClient.js' -import bcrypt from 'bcrypt' - -export default class User { - /** - * This is JSDoc - a way for us to tell other developers what types functions/methods - * 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 - * @returns {User} - */ - static fromDb(user) { - return new User( - user.id, - user.cohortId, - user.profile?.firstName, - user.profile?.lastName, - user.email, - user.profile?.bio, - user.profile?.githubUrl, - user.password, - user.role - ) - } - - static async fromJson(json) { - // eslint-disable-next-line camelcase - const { firstName, lastName, email, biography, githubUrl, password } = json - - const passwordHash = await bcrypt.hash(password, 8) - - return new User( - null, - null, - firstName, - lastName, - email, - biography, - githubUrl, - passwordHash - ) - } - - constructor( - id, - cohortId, - firstName, - lastName, - email, - bio, - githubUrl, - passwordHash = null, - role = 'STUDENT' - ) { - this.id = id - this.cohortId = cohortId - this.firstName = firstName - this.lastName = lastName - this.email = email - this.bio = bio - this.githubUrl = githubUrl - this.passwordHash = passwordHash - this.role = role - } - - toJSON() { - return { - user: { - id: this.id, - cohort_id: this.cohortId, - role: this.role, - firstName: this.firstName, - lastName: this.lastName, - email: this.email, - biography: this.bio, - githubUrl: this.githubUrl - } - } - } - - /** - * @returns {User} - * A user instance containing an ID, representing the user data created in the database - */ - async save() { - const data = { - email: this.email, - password: this.passwordHash, - role: this.role - } - - if (this.cohortId) { - data.cohort = { - connectOrCreate: { - id: this.cohortId - } - } - } - - if (this.firstName && this.lastName) { - data.profile = { - create: { - firstName: this.firstName, - lastName: this.lastName, - bio: this.bio, - githubUrl: this.githubUrl - } - } - } - const createdUser = await dbClient.user.create({ - data, - include: { - profile: true - } - }) - - return User.fromDb(createdUser) - } - - static async findByEmail(email) { - return User._findByUnique('email', email) - } - - static async findById(id) { - return User._findByUnique('id', id) - } - - static async findManyByFirstName(firstName) { - return User._findMany('firstName', firstName) - } - - static async findAll() { - return User._findMany() - } - - static async _findByUnique(key, value) { - const foundUser = await dbClient.user.findUnique({ - where: { - [key]: value - }, - include: { - profile: true - } - }) - - if (foundUser) { - return User.fromDb(foundUser) - } - - return null - } - - static async _findMany(key, value) { - const query = { - include: { - profile: true - } - } - - if (key !== undefined && value !== undefined) { - query.where = { - profile: { - [key]: value - } - } - } - - const foundUsers = await dbClient.user.findMany(query) - - return foundUsers.map((user) => User.fromDb(user)) - } -} +import dbClient from '../utils/dbClient.js' +import bcrypt from 'bcrypt' + +export default class User { + /** + * This is JSDoc - a way for us to tell other developers what types functions/methods + * 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, profileImage: string } } } user + * @returns {User} + */ + static fromDb(user) { + console.log(user) + return new User( + user.id, + user.cohortId, + user.profile?.firstName, + user.profile?.lastName, + user.email, + user.profile?.bio, + user.profile?.githubUrl, + user.password, + user.profile?.profileImage, + user.role + ) + } + + static async fromJson(json) { + // eslint-disable-next-line camelcase + const { + firstName, + lastName, + email, + biography, + githubUrl, + password, + profileImage + } = json + + const passwordHash = await bcrypt.hash(password, 8) + + return new User( + null, + null, + firstName, + lastName, + email, + biography, + githubUrl, + passwordHash, + profileImage + ) + } + + constructor( + id, + cohortId, + firstName, + lastName, + email, + bio, + githubUrl, + passwordHash = null, + profileImage = null, + role = 'STUDENT' + ) { + this.id = id + this.cohortId = cohortId + this.firstName = firstName + this.lastName = lastName + this.email = email + this.bio = bio + this.githubUrl = githubUrl + this.passwordHash = passwordHash + this.role = role + this.profileImage = profileImage + } + + toJSON() { + console.log(this) + return { + user: { + id: this.id, + cohort_id: this.cohortId, + role: this.role, + firstName: this.firstName, + lastName: this.lastName, + email: this.email, + biography: this.bio, + githubUrl: this.githubUrl, + profileImage: this.profileImage + } + } + } + + /** + * @returns {User} + * A user instance containing an ID, representing the user data created in the database + */ + async save() { + const data = { + email: this.email, + password: this.passwordHash, + role: this.role + } + + if (this.cohortId) { + data.cohort = { + connectOrCreate: { + id: this.cohortId + } + } + } + + if (this.firstName && this.lastName) { + data.profile = { + create: { + firstName: this.firstName, + lastName: this.lastName, + bio: this.bio, + githubUrl: this.githubUrl, + profileImage: this.profileImage + } + } + } + const createdUser = await dbClient.user.create({ + data, + include: { + profile: true + } + }) + + return User.fromDb(createdUser) + } + + static async findByEmail(email) { + return User._findByUnique('email', email) + } + + static async findById(id) { + return User._findByUnique('id', id) + } + + static async findManyByFirstName(firstName) { + return User._findMany('firstName', firstName) + } + + static async findAll() { + return User._findMany() + } + + static async _findByUnique(key, value) { + const foundUser = await dbClient.user.findUnique({ + where: { + [key]: value + }, + include: { + profile: true + } + }) + + if (foundUser) { + return User.fromDb(foundUser) + } + + return null + } + + static async _findMany(key, value) { + const query = { + include: { + profile: true + } + } + + if (key !== undefined && value !== undefined) { + query.where = { + profile: { + [key]: value + } + } + } + + const foundUsers = await dbClient.user.findMany(query) + + return foundUsers.map((user) => User.fromDb(user)) + } +} From 86ef6bbfcff4370f9792daebf32b3b56746df78d Mon Sep 17 00:00:00 2001 From: tvaltn Date: Tue, 29 Oct 2024 12:03:16 +0100 Subject: [PATCH 15/32] fixed role format from request body --- src/controllers/user.js | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/src/controllers/user.js b/src/controllers/user.js index 437d8a40..0333a7e8 100644 --- a/src/controllers/user.js +++ b/src/controllers/user.js @@ -65,12 +65,7 @@ export const updateById = async (req, res) => { // otherwise, keep the existing values of the user if (req.user.role === 'TEACHER') { userToUpdate.cohortId = parseInt(req.body.cohortId) - const roleId = parseInt(req.body.role) - if (roleId === 1) { - userToUpdate.role = 'STUDENT' - } else if (roleId === 2) { - userToUpdate.role = 'TEACHER' - } + userToUpdate.role = req.body.role } else { const existingUser = await User.findById(id) userToUpdate.cohortId = existingUser.cohortId From b56e095e7c9430373e19a8d9b267ef0836d183a4 Mon Sep 17 00:00:00 2001 From: Muzea001 Date: Tue, 29 Oct 2024 13:28:02 +0100 Subject: [PATCH 16/32] fixed order of seeding data --- prisma/seed.js | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/prisma/seed.js b/prisma/seed.js index a42ec86b..de67ec44 100644 --- a/prisma/seed.js +++ b/prisma/seed.js @@ -7,7 +7,6 @@ async function seed() { const student = await createUser( 'student@test.com', - 'Testpassword1!', cohort.id, 'Joe', 'Bloggs', @@ -17,11 +16,12 @@ async function seed() { '123-456-7890', // mobile 'Software Engineering', // specialism new Date('2023-01-01'), // startDate - new Date('2023-12-31') // endDate + new Date('2023-12-31'), + 'STUDENT', + 'Testpassword1!' ) const teacher = await createUser( 'teacher@test.com', - 'Testpassword1!', null, 'Rick', 'Sanchez', @@ -32,7 +32,8 @@ async function seed() { 'Teaching', new Date('2022-01-01'), new Date('2022-12-31'), - 'TEACHER' + 'TEACHER', + 'Testpassword1!' ) await createPost(student.id, 'My first post!') @@ -68,9 +69,10 @@ async function createCohort() { } async function createUser( + email, + cohortId, firstName, lastName, - email, bio, githubUrl, username, @@ -78,9 +80,8 @@ async function createUser( specialism, startDate, endDate, - password, role = 'STUDENT', - cohortId = null + password ) { const user = await prisma.user.create({ data: { From 52145ad1f8948905046eddb46fb4851f0bb369f6 Mon Sep 17 00:00:00 2001 From: Ingeborg Brommeland Austeid Date: Tue, 29 Oct 2024 13:28:59 +0100 Subject: [PATCH 17/32] adds 400 response to /users in openapi.yaml --- docs/openapi.yml | 1080 +++++++++++++++++++++++----------------------- 1 file changed, 543 insertions(+), 537 deletions(-) diff --git a/docs/openapi.yml b/docs/openapi.yml index 5f2a05f2..8dd81e7b 100644 --- a/docs/openapi.yml +++ b/docs/openapi.yml @@ -1,537 +1,543 @@ -openapi: 3.0.3 -info: - title: Team Dev Server API - description: |- - version: 1.0 - -servers: - - url: http://localhost:4000/ -tags: - - name: user - - name: post - - name: cohort - - name: log -paths: - /users: - post: - tags: - - user - summary: Create user - description: Create new user - operationId: createUser - requestBody: - description: User registration details - content: - application/json: - schema: - $ref: '#/components/schemas/CreateUser' - responses: - '201': - description: Created - content: - application/json: - schema: - $ref: '#/components/schemas/CreatedUser' - get: - tags: - - user - summary: Get all users by first name if provided - description: '' - operationId: getAllUsers - security: - - bearerAuth: [] - parameters: - - name: firstName - in: query - description: Search all users by first name if provided (case-sensitive and exact string matches only) - schema: - type: string - responses: - '200': - description: successful operation - content: - application/json: - schema: - $ref: '#/components/schemas/AllUsers' - '400': - description: fail - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - '404': - description: fail - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - /login: - post: - tags: - - user - summary: Localhost Login - description: '' - operationId: loginUser - requestBody: - description: User login information - content: - application/json: - schema: - $ref: '#/components/schemas/login' - responses: - '200': - description: OK - content: - application/json: - schema: - $ref: '#/components/schemas/loginRes' - - '400': - description: Invalid username/password supplied - - /users/{id}: - get: - tags: - - user - summary: Get user by user id - description: '' - operationId: getUserByID - security: - - bearerAuth: [] - parameters: - - name: id - in: path - description: 'The name that needs to be fetched. Use user1 for testing. ' - required: true - schema: - type: string - responses: - '200': - description: successful operation - content: - application/json: - schema: - type: object - properties: - status: - type: string - data: - $ref: '#/components/schemas/User' - - '400': - description: fail - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - '404': - description: fail - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - patch: - tags: - - user - summary: Update a user - description: Only users with a TEACHER role can update the cohortId or role. Users with Students role can only update their own details. - operationId: userUpdate - security: - - bearerAuth: [] - parameters: - - name: id - in: path - description: 'The user id that needs to be updated' - required: true - schema: - type: string - requestBody: - description: The profile info - content: - application/json: - schema: - $ref: '#/components/schemas/UpdateUser' - responses: - '201': - description: Successful operation - content: - application/json: - schema: - $ref: '#/components/schemas/CreatedUser' - '401': - description: fail - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - /posts: - post: - tags: - - post - summary: Create post - description: This can only be done by the logged in user. - operationId: createPost - security: - - bearerAuth: [] - requestBody: - description: Created post object - content: - application/json: - schema: - type: object - properties: - content: - type: string - responses: - 201: - description: success - content: - application/json: - schema: - $ref: '#/components/schemas/Post' - 400: - description: fail - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - get: - tags: - - post - summary: Get all posts - description: get all posts - operationId: getPosts - security: - - bearerAuth: [] - responses: - '200': - description: Successful operation - content: - application/json: - schema: - $ref: '#/components/schemas/Posts' - '401': - description: fail - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - /logs: - post: - tags: - - log - summary: Create delivery log - description: This can only be done by an authorised teacher user. - operationId: createLog - security: - - bearerAuth: [] - requestBody: - description: Created log object - content: - application/json: - schema: - type: object - properties: - date: - type: string - cohortId: - type: integer - lines: - type: array - items: - type: object - properties: - content: - type: string - responses: - 201: - description: success - content: - application/json: - schema: - $ref: '#/components/schemas/Log' - '401': - description: Unauthorised - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - /cohorts: - post: - tags: - - cohort - summary: Create a cohort - description: This can only be done by the logged in user with role TEACHER. - operationId: createCohort - security: - - bearerAuth: [] - responses: - 201: - description: success - content: - application/json: - schema: - type: object - properties: - status: - type: string - data: - properties: - cohort: - $ref: '#/components/schemas/Cohort' - 400: - description: fail - content: - application/json: - schema: - $ref: '#/components/schemas/Error' - -components: - securitySchemes: - bearerAuth: - type: http - scheme: bearer - bearerFormat: JWT - schemas: - Post: - type: object - properties: - status: - type: string - data: - properties: - post: - properties: - id: - type: integer - content: - type: string - - Cohort: - type: object - properties: - id: - type: integer - createdAt: - type: string - format: string - updatedAt: - type: string - format: string - - AllUsers: - type: object - properties: - status: - type: string - data: - type: object - properties: - users: - type: array - items: - $ref: '#/components/schemas/User' - - User: - type: object - properties: - id: - type: integer - email: - type: string - role: - type: string - cohortId: - type: integer - firstName: - type: string - lastName: - type: string - bio: - type: string - githubUrl: - type: string - - CreateUser: - type: object - properties: - firstName: - type: string - lastName: - type: string - email: - type: string - bio: - type: string - githubUrl: - type: string - password: - type: string - - UpdateUser: - type: object - properties: - email: - type: string - password: - type: string - cohortId: - type: integer - role: - type: string - firstName: - type: string - lastName: - type: string - bio: - type: string - githubUrl: - type: string - - Posts: - type: object - properties: - status: - type: string - data: - type: object - properties: - posts: - type: array - items: - type: object - properties: - id: - type: integer - content: - type: string - createdAt: - type: string - format: string - updatedAt: - type: string - format: string - author: - type: object - properties: - id: - type: integer - cohortId: - type: integer - role: - type: string - firstName: - type: string - lastName: - type: string - bio: - type: string - githubUrl: - type: string - profileImageUrl: - type: string - - CreatedUser: - type: object - properties: - status: - type: string - example: success - data: - properties: - user: - properties: - id: - type: integer - email: - type: string - cohortId: - type: integer - role: - type: string - firstName: - type: string - lastName: - type: string - bio: - type: string - githubUrl: - type: string - login: - type: object - properties: - email: - type: string - password: - type: string - - loginRes: - type: object - properties: - status: - type: string - data: - properties: - token: - type: string - user: - properties: - id: - type: integer - email: - type: string - cohortId: - type: integer - role: - type: string - firstName: - type: string - lastName: - type: string - bio: - type: string - githubUrl: - type: string - Error: - type: object - properties: - status: - type: string - data: - properties: - error: - type: string - - Log: - type: object - properties: - status: - type: string - data: - properties: - log: - properties: - id: - type: integer - cohortId: - type: integer - date: - type: string - author: - type: object - properties: - id: - type: integer - firstName: - type: string - lastName: - type: string - lines: - type: array - items: - type: object - properties: - id: - type: integer - content: - type: string +openapi: 3.0.3 +info: + title: Team Dev Server API + description: |- + version: 1.0 + +servers: + - url: http://localhost:4000/ +tags: + - name: user + - name: post + - name: cohort + - name: log +paths: + /users: + post: + tags: + - user + summary: Create user + description: Create new user + operationId: createUser + requestBody: + description: User registration details + content: + application/json: + schema: + $ref: '#/components/schemas/CreateUser' + responses: + '201': + description: Created + content: + application/json: + schema: + $ref: '#/components/schemas/CreatedUser' + '400': + description: Invalid email/password supplied + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + get: + tags: + - user + summary: Get all users by first name if provided + description: '' + operationId: getAllUsers + security: + - bearerAuth: [] + parameters: + - name: firstName + in: query + description: Search all users by first name if provided (case-sensitive and exact string matches only) + schema: + type: string + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/AllUsers' + '400': + description: fail + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '404': + description: fail + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /login: + post: + tags: + - user + summary: Localhost Login + description: '' + operationId: loginUser + requestBody: + description: User login information + content: + application/json: + schema: + $ref: '#/components/schemas/login' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/loginRes' + + '400': + description: Invalid username/password supplied + + /users/{id}: + get: + tags: + - user + summary: Get user by user id + description: '' + operationId: getUserByID + security: + - bearerAuth: [] + parameters: + - name: id + in: path + description: 'The name that needs to be fetched. Use user1 for testing. ' + required: true + schema: + type: string + responses: + '200': + description: successful operation + content: + application/json: + schema: + type: object + properties: + status: + type: string + data: + $ref: '#/components/schemas/User' + + '400': + description: fail + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + '404': + description: fail + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + patch: + tags: + - user + summary: Update a user + description: Only users with a TEACHER role can update the cohortId or role. Users with Students role can only update their own details. + operationId: userUpdate + security: + - bearerAuth: [] + parameters: + - name: id + in: path + description: 'The user id that needs to be updated' + required: true + schema: + type: string + requestBody: + description: The profile info + content: + application/json: + schema: + $ref: '#/components/schemas/UpdateUser' + responses: + '201': + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/CreatedUser' + '401': + description: fail + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /posts: + post: + tags: + - post + summary: Create post + description: This can only be done by the logged in user. + operationId: createPost + security: + - bearerAuth: [] + requestBody: + description: Created post object + content: + application/json: + schema: + type: object + properties: + content: + type: string + responses: + 201: + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/Post' + 400: + description: fail + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + get: + tags: + - post + summary: Get all posts + description: get all posts + operationId: getPosts + security: + - bearerAuth: [] + responses: + '200': + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Posts' + '401': + description: fail + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /logs: + post: + tags: + - log + summary: Create delivery log + description: This can only be done by an authorised teacher user. + operationId: createLog + security: + - bearerAuth: [] + requestBody: + description: Created log object + content: + application/json: + schema: + type: object + properties: + date: + type: string + cohortId: + type: integer + lines: + type: array + items: + type: object + properties: + content: + type: string + responses: + 201: + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/Log' + '401': + description: Unauthorised + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + /cohorts: + post: + tags: + - cohort + summary: Create a cohort + description: This can only be done by the logged in user with role TEACHER. + operationId: createCohort + security: + - bearerAuth: [] + responses: + 201: + description: success + content: + application/json: + schema: + type: object + properties: + status: + type: string + data: + properties: + cohort: + $ref: '#/components/schemas/Cohort' + 400: + description: fail + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + +components: + securitySchemes: + bearerAuth: + type: http + scheme: bearer + bearerFormat: JWT + schemas: + Post: + type: object + properties: + status: + type: string + data: + properties: + post: + properties: + id: + type: integer + content: + type: string + + Cohort: + type: object + properties: + id: + type: integer + createdAt: + type: string + format: string + updatedAt: + type: string + format: string + + AllUsers: + type: object + properties: + status: + type: string + data: + type: object + properties: + users: + type: array + items: + $ref: '#/components/schemas/User' + + User: + type: object + properties: + id: + type: integer + email: + type: string + role: + type: string + cohortId: + type: integer + firstName: + type: string + lastName: + type: string + bio: + type: string + githubUrl: + type: string + + CreateUser: + type: object + properties: + firstName: + type: string + lastName: + type: string + email: + type: string + bio: + type: string + githubUrl: + type: string + password: + type: string + + UpdateUser: + type: object + properties: + email: + type: string + password: + type: string + cohortId: + type: integer + role: + type: string + firstName: + type: string + lastName: + type: string + bio: + type: string + githubUrl: + type: string + + Posts: + type: object + properties: + status: + type: string + data: + type: object + properties: + posts: + type: array + items: + type: object + properties: + id: + type: integer + content: + type: string + createdAt: + type: string + format: string + updatedAt: + type: string + format: string + author: + type: object + properties: + id: + type: integer + cohortId: + type: integer + role: + type: string + firstName: + type: string + lastName: + type: string + bio: + type: string + githubUrl: + type: string + profileImageUrl: + type: string + + CreatedUser: + type: object + properties: + status: + type: string + example: success + data: + properties: + user: + properties: + id: + type: integer + email: + type: string + cohortId: + type: integer + role: + type: string + firstName: + type: string + lastName: + type: string + bio: + type: string + githubUrl: + type: string + login: + type: object + properties: + email: + type: string + password: + type: string + + loginRes: + type: object + properties: + status: + type: string + data: + properties: + token: + type: string + user: + properties: + id: + type: integer + email: + type: string + cohortId: + type: integer + role: + type: string + firstName: + type: string + lastName: + type: string + bio: + type: string + githubUrl: + type: string + Error: + type: object + properties: + status: + type: string + data: + properties: + error: + type: string + + Log: + type: object + properties: + status: + type: string + data: + properties: + log: + properties: + id: + type: integer + cohortId: + type: integer + date: + type: string + author: + type: object + properties: + id: + type: integer + firstName: + type: string + lastName: + type: string + lines: + type: array + items: + type: object + properties: + id: + type: integer + content: + type: string From 300711867e0e9bcf460fbdd124894f752a584a26 Mon Sep 17 00:00:00 2001 From: Ingeborg Brommeland Austeid Date: Tue, 29 Oct 2024 13:54:40 +0100 Subject: [PATCH 18/32] adds updated openapi.yml with 400 response to patch in /users --- docs/openapi.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/openapi.yml b/docs/openapi.yml index 8dd81e7b..50533123 100644 --- a/docs/openapi.yml +++ b/docs/openapi.yml @@ -170,6 +170,12 @@ paths: application/json: schema: $ref: '#/components/schemas/Error' + '400': + description: Invalid email/password supplied + content: + application/json: + schema: + $ref: '#/components/schemas/Error' /posts: post: tags: From d4ac66c92b22b864f04fd1a6a365cf5aff2c46ba Mon Sep 17 00:00:00 2001 From: tvaltn Date: Tue, 29 Oct 2024 14:41:08 +0100 Subject: [PATCH 19/32] moved request modification to middleware --- src/controllers/user.js | 15 ++++----------- src/middleware/auth.js | 14 +++++++++++--- 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/src/controllers/user.js b/src/controllers/user.js index 0333a7e8..9e7d3ec7 100644 --- a/src/controllers/user.js +++ b/src/controllers/user.js @@ -59,18 +59,11 @@ export const getAll = async (req, res) => { export const updateById = async (req, res) => { const id = parseInt(req.params.id) const userToUpdate = await User.fromJson(req.body) - userToUpdate.id = id - // Update cohortId and role to userToUpdate (only if logged in role is Teacher) - // otherwise, keep the existing values of the user - if (req.user.role === 'TEACHER') { - userToUpdate.cohortId = parseInt(req.body.cohortId) - userToUpdate.role = req.body.role - } else { - const existingUser = await User.findById(id) - userToUpdate.cohortId = existingUser.cohortId - userToUpdate.role = existingUser.role - } + // Add id, cohortId and role (could be done in the domain) + userToUpdate.id = id + userToUpdate.cohortId = req.body.cohortId + userToUpdate.role = req.body.role try { if (!userToUpdate.cohortId) { diff --git a/src/middleware/auth.js b/src/middleware/auth.js index 1e3f6f10..2d4f505b 100644 --- a/src/middleware/auth.js +++ b/src/middleware/auth.js @@ -27,11 +27,19 @@ export async function validateLoggedInUser(req, res, next) { return sendMessageResponse(res, 500, 'Unable to verify user') } - if (req.user.id !== parseInt(req.params.id)) { - return next() + 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 + } } - res.locals.skipTeacherValidation = true next() } From b624f5a3874685000c4d21de889bb089508f8ec0 Mon Sep 17 00:00:00 2001 From: tvaltn Date: Tue, 29 Oct 2024 15:36:27 +0100 Subject: [PATCH 20/32] added new user fields to update endpoint --- src/controllers/user.js | 2 ++ src/domain/user.js | 7 ++++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/controllers/user.js b/src/controllers/user.js index 173f6e9c..72421118 100644 --- a/src/controllers/user.js +++ b/src/controllers/user.js @@ -69,6 +69,8 @@ export const updateById = async (req, res) => { userToUpdate.cohortId = req.body.cohortId userToUpdate.role = req.body.role + console.log(userToUpdate) + try { if (!userToUpdate.cohortId) { return sendDataResponse(res, 400, { cohort_id: 'Cohort ID is required' }) diff --git a/src/domain/user.js b/src/domain/user.js index 634842b7..21af5fe1 100644 --- a/src/domain/user.js +++ b/src/domain/user.js @@ -179,7 +179,12 @@ export default class User { firstName: this.firstName, lastName: this.lastName, bio: this.bio, - githubUrl: this.githubUrl + githubUrl: this.githubUrl, + username: this.username, + mobile: this.mobile, + specialism: this.specialism, + startDate: this.startDate, + endDate: this.endDate } } }, From 7d9aced26c504398e488f5f421b4bf636b8cae33 Mon Sep 17 00:00:00 2001 From: TMajlu Date: Tue, 29 Oct 2024 15:54:52 +0100 Subject: [PATCH 21/32] Added email-validation in the middleware/user.js file. --- src/middleware/user.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/middleware/user.js b/src/middleware/user.js index 756db248..07accf30 100644 --- a/src/middleware/user.js +++ b/src/middleware/user.js @@ -1,6 +1,24 @@ 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 }) + } + const validatePassword = (password) => { const minLength = 8 const hasUpperCase = /[A-Z]/.test(password) From fd865b337c1f039353a4f79ee0cf21ee83f2809d Mon Sep 17 00:00:00 2001 From: Tuva Aarseth Date: Wed, 30 Oct 2024 09:40:36 +0100 Subject: [PATCH 22/32] Resolved merge conflict --- prisma/migrations/20241030083020_new_user_values/migration.sql | 1 + prisma/seed.js | 2 ++ 2 files changed, 3 insertions(+) create mode 100644 prisma/migrations/20241030083020_new_user_values/migration.sql 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/seed.js b/prisma/seed.js index d869c088..0d22470c 100644 --- a/prisma/seed.js +++ b/prisma/seed.js @@ -17,6 +17,7 @@ async function seed() { 'Software Engineering', // specialism new Date('2023-01-01'), // startDate new Date('2023-12-31'), + null, 'STUDENT', 'Testpassword1!' ) @@ -32,6 +33,7 @@ async function seed() { 'Teaching', new Date('2022-01-01'), new Date('2022-12-31'), + null, 'TEACHER', 'Testpassword1!' ) From 339e5c1b6139182aecb48e81c20ef98826d880ff Mon Sep 17 00:00:00 2001 From: eyvmal Date: Tue, 29 Oct 2024 12:40:20 +0100 Subject: [PATCH 23/32] copypaste progress from issue 5 --- docs/openapi.yml | 53 +++++++++++++++++++++++++++++++++++++++++ src/controllers/post.js | 22 +++++++++++++++++ src/domain/post.js | 40 +++++++++++++++++++++++++++++++ src/routes/post.js | 3 ++- 4 files changed, 117 insertions(+), 1 deletion(-) create mode 100644 src/domain/post.js diff --git a/docs/openapi.yml b/docs/openapi.yml index 27d5a6f4..417c15fc 100644 --- a/docs/openapi.yml +++ b/docs/openapi.yml @@ -225,6 +225,53 @@ paths: application/json: schema: $ref: '#/components/schemas/Error' + /posts/{id}: + 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' /logs: post: tags: @@ -494,6 +541,12 @@ components: profileImage: type: string + UpdatePost: + type: object + properties: + content: + type: string + CreatedUser: type: object properties: diff --git a/src/controllers/post.js b/src/controllers/post.js index 7b168039..959ea83a 100644 --- a/src/controllers/post.js +++ b/src/controllers/post.js @@ -1,4 +1,5 @@ import { sendDataResponse } from '../utils/responses.js' +import { getPostById, updateContentById } from '../domain/post.js' export const create = async (req, res) => { const { content } = req.body @@ -26,3 +27,24 @@ export const getAll = async (req, res) => { ] }) } + +export const updateById = async (req, res) => { + const { id } = req.params + const { content } = req.body + + try { + const post = await getPostById(Number(id)) + if (post) { + const updatedPost = await 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' + }) + } +} diff --git a/src/domain/post.js b/src/domain/post.js new file mode 100644 index 00000000..940c6d7e --- /dev/null +++ b/src/domain/post.js @@ -0,0 +1,40 @@ +import dbClient from '../utils/dbClient.js' + +export class Post { + constructor(id = null) { + this.id = id + } + + toJSON() { + return { + post: { + id: this.id + } + } + } +} + +export async function getPostById(id) { + try { + const post = await dbClient.post.findUnique({ + where: { id: id } + }) + return post + } catch (error) { + console.error('Error fetching post by ID:', error) + return null + } +} + +export async function updateContentById(id, content) { + try { + const post = await dbClient.post.update({ + where: { id: id }, + data: { content: content } + }) + return post + } catch (error) { + console.error('Error updating post content by ID:', error) + return null + } +} diff --git a/src/routes/post.js b/src/routes/post.js index a7fbbfb3..9fa2cfee 100644 --- a/src/routes/post.js +++ b/src/routes/post.js @@ -1,10 +1,11 @@ import { Router } from 'express' -import { create, getAll } from '../controllers/post.js' +import { create, getAll, updateById } from '../controllers/post.js' import { validateAuthentication } from '../middleware/auth.js' const router = Router() router.post('/', validateAuthentication, create) router.get('/', validateAuthentication, getAll) +router.patch('/:id', validateAuthentication, updateById) export default router From 7a9f548a6298d480a77222dfca3a5932e909281a Mon Sep 17 00:00:00 2001 From: eyvmal Date: Tue, 29 Oct 2024 12:43:32 +0100 Subject: [PATCH 24/32] modify getAll to fetch from database --- src/controllers/post.js | 23 ++++++++--------------- src/domain/post.js | 10 ++++++++++ 2 files changed, 18 insertions(+), 15 deletions(-) diff --git a/src/controllers/post.js b/src/controllers/post.js index 959ea83a..e60e4c9c 100644 --- a/src/controllers/post.js +++ b/src/controllers/post.js @@ -1,5 +1,5 @@ import { sendDataResponse } from '../utils/responses.js' -import { getPostById, updateContentById } from '../domain/post.js' +import { getAllPosts, getPostById, updateContentById } from '../domain/post.js' export const create = async (req, res) => { const { content } = req.body @@ -12,20 +12,13 @@ export const create = async (req, res) => { } 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 posts = await getAllPosts() + if (!posts) { + return sendDataResponse(res, 500, { + content: 'Internal server error' + }) + } + return sendDataResponse(res, 200, { posts }) } export const updateById = async (req, res) => { diff --git a/src/domain/post.js b/src/domain/post.js index 940c6d7e..720efba2 100644 --- a/src/domain/post.js +++ b/src/domain/post.js @@ -14,6 +14,16 @@ export class Post { } } +export async function getAllPosts() { + try { + const posts = await dbClient.post.findMany() + return posts + } catch (error) { + console.error('Error fetching all posts:', error) + return null + } +} + export async function getPostById(id) { try { const post = await dbClient.post.findUnique({ From a3eb2afe3009f92b4eb6276ef650f90c094daaea Mon Sep 17 00:00:00 2001 From: eyvmal Date: Tue, 29 Oct 2024 12:48:49 +0100 Subject: [PATCH 25/32] add getById endpoint --- docs/openapi.yml | 40 ++++++++++++++++++++++++++++++++++++++++ src/controllers/post.js | 13 +++++++++++++ src/routes/post.js | 3 ++- 3 files changed, 55 insertions(+), 1 deletion(-) diff --git a/docs/openapi.yml b/docs/openapi.yml index 417c15fc..9e460167 100644 --- a/docs/openapi.yml +++ b/docs/openapi.yml @@ -226,6 +226,46 @@ paths: 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 diff --git a/src/controllers/post.js b/src/controllers/post.js index e60e4c9c..2be25adc 100644 --- a/src/controllers/post.js +++ b/src/controllers/post.js @@ -21,6 +21,19 @@ export const getAll = async (req, res) => { return sendDataResponse(res, 200, { posts }) } +export const getById = async (req, res) => { + const { id } = req.params + const post = await getPostById(Number(id)) + + if (!post) { + return sendDataResponse(res, 404, { + content: `Post with id ${id} not found` + }) + } + + return sendDataResponse(res, 200, { post }) +} + export const updateById = async (req, res) => { const { id } = req.params const { content } = req.body diff --git a/src/routes/post.js b/src/routes/post.js index 9fa2cfee..6b84c714 100644 --- a/src/routes/post.js +++ b/src/routes/post.js @@ -1,11 +1,12 @@ import { Router } from 'express' -import { create, getAll, updateById } from '../controllers/post.js' +import { create, getAll, updateById, getById } from '../controllers/post.js' import { validateAuthentication } from '../middleware/auth.js' const router = Router() router.post('/', validateAuthentication, create) router.get('/', validateAuthentication, getAll) +router.get('/:id', validateAuthentication, getById) router.patch('/:id', validateAuthentication, updateById) export default router From cf1c1e4c9260566c7cd9132d70042400799f915d Mon Sep 17 00:00:00 2001 From: eyvmal Date: Tue, 29 Oct 2024 12:54:21 +0100 Subject: [PATCH 26/32] add delete endpoint --- docs/openapi.yml | 40 ++++++++++++++++++++++++++++++++++++++++ src/controllers/post.js | 27 ++++++++++++++++++++++++++- src/domain/post.js | 12 ++++++++++++ src/routes/post.js | 9 ++++++++- 4 files changed, 86 insertions(+), 2 deletions(-) diff --git a/docs/openapi.yml b/docs/openapi.yml index 9e460167..0aeee602 100644 --- a/docs/openapi.yml +++ b/docs/openapi.yml @@ -312,6 +312,46 @@ paths: 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: + $ref: '#/components/schemas/Error' /logs: post: tags: diff --git a/src/controllers/post.js b/src/controllers/post.js index 2be25adc..f6e24ebe 100644 --- a/src/controllers/post.js +++ b/src/controllers/post.js @@ -1,5 +1,10 @@ import { sendDataResponse } from '../utils/responses.js' -import { getAllPosts, getPostById, updateContentById } from '../domain/post.js' +import { + getAllPosts, + getPostById, + updateContentById, + deletePostById +} from '../domain/post.js' export const create = async (req, res) => { const { content } = req.body @@ -54,3 +59,23 @@ export const updateById = async (req, res) => { }) } } + +export const deleteById = async (req, res) => { + const { id } = req.params + + try { + const post = await getPostById(Number(id)) + if (post) { + const deletedPost = await 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/domain/post.js b/src/domain/post.js index 720efba2..b9bb32a1 100644 --- a/src/domain/post.js +++ b/src/domain/post.js @@ -48,3 +48,15 @@ export async function updateContentById(id, content) { return null } } + +export async function deletePostById(id) { + try { + const post = await dbClient.post.delete({ + where: { id: id } + }) + return post + } catch (error) { + console.error('Error deleting post by ID:', error) + return null + } +} diff --git a/src/routes/post.js b/src/routes/post.js index 6b84c714..38f2b81b 100644 --- a/src/routes/post.js +++ b/src/routes/post.js @@ -1,5 +1,11 @@ import { Router } from 'express' -import { create, getAll, updateById, getById } from '../controllers/post.js' +import { + create, + getAll, + updateById, + getById, + deleteById +} from '../controllers/post.js' import { validateAuthentication } from '../middleware/auth.js' const router = Router() @@ -8,5 +14,6 @@ router.post('/', validateAuthentication, create) router.get('/', validateAuthentication, getAll) router.get('/:id', validateAuthentication, getById) router.patch('/:id', validateAuthentication, updateById) +router.delete('/:id', validateAuthentication, deleteById) export default router From 699b286db15e2c815d64aa2092668982a60a9e3b Mon Sep 17 00:00:00 2001 From: eyvmal Date: Tue, 29 Oct 2024 13:20:25 +0100 Subject: [PATCH 27/32] update create post method to connect to database --- docs/openapi.yml | 2 ++ src/controllers/post.js | 16 ++++++++++++++-- src/domain/post.js | 12 ++++++++++++ 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/docs/openapi.yml b/docs/openapi.yml index 0aeee602..ed8373fa 100644 --- a/docs/openapi.yml +++ b/docs/openapi.yml @@ -191,6 +191,8 @@ paths: properties: content: type: string + userid: + type: integer responses: 201: description: success diff --git a/src/controllers/post.js b/src/controllers/post.js index f6e24ebe..aa997ac1 100644 --- a/src/controllers/post.js +++ b/src/controllers/post.js @@ -1,19 +1,31 @@ import { sendDataResponse } from '../utils/responses.js' import { + createPost, getAllPosts, getPostById, updateContentById, deletePostById } from '../domain/post.js' +import User from '../domain/user.js' export const create = async (req, res) => { - const { content } = req.body + const { content, userid } = req.body + const user = await User.findById(userid) if (!content) { return sendDataResponse(res, 400, { content: 'Must provide content' }) } - return sendDataResponse(res, 201, { post: { id: 1, content } }) + try { + const post = await 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) => { diff --git a/src/domain/post.js b/src/domain/post.js index b9bb32a1..baaa3a9b 100644 --- a/src/domain/post.js +++ b/src/domain/post.js @@ -14,6 +14,18 @@ export class Post { } } +export async function createPost(content, user) { + try { + const post = await dbClient.post.create({ + data: { content: content, userId: user.id } + }) + return post + } catch (error) { + console.error('Error creating post:', error) + return null + } +} + export async function getAllPosts() { try { const posts = await dbClient.post.findMany() From 7e32f23ab0b1be3170389e4f756b697c8695aafb Mon Sep 17 00:00:00 2001 From: eyvmal Date: Tue, 29 Oct 2024 13:49:42 +0100 Subject: [PATCH 28/32] reformat domain- and controller-file of post to match the user-files structure --- src/controllers/post.js | 22 ++++++--------- src/domain/post.js | 60 ++++++++++++----------------------------- 2 files changed, 25 insertions(+), 57 deletions(-) diff --git a/src/controllers/post.js b/src/controllers/post.js index aa997ac1..0dc93868 100644 --- a/src/controllers/post.js +++ b/src/controllers/post.js @@ -1,11 +1,5 @@ import { sendDataResponse } from '../utils/responses.js' -import { - createPost, - getAllPosts, - getPostById, - updateContentById, - deletePostById -} from '../domain/post.js' +import Post from '../domain/post.js' import User from '../domain/user.js' export const create = async (req, res) => { @@ -17,7 +11,7 @@ export const create = async (req, res) => { } try { - const post = await createPost(content, user) + const post = await Post.createPost(content, user) if (post) { return sendDataResponse(res, 201, { post }) } else { @@ -29,7 +23,7 @@ export const create = async (req, res) => { } export const getAll = async (req, res) => { - const posts = await getAllPosts() + const posts = await Post.getAllPosts() if (!posts) { return sendDataResponse(res, 500, { content: 'Internal server error' @@ -40,7 +34,7 @@ export const getAll = async (req, res) => { export const getById = async (req, res) => { const { id } = req.params - const post = await getPostById(Number(id)) + const post = await Post.getPostById(Number(id)) if (!post) { return sendDataResponse(res, 404, { @@ -56,9 +50,9 @@ export const updateById = async (req, res) => { const { content } = req.body try { - const post = await getPostById(Number(id)) + const post = await Post.getPostById(Number(id)) if (post) { - const updatedPost = await updateContentById(Number(id), content) + const updatedPost = await Post.updateContentById(Number(id), content) return sendDataResponse(res, 200, { post: updatedPost }) } else { return sendDataResponse(res, 404, { @@ -76,9 +70,9 @@ export const deleteById = async (req, res) => { const { id } = req.params try { - const post = await getPostById(Number(id)) + const post = await Post.getPostById(Number(id)) if (post) { - const deletedPost = await deletePostById(Number(id)) + const deletedPost = await Post.deletePostById(Number(id)) return sendDataResponse(res, 200, { post: deletedPost }) } else { return sendDataResponse(res, 404, { diff --git a/src/domain/post.js b/src/domain/post.js index baaa3a9b..b69aa4d7 100644 --- a/src/domain/post.js +++ b/src/domain/post.js @@ -1,6 +1,6 @@ import dbClient from '../utils/dbClient.js' -export class Post { +export default class Post { constructor(id = null) { this.id = id } @@ -8,67 +8,41 @@ export class Post { toJSON() { return { post: { - id: this.id + id: this.id, + content: this.content, + userId: this.userId } } } -} -export async function createPost(content, user) { - try { - const post = await dbClient.post.create({ + static async createPost(content, user) { + return dbClient.post.create({ data: { content: content, userId: user.id } }) - return post - } catch (error) { - console.error('Error creating post:', error) - return null } -} -export async function getAllPosts() { - try { - const posts = await dbClient.post.findMany() - return posts - } catch (error) { - console.error('Error fetching all posts:', error) - return null + static async getAllPosts() { + return dbClient.post.findMany() } -} -export async function getPostById(id) { - try { - const post = await dbClient.post.findUnique({ - where: { id: id } + static async getPostById(id) { + return dbClient.post.findUnique({ + where: { + id: id + } }) - return post - } catch (error) { - console.error('Error fetching post by ID:', error) - return null } -} -export async function updateContentById(id, content) { - try { - const post = await dbClient.post.update({ + static async updateContentById(id, content) { + return dbClient.post.update({ where: { id: id }, data: { content: content } }) - return post - } catch (error) { - console.error('Error updating post content by ID:', error) - return null } -} -export async function deletePostById(id) { - try { - const post = await dbClient.post.delete({ + static async deletePostById(id) { + return dbClient.post.delete({ where: { id: id } }) - return post - } catch (error) { - console.error('Error deleting post by ID:', error) - return null } } From ddad8049e58696d4256d4b27451007e4e717519f Mon Sep 17 00:00:00 2001 From: eyvmal Date: Wed, 30 Oct 2024 10:03:39 +0100 Subject: [PATCH 29/32] remove userid from create endpoint --- docs/openapi.yml | 20 +++++++++++++++----- src/controllers/post.js | 4 ++-- 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/docs/openapi.yml b/docs/openapi.yml index ed8373fa..9a064a1d 100644 --- a/docs/openapi.yml +++ b/docs/openapi.yml @@ -191,8 +191,6 @@ paths: properties: content: type: string - userid: - type: integer responses: 201: description: success @@ -200,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: @@ -222,7 +226,13 @@ 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: diff --git a/src/controllers/post.js b/src/controllers/post.js index 0dc93868..6fab24e7 100644 --- a/src/controllers/post.js +++ b/src/controllers/post.js @@ -3,8 +3,8 @@ import Post from '../domain/post.js' import User from '../domain/user.js' export const create = async (req, res) => { - const { content, userid } = req.body - const user = await User.findById(userid) + const { content } = req.body + const user = await User.findById(req.user.id) if (!content) { return sendDataResponse(res, 400, { content: 'Must provide content' }) From 46814e40540fd344ea7550c5ed07816b113db0a2 Mon Sep 17 00:00:00 2001 From: eyvmal Date: Wed, 30 Oct 2024 11:40:24 +0100 Subject: [PATCH 30/32] add more fields to return on post calls --- src/domain/post.js | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/src/domain/post.js b/src/domain/post.js index b69aa4d7..94a0e6a3 100644 --- a/src/domain/post.js +++ b/src/domain/post.js @@ -22,17 +22,52 @@ export default class Post { } static async getAllPosts() { - return dbClient.post.findMany() + return dbClient.post.findMany({ + include: { + user: { + select: { + id: true, + role: true, + cohortId: true, + profile: { + select: { + firstName: true, + lastName: true, + specialism: true + } + } + } + } + } + }) } static async getPostById(id) { return dbClient.post.findUnique({ where: { id: id + }, + include: { + user: { + select: { + id: true, + role: true, + cohortId: true, + profile: { + select: { + firstName: true, + lastName: true, + specialism: true + } + } + } + } } }) } + // firstName lastName rolle specialism + static async updateContentById(id, content) { return dbClient.post.update({ where: { id: id }, From fb2053e4ce9a3d471d99a84d3a0e79ade4600824 Mon Sep 17 00:00:00 2001 From: eyvmal Date: Wed, 30 Oct 2024 14:04:51 +0100 Subject: [PATCH 31/32] update post model in database and return value of post in endpoints --- .../migration.sql | 3 ++ prisma/schema.prisma | 2 + src/controllers/post.js | 47 ++++++++++++++++++- src/domain/post.js | 26 ++-------- 4 files changed, 54 insertions(+), 24 deletions(-) create mode 100644 prisma/migrations/20241030125841_add_created_updated_at_columns_to_post/migration.sql 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/schema.prisma b/prisma/schema.prisma index 7ccee408..1f331713 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -55,6 +55,8 @@ model Post { content String userId Int user User @relation(fields: [userId], references: [id]) + createdAt DateTime @default(now()) + updatedAt DateTime @default(now()) } model DeliveryLog { diff --git a/src/controllers/post.js b/src/controllers/post.js index 6fab24e7..09fcaee6 100644 --- a/src/controllers/post.js +++ b/src/controllers/post.js @@ -29,7 +29,28 @@ export const getAll = async (req, res) => { content: 'Internal server error' }) } - return sendDataResponse(res, 200, { posts }) + const formattedPosts = posts.map((post) => ({ + id: post.id, + content: post.content, + createdAt: post.createdAt, + updatedAt: post.updatedAt, + author: { + id: post.user.id, + cohortId: post.user.cohortId, + role: post.user.role, + firstName: post.user.profile.firstName, + lastName: post.user.profile.lastName, + bio: post.user.profile.bio, + githubUrl: post.user.profile.githubUrl, + username: post.user.profile.username, + mobile: post.user.profile.mobile, + specialism: post.user.profile.specialism, + startDate: post.user.profile.startDate, + endDate: post.user.profile.endDate, + profileImage: post.user.profile.profileImage + } + })) + return sendDataResponse(res, 200, { formattedPosts }) } export const getById = async (req, res) => { @@ -42,7 +63,29 @@ export const getById = async (req, res) => { }) } - return sendDataResponse(res, 200, { post }) + const formattedPost = { + id: post.id, + content: post.content, + createdAt: post.createdAt, + updatedAt: post.updatedAt, + author: { + id: post.user.id, + cohortId: post.user.cohortId, + role: post.user.role, + firstName: post.user.profile.firstName, + lastName: post.user.profile.lastName, + bio: post.user.profile.bio, + githubUrl: post.user.profile.githubUrl, + username: post.user.profile.username, + mobile: post.user.profile.mobile, + specialism: post.user.profile.specialism, + startDate: post.user.profile.startDate, + endDate: post.user.profile.endDate, + profileImage: post.user.profile.profileImage + } + } + + return sendDataResponse(res, 200, { post: formattedPost }) } export const updateById = async (req, res) => { diff --git a/src/domain/post.js b/src/domain/post.js index 94a0e6a3..21b0d308 100644 --- a/src/domain/post.js +++ b/src/domain/post.js @@ -25,17 +25,8 @@ export default class Post { return dbClient.post.findMany({ include: { user: { - select: { - id: true, - role: true, - cohortId: true, - profile: { - select: { - firstName: true, - lastName: true, - specialism: true - } - } + include: { + profile: true } } } @@ -49,17 +40,8 @@ export default class Post { }, include: { user: { - select: { - id: true, - role: true, - cohortId: true, - profile: { - select: { - firstName: true, - lastName: true, - specialism: true - } - } + include: { + profile: true } } } From f18bc19f9fffdf99c2687becbffbcf6c7676db87 Mon Sep 17 00:00:00 2001 From: eyvmal Date: Wed, 30 Oct 2024 14:30:17 +0100 Subject: [PATCH 32/32] reformat toJSON and names --- src/controllers/post.js | 53 ++++-------------------------- src/domain/post.js | 71 ++++++++++++++++++++++++++++++----------- 2 files changed, 59 insertions(+), 65 deletions(-) diff --git a/src/controllers/post.js b/src/controllers/post.js index 09fcaee6..4500634e 100644 --- a/src/controllers/post.js +++ b/src/controllers/post.js @@ -23,34 +23,15 @@ export const create = async (req, res) => { } export const getAll = async (req, res) => { - const posts = await Post.getAllPosts() - if (!posts) { + const postsUnformatted = await Post.getAllPosts() + if (!postsUnformatted) { return sendDataResponse(res, 500, { content: 'Internal server error' }) } - const formattedPosts = posts.map((post) => ({ - id: post.id, - content: post.content, - createdAt: post.createdAt, - updatedAt: post.updatedAt, - author: { - id: post.user.id, - cohortId: post.user.cohortId, - role: post.user.role, - firstName: post.user.profile.firstName, - lastName: post.user.profile.lastName, - bio: post.user.profile.bio, - githubUrl: post.user.profile.githubUrl, - username: post.user.profile.username, - mobile: post.user.profile.mobile, - specialism: post.user.profile.specialism, - startDate: post.user.profile.startDate, - endDate: post.user.profile.endDate, - profileImage: post.user.profile.profileImage - } - })) - return sendDataResponse(res, 200, { formattedPosts }) + + const posts = postsUnformatted.map((post) => post.toJSON()) + return sendDataResponse(res, 200, { posts }) } export const getById = async (req, res) => { @@ -63,29 +44,7 @@ export const getById = async (req, res) => { }) } - const formattedPost = { - id: post.id, - content: post.content, - createdAt: post.createdAt, - updatedAt: post.updatedAt, - author: { - id: post.user.id, - cohortId: post.user.cohortId, - role: post.user.role, - firstName: post.user.profile.firstName, - lastName: post.user.profile.lastName, - bio: post.user.profile.bio, - githubUrl: post.user.profile.githubUrl, - username: post.user.profile.username, - mobile: post.user.profile.mobile, - specialism: post.user.profile.specialism, - startDate: post.user.profile.startDate, - endDate: post.user.profile.endDate, - profileImage: post.user.profile.profileImage - } - } - - return sendDataResponse(res, 200, { post: formattedPost }) + return sendDataResponse(res, 200, { post: post.toJSON() }) } export const updateById = async (req, res) => { diff --git a/src/domain/post.js b/src/domain/post.js index 21b0d308..0f992f10 100644 --- a/src/domain/post.js +++ b/src/domain/post.js @@ -1,16 +1,40 @@ import dbClient from '../utils/dbClient.js' export default class Post { - constructor(id = null) { + constructor( + id = null, + content = '', + user = null, + createdAt = null, + updatedAt = null + ) { this.id = id + this.content = content + this.user = user + this.createdAt = createdAt + this.updatedAt = updatedAt } toJSON() { return { - post: { - id: this.id, - content: this.content, - userId: this.userId + 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 } } } @@ -22,34 +46,45 @@ export default class Post { } static async getAllPosts() { - return dbClient.post.findMany({ + const posts = await dbClient.post.findMany({ include: { user: { - include: { - profile: true - } + include: { profile: true } } } }) + return posts.map( + (post) => + new Post( + post.id, + post.content, + post.user, + post.createdAt, + post.updatedAt + ) + ) } static async getPostById(id) { - return dbClient.post.findUnique({ - where: { - id: id - }, + const post = await dbClient.post.findUnique({ + where: { id }, include: { user: { - include: { - profile: true - } + include: { profile: true } } } }) + return post + ? new Post( + post.id, + post.content, + post.user, + post.createdAt, + post.updatedAt + ) + : null } - // firstName lastName rolle specialism - static async updateContentById(id, content) { return dbClient.post.update({ where: { id: id },