Skip to content

Commit

Permalink
Can return opened docs
Browse files Browse the repository at this point in the history
  • Loading branch information
Gaetanbrl committed Oct 4, 2024
1 parent 6af688f commit ea25039
Show file tree
Hide file tree
Showing 8 changed files with 269 additions and 52 deletions.
3 changes: 2 additions & 1 deletion docs-manager-back/.vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
"name": "Application",
"request": "launch",
"mainClass": "org.georchestra.docsmanager.Application",
"projectName": "docsmanager"
"projectName": "docsmanager",
"args": "--spring.devtools.restart.enabled=true --spring.config.location=/srv/docs-manager/application.properties"
}
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,14 @@
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.beans.factory.annotation.Value;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.websocket.server.PathParam;
import org.georchestra.docsmanager.helper.FileEntityHelper;
import org.georchestra.docsmanager.helper.RoleHelper;
import org.georchestra.docsmanager.model.FileEntity;
Expand All @@ -43,24 +44,43 @@ public class FilesController {
String additionalRoles;
@Value("${docs.roles.admin}")
List<String> adminRoles;
@Value("${docs.public.value}")
String publicValue;
@Value("${docs.context.path:}")
String contextPath;

@Autowired
public FilesController(FileService fileService) {
this.fileService = fileService;
}

/**
* [protected] - Upload a file
*
* @param request
* @param file - blob
* @param comment
* @param label
* @param dateDoc
* @param plugin - code or id plugin
* @param status - e.g public
* @param entity - id feature
* @return
*/
@PostMapping(value = "/plugin/{plugin}")
public ResponseEntity<String> upload(HttpServletRequest request,
@RequestParam("file") MultipartFile file,
@RequestParam("comment") String comment,
@RequestParam(value = "comment", required = false) String comment,
@RequestParam("label") String label,
@RequestParam("dateDoc") String dateDoc,
@RequestParam("status") String status,
@RequestParam("entity") String entity, @PathVariable String plugin) {
@RequestParam(value = "status", required = false) String status,
@RequestParam("entity") String entity,
@RequestParam(value = "opened", defaultValue = "false",
required = false) Boolean opened,
@PathVariable String plugin) {
try {
String roles = request.getHeader(HEADER_ROLE);
String username = request.getHeader(HEADER_USERNAME);
String org = request.getHeader(HEADER_ORG);

List<String> defaultWriteRoles = RoleHelper.getFullAuthorizedRoles(plugin,
"edit", adminRoles, additionalRoles);
Expand All @@ -72,7 +92,7 @@ public ResponseEntity<String> upload(HttpServletRequest request,
file.getOriginalFilename()));
}
fileService.save(file, plugin, comment, username, label, dateDoc, status,
entity);
entity, opened);
return ResponseEntity.status(HttpStatus.OK)
.body(String.format("File uploaded successfully: %s",
file.getOriginalFilename()));
Expand All @@ -84,6 +104,70 @@ public ResponseEntity<String> upload(HttpServletRequest request,
}
}

