1
0
forked from PGL/Clyde

cleaned the services

This commit is contained in:
Bartha Maxime 2024-03-16 20:25:35 +01:00
parent 97b57b361d
commit 382d3c203a
16 changed files with 67 additions and 87 deletions

View File

@ -56,17 +56,17 @@ public class ApplicationsController {
Role posterRole = user.getRole(); Role posterRole = user.getRole();
if (!authServ.IsNotIn(new Role[]{Role.Teacher,Role.Student,Role.Admin},token)) { 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 Teacher or Secretary or Admin add ManageCourses App //if Teacher or Secretary or Admin add ManageCourses App
if (!authServ.IsNotIn(new Role[]{Role.Teacher,Role.Secretary,Role.Admin},token)) if (!authServ.isNotIn(new Role[]{Role.Teacher,Role.Secretary,Role.Admin},token))
authorizedApps.add(Applications.ManageCourses); authorizedApps.add(Applications.ManageCourses);
if (!authServ.IsNotIn(new Role[]{Role.InscriptionService,Role.Admin},token)) if (!authServ.isNotIn(new Role[]{Role.InscriptionService,Role.Admin},token))
authorizedApps.add(Applications.Inscription); authorizedApps.add(Applications.Inscription);
return authorizedApps; return authorizedApps;

View File

@ -46,7 +46,7 @@ public class CourseController {
@RequestBody Course course) @RequestBody Course course)
{ {
if (authServ.IsNotIn(new Role[]{Role.Secretary,Role.Admin},token)) 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);
@ -59,15 +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);
Course modifiedCourse = courseServ.modifyData(id,updates,authServ.getUserFromToken(token).getRole());
if (modifiedCourse == null)
if (!courseServ.modifyData(id, updates, authServ.getUserFromToken(token).getRole()))
return new ResponseEntity<>(HttpStatus.BAD_REQUEST); return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
return new ResponseEntity<>(modifiedCourse, HttpStatus.OK); return new ResponseEntity<>(HttpStatus.OK);
} }
@PostMapping("/course/{id}") @PostMapping("/course/{id}")
@ -76,7 +76,7 @@ public class CourseController {
@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);

View File

