boolean-uk / team-dev-server-ex-2410-team3

0 stars 0 forks source link

API endpoint - PUT: Change user from student to teacher #5

Open sebgro98 opened 1 month ago

sebgro98 commented 1 month ago

Create a PUT endpoint with the routing ('/changeUserRole') that asynchronously calls a function called changeUserRole. The changeUserRole function should find the user by their ID in the database and update their role from STUDENT to TEACHER.

The prisma model looks like:

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[]
}

The user API spec model looks like:

{
  token: "string",
  user: {
    id: 0,
    email: "string",
    cohortId: 0,
    role: "string",
    firstName: "string",
    lastName: "string",
    bio: "string",
    githubUrl: "string"
  }
}

The endpoint returns a response of 201 with the JSON-formatted user if the operation is successful and a response of 401 if the operation fails. The function also returns 401 if the logged in user attempting to change another user's role to teacher is not a teacher using validateTeacherRole which returns false if the logged in user is a student and true if the logged in user is a teacher.

app.put('/changeUserRole', async (req, res) => {
  const { userId } = req.body;
  if(!validateTeacherRole(UserID)){
     res.status(401).json({
      status: 'fail',
      message: "Only a teacher can change a student's role to teacher"
  }
  try {
    const updatedUser = await prisma.user.update({
      where: { id: userId },
      data: { role: 'TEACHER' }
    })
    res.status(201).json({
      status: 'success',
      data: {
        user: updatedUser
      }
    })
  } catch (err) {
    res.status(401).json({
      status: 'fail',
      message: err.message
    })
  }
})
sebgro98 commented 1 month ago

Behöver vi någon validation som kollar att det är en Teacher som gjort requesten?

sebgro98 commented 1 month ago

Approved

amos1969 commented 1 month ago

Approved