1
0
forked from PGL/Clyde

cleaned all controllers

This commit is contained in:
Bartha Maxime 2024-03-16 19:13:57 +01:00
parent 069466ef5f
commit 97b57b361d
16 changed files with 181 additions and 126 deletions

View File

@ -30,7 +30,6 @@ public class ApplicationsController {
*/ */
@GetMapping("/apps") @GetMapping("/apps")
public ResponseEntity<Iterable<Applications>> getAuthorizedApps(@RequestHeader("Authorization") String token){ public ResponseEntity<Iterable<Applications>> getAuthorizedApps(@RequestHeader("Authorization") String token){
return new ResponseEntity<>(getAuthorizedApplications(token), HttpStatus.OK); return new ResponseEntity<>(getAuthorizedApplications(token), HttpStatus.OK);
} }
@ -46,24 +45,29 @@ public class ApplicationsController {
public ArrayList<Applications> getAuthorizedApplications(String token){ public ArrayList<Applications> getAuthorizedApplications(String token){
ArrayList<Applications> authorizedApps = new ArrayList<>(); ArrayList<Applications> authorizedApps = new ArrayList<>();
//if unAuthed
authorizedApps.add(Applications.Login); authorizedApps.add(Applications.Login);
authorizedApps.add(Applications.Profile);
User user = authServ.getUserFromToken(token); User user = authServ.getUserFromToken(token);
if(user == null) if(user == null)
return authorizedApps; return authorizedApps;
// if authed
authorizedApps.add(Applications.Profile);
Role posterRole = user.getRole(); Role posterRole = user.getRole();
if (posterRole == Role.Teacher || posterRole == Role.Student || posterRole == Role.Admin){ if (!authServ.IsNotIn(new Role[]{Role.Teacher,Role.Student,Role.Admin},token)) {
authorizedApps.add(Applications.Msg); authorizedApps.add(Applications.Msg);
authorizedApps.add(Applications.Forum); authorizedApps.add(Applications.Forum);
authorizedApps.add(Applications.Rdv); authorizedApps.add(Applications.Rdv);
} }
if (posterRole == Role.Teacher || posterRole == Role.Secretary || posterRole == Role.Admin) authorizedApps.add(Applications.ManageCourses); //if Teacher or Secretary or Admin add ManageCourses App
if (!authServ.IsNotIn(new Role[]{Role.Teacher,Role.Secretary,Role.Admin},token))
authorizedApps.add(Applications.ManageCourses);
if (posterRole == Role.InscriptionService || posterRole == Role.Admin) authorizedApps.add(Applications.Inscription); if (!authServ.IsNotIn(new Role[]{Role.InscriptionService,Role.Admin},token))
authorizedApps.add(Applications.Inscription);
return authorizedApps; return authorizedApps;
} }

View File

@ -9,10 +9,6 @@ import ovh.herisson.Clyde.Services.CourseService;
import ovh.herisson.Clyde.Services.TeacherCourseService; import ovh.herisson.Clyde.Services.TeacherCourseService;
import ovh.herisson.Clyde.Tables.Course; import ovh.herisson.Clyde.Tables.Course;
import ovh.herisson.Clyde.Tables.Role; import ovh.herisson.Clyde.Tables.Role;
import ovh.herisson.Clyde.Tables.TeacherCourse;
import ovh.herisson.Clyde.Tables.User;
import java.util.ArrayList;
import java.util.Map; import java.util.Map;
@RestController @RestController
@ -36,13 +32,21 @@ public class CourseController {
if (authServ.getUserFromToken(token) == null) if (authServ.getUserFromToken(token) == null)
return new UnauthorizedResponse<>(null); return new UnauthorizedResponse<>(null);
return new ResponseEntity<>(courseServ.findById(id), HttpStatus.OK); Course foundCourse = courseServ.findById(id);
if (foundCourse == null)
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
return new ResponseEntity<>(foundCourse, HttpStatus.OK);
} }
@PostMapping("/course") @PostMapping("/course")
public ResponseEntity<Course> postCourse(@RequestHeader("Authorization") String token, @RequestBody Course course){ public ResponseEntity<Course> postCourse(@RequestHeader("Authorization") String token,
if (authServ.isNotSecretaryOrAdmin(token)) @RequestBody Course course)
{
if (authServ.IsNotIn(new Role[]{Role.Secretary,Role.Admin},token))
return new UnauthorizedResponse<>(null); return new UnauthorizedResponse<>(null);
return new ResponseEntity<>(courseServ.save(course), HttpStatus.CREATED); return new ResponseEntity<>(courseServ.save(course), HttpStatus.CREATED);
@ -55,11 +59,15 @@ public class CourseController {
@PathVariable long id) @PathVariable long id)
{ {
if (authServ.IsNotIn(new Role[]{Role.Admin,Role.Teacher,Role.Secretary}, token)){ if (authServ.IsNotIn(new Role[]{Role.Admin,Role.Teacher,Role.Secretary}, token))
return new UnauthorizedResponse<>(null); return new UnauthorizedResponse<>(null);
}
return new ResponseEntity<>(courseServ.modifyData(id, updates, authServ.getUserFromToken(token).getRole()), HttpStatus.OK); Course modifiedCourse = courseServ.modifyData(id,updates,authServ.getUserFromToken(token).getRole());
if (modifiedCourse == null)
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
return new ResponseEntity<>(modifiedCourse, HttpStatus.OK);
} }
@PostMapping("/course/{id}") @PostMapping("/course/{id}")
@ -67,14 +75,14 @@ public class CourseController {
@RequestBody Iterable<Long> teacherIds, @RequestBody Iterable<Long> teacherIds,
@PathVariable Long id) @PathVariable Long id)
{ {
if (authServ.IsNotIn(new Role[]{Role.Admin,Role.Secretary}, token)) if (authServ.IsNotIn(new Role[]{Role.Admin,Role.Secretary}, token))
return new UnauthorizedResponse<>(null); return new UnauthorizedResponse<>(null);
if (!teacherCourseServ.saveAll(teacherIds,courseServ.findById(id)))
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
teacherCourseServ.saveAll(teacherIds,courseServ.findById(id));
return new ResponseEntity<>(HttpStatus.OK); return new ResponseEntity<>(HttpStatus.OK);
} }
} }

