From 6e6bd285afb6a9c55795aee454ce470a666b220a Mon Sep 17 00:00:00 2001
From: Bartha Maxime <231026@umons.ac.be>
Date: Sun, 17 Mar 2024 02:15:08 +0100
Subject: [PATCH] added security to the post of course and GET /courses

---
 .../Clyde/EndPoints/CourseController.java         | 15 ++++++++++++++-
 .../herisson/Clyde/Services/CourseService.java    |  8 ++++++++
 2 files changed, 22 insertions(+), 1 deletion(-)

diff --git a/backend/src/main/java/ovh/herisson/Clyde/EndPoints/CourseController.java b/backend/src/main/java/ovh/herisson/Clyde/EndPoints/CourseController.java
index ebfa730..60e7e1e 100644
--- a/backend/src/main/java/ovh/herisson/Clyde/EndPoints/CourseController.java
+++ b/backend/src/main/java/ovh/herisson/Clyde/EndPoints/CourseController.java
@@ -40,6 +40,15 @@ public class CourseController {
         return new ResponseEntity<>(foundCourse, HttpStatus.OK);
     }
 
+    @GetMapping("/courses")
+    public ResponseEntity<Iterable<Course>> getAllCourses(@RequestHeader("Authorization") String token){
+        if (authServ.isNotIn(new Role[]{Role.Admin,Role.Secretary},token))
+            return new UnauthorizedResponse<>(null);
+
+
+        return new ResponseEntity<>(courseServ.findAll(),HttpStatus.OK);
+    }
+
 
     @PostMapping("/course")
     public ResponseEntity<Course> postCourse(@RequestHeader("Authorization") String token,
@@ -49,7 +58,11 @@ public class CourseController {
         if (authServ.isNotIn(new Role[]{Role.Secretary,Role.Admin},token))
             return new UnauthorizedResponse<>(null);
 
-        return new ResponseEntity<>(courseServ.save(course), HttpStatus.CREATED);
+        Course createdCourse = courseServ.save(course);
+        if (createdCourse == null)
+            return new ResponseEntity<>(null,HttpStatus.BAD_REQUEST);
+
+        return new ResponseEntity<>(createdCourse, HttpStatus.CREATED);
     }
 
 
diff --git a/backend/src/main/java/ovh/herisson/Clyde/Services/CourseService.java b/backend/src/main/java/ovh/herisson/Clyde/Services/CourseService.java
index abfa6ae..bdb9ae8 100644
--- a/backend/src/main/java/ovh/herisson/Clyde/Services/CourseService.java
+++ b/backend/src/main/java/ovh/herisson/Clyde/Services/CourseService.java
@@ -17,6 +17,8 @@ public class CourseService {
     }
 
     public Course save(Course course){
+        if (course.getOwner().getRole() != Role.Teacher)
+            return null;
         return courseRepo.save(course);
     }
 
@@ -24,6 +26,11 @@ public class CourseService {
         return courseRepo.findById(id);
     }
 
+
+    public Iterable<Course> findAll() {
+        return courseRepo.findAll();
+    }
+
     public boolean modifyData(long id, Map<String, Object> updates, Role role) {
         Course target = courseRepo.findById(id);
 
@@ -62,4 +69,5 @@ public class CourseService {
         courseRepo.save(target);
         return true;
     }
+
 }