@ -47,7 +47,7 @@ public class CurriculumController {
@PostMapping("/curriculum") @PostMapping("/curriculum")
public ResponseEntity<Curriculum> postCurriculum(@RequestHeader("Authorization") String token,@RequestBody Curriculum curriculum){ public ResponseEntity<Curriculum> postCurriculum(@RequestHeader("Authorization") String token,@RequestBody Curriculum curriculum){
if (authServ.IsNotIn(new Role[]{Role.Secretary,Role.Admin},token)) if (authServ.isNotIn(new Role[]{Role.Secretary,Role.Admin},token))
return new UnauthorizedResponse<>(null); return new UnauthorizedResponse<>(null);
return new ResponseEntity<>(curriculumServ.save(curriculum),HttpStatus.CREATED); return new ResponseEntity<>(curriculumServ.save(curriculum),HttpStatus.CREATED);

View File

@ -30,7 +30,7 @@ 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.IsNotIn(new Role[]{Role.Admin,Role.InscriptionService},token)) if (authServ.isNotIn(new Role[]{Role.Admin,Role.InscriptionService},token))
return new UnauthorizedResponse<>(null); return new UnauthorizedResponse<>(null);
Iterable<InscriptionRequest> inscriptionRequests = inscriptionServ.getAll(); Iterable<InscriptionRequest> inscriptionRequests = inscriptionServ.getAll();
@ -47,7 +47,7 @@ public class InscriptionController {
@GetMapping("/request/register/{id}") @GetMapping("/request/register/{id}")
public ResponseEntity<Map<String,Object>> getById(@RequestHeader("Authorization") String token, @PathVariable long id){ public ResponseEntity<Map<String,Object>> getById(@RequestHeader("Authorization") String token, @PathVariable long id){
if (authServ.IsNotIn(new Role[]{Role.Admin,Role.InscriptionService},token)) if (authServ.isNotIn(new Role[]{Role.Admin,Role.InscriptionService},token))
return new UnauthorizedResponse<>(null); return new UnauthorizedResponse<>(null);
InscriptionRequest foundInscriptionRequest = inscriptionServ.getById(id); InscriptionRequest foundInscriptionRequest = inscriptionServ.getById(id);
@ -80,7 +80,7 @@ public class InscriptionController {
@RequestBody RequestState requestState) @RequestBody RequestState requestState)
{ {
if (authServ.IsNotIn(new Role[]{Role.InscriptionService,Role.Admin},token)) if (authServ.isNotIn(new Role[]{Role.InscriptionService,Role.Admin},token))
return new UnauthorizedResponse<>(null); return new UnauthorizedResponse<>(null);
if (!inscriptionServ.modifyState(id, requestState)) if (!inscriptionServ.modifyState(id, requestState))

View File

@ -29,7 +29,7 @@ public class TokenController {
@GetMapping("/tokens") @GetMapping("/tokens")
public ResponseEntity<Iterable<Token>> getTokens(@RequestHeader("Authorization")String token){ public ResponseEntity<Iterable<Token>> getTokens(@RequestHeader("Authorization")String token){
if (authServ.IsNotIn(new Role[]{Role.Admin},token)) if (authServ.isNotIn(new Role[]{Role.Admin},token))
return new UnauthorizedResponse<>(null); return new UnauthorizedResponse<>(null);
return new ResponseEntity<>(tokenServ.getAllTokens(), HttpStatus.OK); return new ResponseEntity<>(tokenServ.getAllTokens(), HttpStatus.OK);

View File

@ -41,7 +41,7 @@ public class UserController {
@PostMapping("/user") @PostMapping("/user")
public ResponseEntity<Map<String ,Object>> postUser(@RequestBody User user,@RequestHeader("Authorization") String token){ public ResponseEntity<Map<String ,Object>> postUser(@RequestBody User user,@RequestHeader("Authorization") String token){
if (authServ.IsNotIn(new Role[]{Role.Admin,Role.InscriptionService,Role.Secretary},token)) if (authServ.isNotIn(new Role[]{Role.Admin,Role.InscriptionService,Role.Secretary},token))
return new UnauthorizedResponse<>(null); return new UnauthorizedResponse<>(null);
return new ResponseEntity<>(userWithoutPassword(userService.save(user)),HttpStatus.CREATED); return new ResponseEntity<>(userWithoutPassword(userService.save(user)),HttpStatus.CREATED);
@ -50,7 +50,7 @@ public class UserController {
@GetMapping("/users") @GetMapping("/users")
public ResponseEntity<Iterable<HashMap<String,Object>>> getAllUsers(@RequestHeader("Authorization") String token){ public ResponseEntity<Iterable<HashMap<String,Object>>> getAllUsers(@RequestHeader("Authorization") String token){
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);
Iterable<User> users = userService.getAll(); Iterable<User> users = userService.getAll();

View File

@ -10,7 +10,5 @@ public interface TokenRepository extends CrudRepository<Token,Long> {
Token getByToken(String token); Token getByToken(String token);
Iterable<Token> getByUser(User user);
ArrayList <Token> getByUserOrderByExpirationDate(User user); ArrayList <Token> getByUserOrderByExpirationDate(User user);
} }

View File

@ -4,19 +4,12 @@ import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.CrudRepository;
import ovh.herisson.Clyde.Tables.User; import ovh.herisson.Clyde.Tables.User;
import java.util.List;
public interface UserRepository extends CrudRepository<User, Long> { public interface UserRepository extends CrudRepository<User, Long> {
User findById(long id); User findById(long id);
User findByEmail(String email); User findByEmail(String email);
/**
@Query(value = "select a.* from Users a ",nativeQuery = true)
Iterable<User> findAllUsers();**/
@Query("select u from User u where u.role = ovh.herisson.Clyde.Tables.Role.Teacher") @Query("select u from User u where u.role = ovh.herisson.Clyde.Tables.Role.Teacher")
Iterable<User> findAllTeachers(); Iterable<User> findAllTeachers();
} }

View File

@ -39,18 +39,7 @@ public class AuthenticatorService {
return inscriptionService.save(inscriptionRequest); return inscriptionService.save(inscriptionRequest);
} }
public boolean isNotIn(Role[] roles, String token){
public boolean isNotSecretaryOrAdmin(String authorization){
if (authorization ==null)
return true;
User poster = getUserFromToken(authorization);
if (poster == null) return true;
return poster.getRole() != Role.Secretary || poster.getRole() != Role.Admin;
}
public boolean IsNotIn(Role[] roles, String token){
if (token == null) if (token == null)
return true; return true;

View File

@ -5,7 +5,6 @@ import ovh.herisson.Clyde.Repositories.CourseRepository;
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.User; import ovh.herisson.Clyde.Tables.User;
import java.util.Map; import java.util.Map;
@Service @Service
@ -25,21 +24,25 @@ public class CourseService {
return courseRepo.findById(id); return courseRepo.findById(id);
} }
public Course modifyData(long id, Map<String, Object> updates, Role role) { public boolean modifyData(long id, Map<String, Object> updates, Role role) {
Course target = courseRepo.findById(id); Course target = courseRepo.findById(id);
if (target == null) if (target == null)
return null; return false;
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")){
target.setTitle((String) entry.getValue()); target.setTitle((String) entry.getValue());
return courseRepo.save(target); courseRepo.save(target);
return true;
} }
} }
} }
if (role != Role.Secretary)
return false;
for (Map.Entry<String ,Object> entry: updates.entrySet()){ for (Map.Entry<String ,Object> entry: updates.entrySet()){
switch (entry.getKey()){ switch (entry.getKey()){
case "title": case "title":
@ -49,14 +52,14 @@ public class CourseService {
target.setCredits((Integer) entry.getValue()); target.setCredits((Integer) entry.getValue());
break; break;
case "owner": case "owner":
target.setOwner((User) entry.getValue()); //todo check if is a teacher ! if (((User) entry.getValue() ).getRole() != Role.Teacher)
break;
target.setOwner((User) entry.getValue());
break; break;
} }
} }
return courseRepo.save(target); courseRepo.save(target);
} return true;
public void delete(Long id) {
courseRepo.deleteById(id);
} }
} }

View File

@ -1,13 +1,10 @@
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.CurriculumCourseRepository; import ovh.herisson.Clyde.Repositories.CurriculumCourseRepository;
import ovh.herisson.Clyde.Repositories.CurriculumRepository;
import ovh.herisson.Clyde.Tables.Course; import ovh.herisson.Clyde.Tables.Course;
import ovh.herisson.Clyde.Tables.Curriculum; import ovh.herisson.Clyde.Tables.Curriculum;
import ovh.herisson.Clyde.Tables.CurriculumCourse; import ovh.herisson.Clyde.Tables.CurriculumCourse;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -17,27 +14,21 @@ public class CurriculumCourseService {
private final CurriculumCourseRepository curriculumCourseRepo; private final CurriculumCourseRepository curriculumCourseRepo;
private final CourseRepository courseRepo;
private final CurriculumRepository curriculumRepo; public CurriculumCourseService(CurriculumCourseRepository curriculumCourseRepository) {
public CurriculumCourseService(CurriculumCourseRepository curriculumCourseRepository, CourseRepository courseRepo, CurriculumRepository curriculumRepo) {
this.curriculumCourseRepo = curriculumCourseRepository; this.curriculumCourseRepo = curriculumCourseRepository;
this.courseRepo = courseRepo;
this.curriculumRepo = curriculumRepo;
} }
public void save(CurriculumCourse curriculumCourse){ public void save(CurriculumCourse curriculumCourse){
curriculumCourseRepo.save(curriculumCourse); curriculumCourseRepo.save(curriculumCourse);
} }
public Iterable<CurriculumCourse> findAll(){
return curriculumCourseRepo.findAll();
}
public Map<String, Object> getDepthCurriculum(Curriculum curriculum){ public Map<String, Object> getDepthCurriculum(Curriculum curriculum){
if (curriculum == null)
return null;
HashMap<String ,Object> toReturn = new HashMap<>(); HashMap<String ,Object> toReturn = new HashMap<>();
ArrayList<Course> courses = new ArrayList<>(); ArrayList<Course> courses = new ArrayList<>();
for (Course c: curriculumCourseRepo.findCoursesByCurriculum(curriculum)){ for (Course c: curriculumCourseRepo.findCoursesByCurriculum(curriculum)){
@ -61,8 +52,4 @@ public class CurriculumCourseService {
} }
return toReturn; return toReturn;
} }
} }

View File

@ -15,12 +15,8 @@ public class CurriculumService {
public Curriculum save(Curriculum curriculum){ public Curriculum save(Curriculum curriculum){
return curriculumRepo.save(curriculum); return curriculumRepo.save(curriculum);
} }
public Curriculum findById(long id){ public Curriculum findById(long id){
return curriculumRepo.findById(id); return curriculumRepo.findById(id);
} }
public void delete(Long id) {
curriculumRepo.deleteById(id);
}
} }

View File

@ -35,6 +35,9 @@ public class StorageService {
public StorageFile store(MultipartFile file, FileType fileType) { public StorageFile store(MultipartFile file, FileType fileType) {
if (file == null || file.getOriginalFilename() == null)
return null;
if (file.getOriginalFilename().isEmpty()){return null;} if (file.getOriginalFilename().isEmpty()){return null;}
UUID uuid = UUID.randomUUID(); UUID uuid = UUID.randomUUID();

View File

@ -22,21 +22,23 @@ public class TeacherCourseService {
public boolean saveAll(Iterable<Long> teacherIds, Course course){ public boolean saveAll(Iterable<Long> teacherIds, Course course){
if (course == null) if (course == null || teacherIds == null)
return false; return false;
ArrayList<Long> addedIds = new ArrayList<>(); ArrayList<User> toAdd = new ArrayList<>();
for (Long teacherId : teacherIds){ for (Long teacherId : teacherIds){
User teacher = userRepo.findById((long) teacherId); User teacher = userRepo.findById((long) teacherId);
if ( teacher== null){ if ( teacher== null){
return false; return false;
} }
if (!addedIds.contains(teacherId)) if (!toAdd.contains(teacher))
{ {
teacherCourseRepo.save(new TeacherCourse(teacher,course)); toAdd.add(teacher);
addedIds.add(teacherId);
} }
} }
for (User teacher: toAdd){
teacherCourseRepo.save(new TeacherCourse(teacher,course));
}
return true; return true;
} }
} }

View File

@ -40,16 +40,19 @@ public class TokenService {
public User getUserFromToken(String token) { public User getUserFromToken(String token) {
Token tokenRep = tokenRepo.getByToken(token); Token tokenRep = tokenRepo.getByToken(token);
if (tokenRep == null) return null; if (tokenRep == null)
return null;
return tokenRep.getUser(); return tokenRep.getUser();
} }
public void saveToken(Token token){ public void saveToken(Token token){
//Si l'utilisateur a déja 5 token delete celui qui devait expirer le plus vite //Si l'utilisateur a déja 5 token delete celui qui devait expirer le plus vite
ArrayList<Token> tokenList = tokenRepo.getByUserOrderByExpirationDate(token.getUser()); ArrayList<Token> tokenList = tokenRepo.getByUserOrderByExpirationDate(token.getUser());
while(tokenList.size() >= 5){ while(tokenList.size() >= 5){
tokenRepo.delete(tokenList.get(0)); tokenRepo.delete(tokenList.getFirst());
tokenList.remove(tokenList.get(0)); tokenList.remove(tokenList.getFirst());
} }
tokenRepo.save(token); tokenRepo.save(token);
} }
@ -67,5 +70,5 @@ public class TokenService {
tokenRepo.delete(t); tokenRepo.delete(t);
} }
} }
}; }
} }

View File

@ -17,8 +17,15 @@ public class UserService {
} }
/** return the user identified by th identifier
*
* @param identifier can be an email or the RegNo
* @return the identified user
*/
public User getUser(String identifier){ public User getUser(String identifier){
if (identifier == null) return null; if (identifier == null)
return null;
try { try {
int id = Integer.parseInt(identifier); int id = Integer.parseInt(identifier);
return userRepo.findById(id); return userRepo.findById(id);
@ -33,7 +40,7 @@ public class UserService {
* *
* @param poster the user wanting to modify target's data * @param poster the user wanting to modify target's data
* @param updates the changes to be made * @param updates the changes to be made
* @param target the user to update * @param targetId the id of the user to update
* @return if the changes were done or not * @return if the changes were done or not
*/ */
public boolean modifyData(long targetId, Map<String ,Object> updates, User poster){ public boolean modifyData(long targetId, Map<String ,Object> updates, User poster){
@ -45,8 +52,6 @@ public class UserService {
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()){
if ( entry.getKey().equals("regNo") || entry.getKey().equals("role")) {return false;}
switch (entry.getKey()){ switch (entry.getKey()){
case "firstName": case "firstName":
target.setFirstName((String) entry.getValue()); target.setFirstName((String) entry.getValue());
@ -82,13 +87,14 @@ public class UserService {
{ {
for (Map.Entry<String, Object> entry : updates.entrySet()){ for (Map.Entry<String, Object> entry : updates.entrySet()){
if ( !entry.getKey().equals("role")) {return false;} if ( entry.getKey().equals("role")) {
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);
return true; return true;
}
} }
} }
return false; return false;