View File

@ -4,13 +4,12 @@ package ovh.herisson.Clyde.EndPoints;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import ovh.herisson.Clyde.Responses.UnauthorizedResponse;
import ovh.herisson.Clyde.Services.AuthenticatorService; import ovh.herisson.Clyde.Services.AuthenticatorService;
import ovh.herisson.Clyde.Services.CurriculumCourseService; import ovh.herisson.Clyde.Services.CurriculumCourseService;
import ovh.herisson.Clyde.Services.CurriculumService; import ovh.herisson.Clyde.Services.CurriculumService;
import ovh.herisson.Clyde.Tables.Curriculum; import ovh.herisson.Clyde.Tables.Curriculum;
import ovh.herisson.Clyde.Tables.CurriculumCourse;
import ovh.herisson.Clyde.Tables.Role; import ovh.herisson.Clyde.Tables.Role;
import ovh.herisson.Clyde.Tables.User;
import java.util.Map; import java.util.Map;
@ -32,29 +31,25 @@ public class CurriculumController {
@GetMapping("/curriculum/{id}") @GetMapping("/curriculum/{id}")
public ResponseEntity<Curriculum> findById(@PathVariable long id){ public ResponseEntity<Curriculum> findById(@PathVariable long id){
return new ResponseEntity<>(curriculumServ.findById(id), HttpStatus.OK); Curriculum foundCurriculum = curriculumServ.findById(id);
if (foundCurriculum == null)
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
return new ResponseEntity<>(foundCurriculum, HttpStatus.OK);
} }
@GetMapping("/curriculums") @GetMapping("/curriculums")
public ResponseEntity<Iterable<Map<String, Object>>> findAllindDepth(){ public ResponseEntity<Iterable<Map<String, Object>>> findAllIndDepth(){
return new ResponseEntity<>(curriculumCourseServ.getAllDepthCurriculum(),HttpStatus.OK); return new ResponseEntity<>(curriculumCourseServ.getAllDepthCurriculum(),HttpStatus.OK);
} }
@GetMapping("/curriculum") @PostMapping("/curriculum")
public ResponseEntity<Iterable<CurriculumCourse>> findAll(){ public ResponseEntity<Curriculum> postCurriculum(@RequestHeader("Authorization") String token,@RequestBody Curriculum curriculum){
return new ResponseEntity<>(curriculumCourseServ.findAll(),HttpStatus.OK);
if (authServ.IsNotIn(new Role[]{Role.Secretary,Role.Admin},token))
return new UnauthorizedResponse<>(null);
return new ResponseEntity<>(curriculumServ.save(curriculum),HttpStatus.CREATED);
} }
/**@PostMapping("/curriculum") //todo now
public ResponseEntity<String> postCurriculum(@RequestHeader("Authorization") String token,@RequestBody Curriculum curriculum){
if (!isSecretaryOrAdmin(token)){
return new UnauthorizedResponse<>("you're not allowed to post a Curriculum");
}
CurriculumServ.save(Curriculum);
return new ResponseEntity<>("created !",HttpStatus.CREATED);
}**/
} }