/**
*
* @param request
* @param comment
* @param label
* @param dateDoc
* @param status
* @param entity - id feature
* @param opened
* @param id - file
* @param plugin
* @return
*/
@PutMapping("/plugin/{plugin}/{id}")
public ResponseEntity<String> update(HttpServletRequest request,
@RequestParam("comment") String comment,
@RequestParam("label") String label,
@RequestParam("dateDoc") String dateDoc,
@RequestParam("status") String status,
@RequestParam("entity") String entity,
@RequestParam("opened") Boolean opened, @PathVariable String id,
@PathVariable String plugin) {
try {
String roles = request.getHeader(HEADER_ROLE);

List<String> defaultWriteRoles = RoleHelper.getFullAuthorizedRoles(plugin,
"edit", adminRoles, additionalRoles);

if (!RoleHelper.isWriter(plugin, roles, defaultWriteRoles)) {
logger.info("Upload failed : check user ROLES (header sec-roles)");
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(String
.format("Not authorized to upload the file with id: %s",
id));
}
// chek if exists
Optional<FileEntity> optionalFileToUp = fileService.getFile(id);
if (!optionalFileToUp.isPresent()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(
String.format("File with id %s not found !", id));
}

// change
fileService.update(id, comment, label, dateDoc, status, entity, opened);

return ResponseEntity.status(HttpStatus.OK)
.body(String.format("File successfully updated: %s", id));
} catch (Exception e) {
logger.error("Upload failed due to Unknown error", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(String
.format("Could not update the file with id : %s!", id));
}
}


/**
* [protected] - List all files
*
* @param request
* @param plugin - code or id plugin
* @param status - e.g public
* @param entity - id feature
* @param label
* @return
*/
@GetMapping("/all")
public List<FileResponse> list(HttpServletRequest request,
@RequestParam(required = false) String status,
Expand All @@ -103,28 +187,58 @@ public List<FileResponse> list(HttpServletRequest request,
.collect(Collectors.toList());
}

/**
* [protected] - Get all files by plugin value
*
* @param request
* @param plugin - code or id plugin
* @param status - e.g public
* @param entity - id feature
* @param label
* @return
*/
@GetMapping(value = "/plugin/{plugin}")
public List<FileResponse> listByPlugin(HttpServletRequest request,
public List<FileResponse> listFilesByPlugin(HttpServletRequest request,
@PathVariable String plugin, @RequestParam(required = false) String status,
@RequestParam(required = false) String entity,
@RequestParam(required = false) String label) {
String roles = request.getHeader(HEADER_ROLE);
List<String> defaultReadersRoles = RoleHelper.getFullAuthorizedRoles(plugin, "read",
adminRoles, additionalRoles);
if (!RoleHelper.isReader(plugin, roles, defaultReadersRoles)) {
logger.info("GET /plugin/{plugin} : Not autorized roles [%s]"
.formatted(roles));
return Collections.emptyList();
}

List<FileEntity> responseFiles;
FileEntity searchFile =
FileEntityHelper.getFileExample(status, plugin, entity, label);
return fileService.getAllFilesFromExample(searchFile).stream()
.map(this::mapToFileResponse).collect(Collectors.toList());

Boolean onlyReadOpenFiles = roles == null
|| !RoleHelper.isReader(plugin, roles, defaultReadersRoles);
if (onlyReadOpenFiles) {
searchFile.setOpened(onlyReadOpenFiles);
} else {
searchFile.setOpened(null);
}

responseFiles = fileService.getAllFilesFromExample(searchFile);
return responseFiles.stream().map(this::mapToFileResponse)
.collect(Collectors.toList());

}


/**
* Utility func to create a file response.
*
* @param fileEntity
* @return
*/
private FileResponse mapToFileResponse(FileEntity fileEntity) {
String downloadURL = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/files/").path(fileEntity.getId()).toUriString();
String downloadURL = "/plugin/" + fileEntity.getPlugin() + "/" + fileEntity.getId();

if (contextPath != null) {
downloadURL = contextPath + downloadURL;
} else {
downloadURL = "files" + downloadURL;
}
FileResponse fileResponse = new FileResponse();
fileResponse.setId(fileEntity.getId());
fileResponse.setName(fileEntity.getName());
Expand All @@ -137,17 +251,33 @@ private FileResponse mapToFileResponse(FileEntity fileEntity) {
fileResponse.setStatus(fileEntity.getStatus());
fileResponse.setComment(fileEntity.getComment());
fileResponse.setEntity(fileEntity.getEntity());
fileResponse.setOpened(fileEntity.getOpened());

return fileResponse;
}

/**
* Check if a label exist
*
* @param request
* @param label
* @return
*/
@GetMapping("/label/exists/{label}")
public ResponseEntity<Boolean> labelExists(HttpServletRequest request,
@PathVariable String label) {
Boolean test = fileService.existsByLabel(label);
return ResponseEntity.status(HttpStatus.OK).body(test);
}

/**
* [protected] - Delete file
*
* @param request
* @param id - file ID
* @param plugin - plugin name or code
* @return
*/
@DeleteMapping("/plugin/{plugin}/{id}")
public ResponseEntity<String> deleteFile(HttpServletRequest request,
@PathVariable String id, @PathVariable String plugin) {
Expand All @@ -174,51 +304,47 @@ public ResponseEntity<String> deleteFile(HttpServletRequest request,
.body(String.format("File successfully deleted !"));
}

/**
* [Protected] - Get file by ID
*
* @param request
* @param id - file ID
* @param plugin - plugin name or code
* @return
*/
@GetMapping("/plugin/{plugin}/{id}")
public ResponseEntity<byte[]> getFile(HttpServletRequest request, @PathVariable String id,
@PathVariable String plugin) {
String roles = request.getHeader(HEADER_ROLE);

Optional<FileEntity> fileEntityOptional = fileService.getFile(id);
List<String> defaultReaders = RoleHelper.getFullAuthorizedRoles(plugin, "read",
adminRoles, additionalRoles);

if (!fileEntityOptional.isPresent()) {
// check if exists
Boolean idExists = fileService.existsByIdLike(id);
if (!idExists) {
logger.info("GET /plugin/{plugin}/{id} : No document exists with this ID -> Check ID.");
return ResponseEntity.notFound().build();
}
List<String> defaultReaders = RoleHelper.getFullAuthorizedRoles(plugin, "read",
adminRoles, additionalRoles);
if (!RoleHelper.isReader(plugin, roles, defaultReaders)) {

// read file
Optional<FileEntity> fileEntityOptional = fileService.getFile(id);

FileEntity fileEntity = fileEntityOptional.get();

// fobid if not opened file
if (!fileEntity.getOpened()
&& !RoleHelper.isReader(plugin, roles, defaultReaders)) {
logger.info("GET /plugin/{plugin}/{id} : Not autorized roles [%s]"
.formatted(roles));
return ResponseEntity.notFound().build();
}

FileEntity fileEntity = fileEntityOptional.get();
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + fileEntity.getName()
+ "\"")
.contentType(MediaType.valueOf(fileEntity.getContentType()))
.body(fileEntity.getData());
}

@GetMapping("/plugin/{plugin}/public/{id}")
public List<FileResponse> getPublicFilesByPluginAndFeature(HttpServletRequest request, @PathVariable String id,
@PathVariable String plugin) {
List<FileEntity> responseFiles;

responseFiles = fileService.getPublicFilesByPluginAndEntity(plugin, "public", id);
return responseFiles.stream().map(this::mapToFileResponse)
.collect(Collectors.toList());
}

@GetMapping("/plugin/public/{id}")
public List<FileResponse> getPublicFilesByFeature(HttpServletRequest request, @PathVariable String id,
@PathVariable String plugin) {
List<FileEntity> responseFiles;

responseFiles = fileService.getPublicFilesByIdFeature("public", id);
return responseFiles.stream().map(this::mapToFileResponse)
.collect(Collectors.toList());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,33 @@ public static FileEntity getFileExample(String status, String plugin, String ent
}
return fileAsExample;
}

public static FileEntity getOpenedFileExample(String status, String plugin, String entity,
String label) {
FileEntity fileAsExample = new FileEntity();
if (entity != null) {
fileAsExample.setEntity(entity);
}
if (status != null) {
fileAsExample.setStatus(status);
}
if (plugin != null) {
fileAsExample.setPlugin(plugin);
}
if (label != null) {
fileAsExample.setLabel(label);
}

fileAsExample.setOpened(true);

return fileAsExample;
}

public static FileEntity getFileExample(Boolean opened) {
FileEntity fileAsExample = new FileEntity();
if (opened != null) {
fileAsExample.setOpened(opened);
}
return fileAsExample;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ public class FileEntity {
private String createDate;
private String userInfos;

private Boolean opened;

private String dateDoc;

private Long size;
Expand Down Expand Up @@ -158,4 +160,12 @@ public void setDateDoc(String dateDoc) {
LocalDate date = LocalDate.parse(dateDoc, formatter);
this.dateDoc = date.toString();
}

public void setOpened(Boolean opened) {
this.opened = opened;
}

public Boolean getOpened() {
return this.opened;
}
}
Loading

0 comments on commit ea25039

Please sign in to comment.