View File

@ -9,14 +9,12 @@ import ovh.herisson.Clyde.Services.InscriptionService;
import ovh.herisson.Clyde.Tables.InscriptionRequest; import ovh.herisson.Clyde.Tables.InscriptionRequest;
import ovh.herisson.Clyde.Tables.RequestState; import ovh.herisson.Clyde.Tables.RequestState;
import ovh.herisson.Clyde.Tables.Role; import ovh.herisson.Clyde.Tables.Role;
import ovh.herisson.Clyde.Tables.User;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@RestController @RestController
@CrossOrigin(originPatterns = "*", allowCredentials = "true") @CrossOrigin(originPatterns = "*", allowCredentials = "true")
public class InscriptionController { public class InscriptionController {
@ -32,7 +30,8 @@ public class InscriptionController {
@GetMapping("/requests/register") @GetMapping("/requests/register")
public ResponseEntity<Iterable<Map<String,Object>>> getAllRequests(@RequestHeader("Authorization") String token){ public ResponseEntity<Iterable<Map<String,Object>>> getAllRequests(@RequestHeader("Authorization") String token){
if (authServ.isNotSecretaryOrAdmin(token)){return new UnauthorizedResponse<>(null);} if (authServ.IsNotIn(new Role[]{Role.Admin,Role.InscriptionService},token))
return new UnauthorizedResponse<>(null);
Iterable<InscriptionRequest> inscriptionRequests = inscriptionServ.getAll(); Iterable<InscriptionRequest> inscriptionRequests = inscriptionServ.getAll();
ArrayList<Map<String,Object>> toReturn = new ArrayList<>(); ArrayList<Map<String,Object>> toReturn = new ArrayList<>();
@ -46,41 +45,64 @@ public class InscriptionController {
@GetMapping("/request/register/{id}") @GetMapping("/request/register/{id}")
public ResponseEntity<Map<String,Object>> getById(@PathVariable long id){ public ResponseEntity<Map<String,Object>> getById(@RequestHeader("Authorization") String token, @PathVariable long id){
InscriptionRequest inscriptionRequest = inscriptionServ.getById(id);
if (inscriptionRequest == null) {return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);}
return new ResponseEntity<>(requestWithoutPassword(inscriptionRequest), HttpStatus.OK); if (authServ.IsNotIn(new Role[]{Role.Admin,Role.InscriptionService},token))
return new UnauthorizedResponse<>(null);
InscriptionRequest foundInscriptionRequest = inscriptionServ.getById(id);
if (foundInscriptionRequest == null)
return new ResponseEntity<>(null, HttpStatus.BAD_REQUEST);
return new ResponseEntity<>(requestWithoutPassword(foundInscriptionRequest), HttpStatus.OK);
} }
@GetMapping("request/user/{id}") /**
public ResponseEntity<InscriptionRequest> getUserInscriptionRequest(@PathVariable long id, @RequestHeader("Authorize") String token){ @GetMapping("request/user")
public ResponseEntity<InscriptionRequest> getUserInscriptionRequest(@RequestHeader("Authorization") String token){
//todo return l'inscriptionRequest ACTUELLE du user (check si le poster est bien le même que id target ou secretariat) //todo return l'inscriptionRequest ACTUELLE du user (check si le poster est bien le même que id target ou secretariat)
if (authServ.IsNotIn(new Role[]{Role.Student,Role.Admin},token))
return new UnauthorizedResponse<>(null);
User poster = authServ.getUserFromToken(token);
inscriptionServ.getById()
return null; return null;
} } **/
@PatchMapping("/request/register/{id}") @PatchMapping("/request/register/{id}")
public ResponseEntity<InscriptionRequest> changeRequestState(@PathVariable long id, public ResponseEntity<InscriptionRequest> changeRequestState(@PathVariable long id,
@RequestHeader("Authorize") String token, @RequestHeader("Authorization") String token,
@RequestBody RequestState requestState) @RequestBody RequestState requestState)
{ {
if (authServ.isNotSecretaryOrAdmin(token)) return new UnauthorizedResponse<>(null);
inscriptionServ.modifyState(id, requestState); if (authServ.IsNotIn(new Role[]{Role.InscriptionService,Role.Admin},token))
return null; return new UnauthorizedResponse<>(null);
if (!inscriptionServ.modifyState(id, requestState))
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
return new ResponseEntity<>(HttpStatus.OK);
} }
private Map<String, Object> requestWithoutPassword(InscriptionRequest inscriptionRequest) { private Map<String, Object> requestWithoutPassword(InscriptionRequest inscriptionRequest) {
Map<String, Object> toReturn = new HashMap<>(); Map<String, Object> toReturn = new HashMap<>();
toReturn.put("id", inscriptionRequest.getId()); toReturn.put("id", inscriptionRequest.getId());
toReturn.put("firstName", inscriptionRequest.getFirstName());
toReturn.put("lastName", inscriptionRequest.getLastName()); toReturn.put("lastName", inscriptionRequest.getLastName());
toReturn.put("firstName", inscriptionRequest.getFirstName());
toReturn.put("address", inscriptionRequest.getAddress()); toReturn.put("address", inscriptionRequest.getAddress());
toReturn.put("email",inscriptionRequest.getEmail());
toReturn.put("birthDate", inscriptionRequest.getBirthDate()); toReturn.put("birthDate", inscriptionRequest.getBirthDate());
toReturn.put("country", inscriptionRequest.getCountry()); toReturn.put("country", inscriptionRequest.getCountry());
toReturn.put("curriculum", inscriptionRequest.getCurriculum()); toReturn.put("curriculum", inscriptionRequest.getCurriculum());
toReturn.put("profilePictureUrl", inscriptionRequest.getProfilePicture());
toReturn.put("state", inscriptionRequest.getState()); toReturn.put("state", inscriptionRequest.getState());
toReturn.put("profilePictureUrl", inscriptionRequest.getProfilePicture());
return toReturn; return toReturn;
} }
} }

View File

@ -1,4 +1,5 @@
package ovh.herisson.Clyde.EndPoints; package ovh.herisson.Clyde.EndPoints;
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
@ -7,7 +8,6 @@ import org.springframework.web.bind.annotation.*;
import ovh.herisson.Clyde.Responses.UnauthorizedResponse; import ovh.herisson.Clyde.Responses.UnauthorizedResponse;
import ovh.herisson.Clyde.Services.AuthenticatorService; import ovh.herisson.Clyde.Services.AuthenticatorService;
import ovh.herisson.Clyde.Tables.InscriptionRequest; import ovh.herisson.Clyde.Tables.InscriptionRequest;
import java.util.Date; import java.util.Date;
@RestController @RestController
@ -45,8 +45,7 @@ public class LoginController {
} }
@PostMapping("/request/register") @PostMapping("/request/register")
public ResponseEntity<String> register(@RequestBody InscriptionRequest inscriptionRequest){ public ResponseEntity<InscriptionRequest> register(@RequestBody InscriptionRequest inscriptionRequest){
authServ.register(inscriptionRequest); return new ResponseEntity<>(authServ.register(inscriptionRequest), HttpStatus.CREATED);
return new ResponseEntity<>("Is OK", HttpStatus.CREATED);
} }
} }

View File

@ -6,7 +6,6 @@ import ovh.herisson.Clyde.Repositories.TokenRepository;
import ovh.herisson.Clyde.Repositories.UserRepository; import ovh.herisson.Clyde.Repositories.UserRepository;
import ovh.herisson.Clyde.Services.*; import ovh.herisson.Clyde.Services.*;
import ovh.herisson.Clyde.Tables.*; import ovh.herisson.Clyde.Tables.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Date; import java.util.Date;
@ -51,12 +50,11 @@ public class MockController {
User joe = new User("Mama","Joe","student@student.com","roundabout","DaWarudo",new Date(0), null,Role.Student,passwordEncoder.encode("student")); User joe = new User("Mama","Joe","student@student.com","roundabout","DaWarudo",new Date(0), null,Role.Student,passwordEncoder.encode("student"));
User meh = new User("Inspiration","lackOf","secretary@secretary.com","a Box","the street",new Date(0), null,Role.Secretary,passwordEncoder.encode("secretary")); User meh = new User("Inspiration","lackOf","secretary@secretary.com","a Box","the street",new Date(0), null,Role.Secretary,passwordEncoder.encode("secretary"));
User joke = new User("CthemBalls","Lemme","teacher@teacher.com","lab","faculty",new Date(0), null,Role.Teacher,passwordEncoder.encode("teacher")); User joke = new User("CthemBalls","Lemme","teacher@teacher.com","lab","faculty",new Date(0), null,Role.Teacher,passwordEncoder.encode("teacher"));
User lena = new User("Louille","Lena","inscriptionService@InscriptionService.com","no","yes",new Date(0), null,Role.Teacher,passwordEncoder.encode("inscriptionService")); User lena = new User("Louille","Lena","inscriptionService@InscriptionService.com","no","yes",new Date(0), null,Role.InscriptionService,passwordEncoder.encode("inscriptionService"));
mockUsers = new ArrayList<>(Arrays.asList(herobrine,joe,meh,joke)); mockUsers = new ArrayList<>(Arrays.asList(herobrine,joe,meh,joke,lena));
userRepo.saveAll(mockUsers); userRepo.saveAll(mockUsers);
// Course / Curriculum part // Course / Curriculum part
Curriculum infoBab1 = new Curriculum(1,"info"); Curriculum infoBab1 = new Curriculum(1,"info");
@ -68,7 +66,7 @@ public class MockController {
curriculumService.save(psychologyBab1); curriculumService.save(psychologyBab1);
Course progra1 = new Course(5,"Programmation et algorithimque 1",joke); Course progra1 = new Course(5,"Programmation et algorithmique 1",joke);
Course chemistry1 = new Course(12, "Thermochimie",joke); Course chemistry1 = new Course(12, "Thermochimie",joke);
Course psycho1 = new Course(21, "rien faire t'as cru c'est psycho",joke); Course psycho1 = new Course(21, "rien faire t'as cru c'est psycho",joke);
Course commun = new Course(2, "cours commun",joke); Course commun = new Course(2, "cours commun",joke);
@ -89,16 +87,6 @@ public class MockController {
CurriculumCourseService.save(new CurriculumCourse(chemistryBab1,commun)); CurriculumCourseService.save(new CurriculumCourse(chemistryBab1,commun));
CurriculumCourseService.save(new CurriculumCourse(chemistryBab1,chemistry1)); CurriculumCourseService.save(new CurriculumCourse(chemistryBab1,chemistry1));
}
@DeleteMapping("/mock")
public void deleteMock(){
for (User user:mockUsers){
tokenRepo.deleteAll(tokenRepo.getByUser(user));
}
userRepo.deleteAll(mockUsers);
} }
} }

View File

@ -22,12 +22,13 @@ public class StorageController {
@PostMapping("/upload/{fileType}") @PostMapping("/upload/{fileType}")
public ResponseEntity<StorageFile> handleFileUpload(@RequestParam("file") MultipartFile file, @PathVariable FileType fileType) { public ResponseEntity<StorageFile> handleFileUpload(@RequestParam("file") MultipartFile file, @PathVariable FileType fileType) {
StorageFile fileEntry = null; StorageFile fileEntry;
try { try {
fileEntry = storageServ.store(file,fileType); fileEntry = storageServ.store(file,fileType);
} catch(Exception e){ } catch(Exception e){
e.printStackTrace(); e.printStackTrace();
return new ResponseEntity<>(null,HttpStatus.BAD_REQUEST);
} }

View File

@ -1,11 +1,15 @@
package ovh.herisson.Clyde.EndPoints; package ovh.herisson.Clyde.EndPoints;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import ovh.herisson.Clyde.Responses.UnauthorizedResponse;
import ovh.herisson.Clyde.Services.AuthenticatorService;
import ovh.herisson.Clyde.Services.TokenService; import ovh.herisson.Clyde.Services.TokenService;
import ovh.herisson.Clyde.Tables.Role;
import ovh.herisson.Clyde.Tables.Token; import ovh.herisson.Clyde.Tables.Token;
@RestController @RestController
@ -14,13 +18,20 @@ public class TokenController {
private final TokenService tokenServ; private final TokenService tokenServ;
public TokenController(TokenService tokenServ){ private final AuthenticatorService authServ;
public TokenController(TokenService tokenServ, AuthenticatorService authServ){
this.tokenServ = tokenServ; this.tokenServ = tokenServ;
this.authServ = authServ;
} }
@GetMapping("/tokens") @GetMapping("/tokens")
public Iterable<Token> getTokens(){ public ResponseEntity<Iterable<Token>> getTokens(@RequestHeader("Authorization")String token){
return tokenServ.getAllTokens();
if (authServ.IsNotIn(new Role[]{Role.Admin},token))
return new UnauthorizedResponse<>(null);
return new ResponseEntity<>(tokenServ.getAllTokens(), HttpStatus.OK);
} }
} }

View File

@ -1,6 +1,5 @@
package ovh.herisson.Clyde.EndPoints; package ovh.herisson.Clyde.EndPoints;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
@ -9,8 +8,6 @@ import ovh.herisson.Clyde.Services.AuthenticatorService;
import ovh.herisson.Clyde.Services.UserService; import ovh.herisson.Clyde.Services.UserService;
import ovh.herisson.Clyde.Tables.Role; import ovh.herisson.Clyde.Tables.Role;
import ovh.herisson.Clyde.Tables.User; import ovh.herisson.Clyde.Tables.User;
import java.security.Key;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -27,30 +24,33 @@ public class UserController {
this.authServ = authServ; this.authServ = authServ;
} }
/** returns information about the connected user
*
* @param token the session token of the user
* @return the user information except his password
*/
@GetMapping("/user") @GetMapping("/user")
public ResponseEntity<HashMap<String,Object>> getUser(@RequestHeader("Authorization") String authorization){ public ResponseEntity<HashMap<String,Object>> getUser(@RequestHeader("Authorization") String token){
if (authorization == null) return new UnauthorizedResponse<>(null); User user = authServ.getUserFromToken(token);
User user = authServ.getUserFromToken(authorization);
if (user == null) return new UnauthorizedResponse<>(null); if (user == null) return new UnauthorizedResponse<>(null);
return new ResponseEntity<>(userWithoutPassword(user), HttpStatus.OK); return new ResponseEntity<>(userWithoutPassword(user), HttpStatus.OK);
} }
@PostMapping("/user") @PostMapping("/user")
public ResponseEntity<String> postUser(@RequestBody User user,@RequestHeader("Authorization") String authorization){ public ResponseEntity<Map<String ,Object>> postUser(@RequestBody User user,@RequestHeader("Authorization") String token){
if (authServ.isNotSecretaryOrAdmin(authorization)) if (authServ.IsNotIn(new Role[]{Role.Admin,Role.InscriptionService,Role.Secretary},token))
return new UnauthorizedResponse<>(null); return new UnauthorizedResponse<>(null);
userService.save(user); return new ResponseEntity<>(userWithoutPassword(userService.save(user)),HttpStatus.CREATED);
return new ResponseEntity<>(String.format("Account created with ID:%s",user.getRegNo()),HttpStatus.CREATED);
} }
@GetMapping("/users") @GetMapping("/users")
public ResponseEntity<Iterable<HashMap<String,Object>>> getAllUsers(@RequestHeader("Authorization") String authorization){ public ResponseEntity<Iterable<HashMap<String,Object>>> getAllUsers(@RequestHeader("Authorization") String token){
if (authServ.isNotSecretaryOrAdmin(authorization)) if (authServ.IsNotIn(new Role[]{Role.Admin,Role.Secretary},token))
return new UnauthorizedResponse<>(null); return new UnauthorizedResponse<>(null);
Iterable<User> users = userService.getAll(); Iterable<User> users = userService.getAll();
@ -61,24 +61,36 @@ public class UserController {
} }
return new ResponseEntity<>(withoutPassword, HttpStatus.OK); return new ResponseEntity<>(withoutPassword, HttpStatus.OK);
} }
@PatchMapping("/user")
public ResponseEntity<String> patchUser(@RequestBody Map<String,Object> updates, @RequestHeader("Authorization") String authorization) {
if (authorization == null) return new UnauthorizedResponse<>(null); /** changes the specified user's information
*
* @param updates the changes to be made
* @param token the session token of the user posting the change
* @param id the id of the user to change
* @return a string clarifying the issue (if there is any)
*/
@PatchMapping("/user/{id}")
public ResponseEntity<String> patchUser(@RequestHeader("Authorization") String token,
@RequestBody Map<String,Object> updates,
@PathVariable Long id) {
User poster = authServ.getUserFromToken(authorization); if (token == null) return new UnauthorizedResponse<>(null);
if (poster == null) {return new UnauthorizedResponse<>("bad authorization");}
if (!userService.modifyData(poster, updates, poster)) User poster = authServ.getUserFromToken(token);
if (poster == null) {return new UnauthorizedResponse<>("bad token");}
if (!userService.modifyData(id, updates, poster))
return new UnauthorizedResponse<>("there was an issue with the updates requested"); return new UnauthorizedResponse<>("there was an issue with the updates requested");
return new ResponseEntity<>("data modified", HttpStatus.OK); return new ResponseEntity<>(null, HttpStatus.OK);
} }
@GetMapping("/teachers") @GetMapping("/teachers")
public ResponseEntity<Iterable<HashMap<String,Object>>> getAllTeachers(@RequestHeader("Authorization") String token){ public ResponseEntity<Iterable<HashMap<String,Object>>> getAllTeachers(@RequestHeader("Authorization") String token){
if (authServ.getUserFromToken(token) == null) if (authServ.getUserFromToken(token) == null)
return new UnauthorizedResponse<>(null); return new UnauthorizedResponse<>(null);
Iterable<User> teachers = userService.getAllTeachers(); Iterable<User> teachers = userService.getAllTeachers();
ArrayList<HashMap<String, Object>> withoutPassword = new ArrayList<>(); ArrayList<HashMap<String, Object>> withoutPassword = new ArrayList<>();
@ -98,11 +110,13 @@ public class UserController {
private HashMap<String,Object> userWithoutPassword(User user){ private HashMap<String,Object> userWithoutPassword(User user){
HashMap<String,Object> toReturn = new HashMap<>(); HashMap<String,Object> toReturn = new HashMap<>();
toReturn.put("regNo",user.getRegNo()); toReturn.put("regNo",user.getRegNo());
toReturn.put("firstName",user.getFirstName());
toReturn.put("lastName",user.getLastName()); toReturn.put("lastName",user.getLastName());
toReturn.put("firstName",user.getFirstName());
toReturn.put("email", user.getEmail());
toReturn.put("address",user.getAddress());
toReturn.put("birthDate",user.getBirthDate()); toReturn.put("birthDate",user.getBirthDate());
toReturn.put("country",user.getCountry()); toReturn.put("country",user.getCountry());
toReturn.put("address",user.getAddress()); toReturn.put("profilePictureUrl",user.getProfilePictureUrl());
toReturn.put("role",user.getRole()); toReturn.put("role",user.getRole());
return toReturn; return toReturn;
} }

View File

@ -35,8 +35,8 @@ public class AuthenticatorService {
return token; return token;
} }
public void register(InscriptionRequest inscriptionRequest) { public InscriptionRequest register(InscriptionRequest inscriptionRequest) {
inscriptionService.save(inscriptionRequest); return inscriptionService.save(inscriptionRequest);
} }

View File

@ -28,6 +28,9 @@ public class CourseService {
public Course modifyData(long id, Map<String, Object> updates, Role role) { public Course modifyData(long id, Map<String, Object> updates, Role role) {
Course target = courseRepo.findById(id); Course target = courseRepo.findById(id);
if (target == null)
return null;
if (role == Role.Teacher){ if (role == Role.Teacher){
for (Map.Entry<String, Object> entry : updates.entrySet()){ for (Map.Entry<String, Object> entry : updates.entrySet()){
if (entry.getKey().equals("title")){ if (entry.getKey().equals("title")){
@ -52,4 +55,8 @@ public class CourseService {
} }
return courseRepo.save(target); return courseRepo.save(target);
} }
public void delete(Long id) {
courseRepo.deleteById(id);
}
} }

View File

@ -1,7 +1,6 @@
package ovh.herisson.Clyde.Services; package ovh.herisson.Clyde.Services;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import ovh.herisson.Clyde.Repositories.CourseRepository;
import ovh.herisson.Clyde.Repositories.CurriculumRepository; import ovh.herisson.Clyde.Repositories.CurriculumRepository;
import ovh.herisson.Clyde.Tables.Curriculum; import ovh.herisson.Clyde.Tables.Curriculum;
@ -10,23 +9,18 @@ public class CurriculumService {
private final CurriculumRepository curriculumRepo; private final CurriculumRepository curriculumRepo;
private final CourseRepository courseRepo; public CurriculumService(CurriculumRepository curriculumRepo){
public CurriculumService(CurriculumRepository curriculumRepo, CourseRepository courseRepo){
this.curriculumRepo = curriculumRepo; this.curriculumRepo = curriculumRepo;
this.courseRepo = courseRepo;
} }
public Curriculum save(Curriculum curriculum){
return curriculumRepo.save(curriculum);
public void save(Curriculum curriculum){
curriculumRepo.save(curriculum);
} }
public Curriculum findById(long id){ public Curriculum findById(long id){
return curriculumRepo.findById(id); return curriculumRepo.findById(id);
} }
public Iterable<Curriculum> findAll(){ public void delete(Long id) {
return curriculumRepo.findAll(); curriculumRepo.deleteById(id);
} }
} }

View File

@ -14,8 +14,8 @@ public class InscriptionService {
this.inscriptionRepo = inscriptionRepo; this.inscriptionRepo = inscriptionRepo;
} }
public void save(InscriptionRequest inscriptionRequest){ public InscriptionRequest save(InscriptionRequest inscriptionRequest){
inscriptionRepo.save(inscriptionRequest); return inscriptionRepo.save(inscriptionRequest);
} }
public InscriptionRequest getById(long id){ public InscriptionRequest getById(long id){
@ -26,9 +26,14 @@ public class InscriptionService {
return inscriptionRepo.findAll(); return inscriptionRepo.findAll();
} }
public void modifyState(long id, RequestState requestState) { public boolean modifyState(long id, RequestState requestState) {
InscriptionRequest inscriptionRequest = getById(id); InscriptionRequest inscriptionRequest = getById(id);
if (inscriptionRequest == null)
return false;
inscriptionRequest.setState(requestState); inscriptionRequest.setState(requestState);
save(inscriptionRequest); save(inscriptionRequest);
return true;
} }
} }

View File

@ -22,6 +22,9 @@ public class TeacherCourseService {
public boolean saveAll(Iterable<Long> teacherIds, Course course){ public boolean saveAll(Iterable<Long> teacherIds, Course course){
if (course == null)
return false;
ArrayList<Long> addedIds = new ArrayList<>(); ArrayList<Long> addedIds = new ArrayList<>();
for (Long teacherId : teacherIds){ for (Long teacherId : teacherIds){
User teacher = userRepo.findById((long) teacherId); User teacher = userRepo.findById((long) teacherId);

View File

@ -36,7 +36,11 @@ public class UserService {
* @param target the user to update * @param target the user to update
* @return if the changes were done or not * @return if the changes were done or not
*/ */
public boolean modifyData(User poster, Map<String ,Object> updates, User target){ public boolean modifyData(long targetId, Map<String ,Object> updates, User poster){
User target = userRepo.findById(targetId);
if (target == null)
return false;
if (poster.getRegNo().equals(target.getRegNo())){ if (poster.getRegNo().equals(target.getRegNo())){
for (Map.Entry<String, Object> entry : updates.entrySet()){ for (Map.Entry<String, Object> entry : updates.entrySet()){
@ -80,7 +84,7 @@ public class UserService {
if ( !entry.getKey().equals("role")) {return false;} if ( !entry.getKey().equals("role")) {return false;}
if (entry.getValue() == Role.Admin){return false;} if (entry.getValue() == Role.Admin) {return false;}
target.setRole((Role) entry.getValue()); target.setRole((Role) entry.getValue());
userRepo.save(target); userRepo.save(target);
@ -95,9 +99,9 @@ public class UserService {
return passwordEncoder.matches(tryingPassword, user.getPassword()); return passwordEncoder.matches(tryingPassword, user.getPassword());
} }
public void save(User user){ public User save(User user){
user.setPassword(passwordEncoder.encode(user.getPassword())); user.setPassword(passwordEncoder.encode(user.getPassword()));
userRepo.save(user); return userRepo.save(user);
} }
public Iterable<User> getAll(){ public Iterable<User> getAll(){

View File

@ -1,7 +1,6 @@
package ovh.herisson.Clyde.Tables; package ovh.herisson.Clyde.Tables;
import jakarta.persistence.*; import jakarta.persistence.*;
import java.util.Date; import java.util.Date;
@ -25,13 +24,14 @@ public class InscriptionRequest {
private String password; private String password;
public InscriptionRequest(){} public InscriptionRequest(){}
public InscriptionRequest(String lastName, String firstName, String address, String email, String country, Date birthDate, RequestState state, String profilePicture, String password){ public InscriptionRequest(String lastName, String firstName, String address, String email, String country, Date birthDate,Curriculum curriculum, RequestState state, String profilePicture, String password){
this.lastName = lastName; this.lastName = lastName;
this.firstName = firstName; this.firstName = firstName;
this.address = address; this.address = address;
this.email = email; this.email = email;
this.country = country; this.country = country;
this.birthDate = birthDate; this.birthDate = birthDate;
this.curriculum = curriculum;
this.state = state; this.state = state;
this.profilePicture = profilePicture; this.profilePicture = profilePicture;
this.password = password; this.password = password;