Skip to content
This repository was archived by the owner on Apr 5, 2024. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
</parent>
<groupId>de.filefighter</groupId>
<artifactId>rest</artifactId>
<version>0.0.9</version>
<version>0.1.0</version>
<name>RestApi</name>
<description>RestApi for FileFighter</description>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import de.filefighter.rest.domain.common.exceptions.RequestDidntMeetFormalRequirementsException;
import de.filefighter.rest.domain.filesystem.data.InteractionType;
import de.filefighter.rest.domain.filesystem.data.dto.FileSystemItem;
import de.filefighter.rest.domain.filesystem.data.dto.upload.CreateNewFolder;
import de.filefighter.rest.domain.filesystem.data.dto.upload.FileSystemUpload;
import de.filefighter.rest.domain.filesystem.data.dto.upload.FileSystemUploadPreflightResponse;
import de.filefighter.rest.domain.filesystem.data.dto.upload.PreflightResponse;
Expand Down Expand Up @@ -386,4 +387,75 @@ public PreflightResponse handlePreflightEntity(String absolutePath, String curre
}
}
}

public FileSystemItem createNewFolder(long parentId, CreateNewFolder newFolderRequest, User authenticatedUser) {
FileSystemEntity parent = fileSystemRepository.findByFileSystemId(parentId);
if (null == parent)
throw new FileSystemItemCouldNotBeUploadedException("Could not find parent entity or you are not allowed to see it.");

if (!fileSystemHelperService.userIsAllowedToInteractWithFileSystemEntity(parent, authenticatedUser, InteractionType.READ))
throw new FileSystemItemCouldNotBeUploadedException("Could not find parent entity or you are not allowed to see it.");

if (!fileSystemHelperService.userIsAllowedToInteractWithFileSystemEntity(parent, authenticatedUser, InteractionType.CHANGE))
throw new FileSystemItemCouldNotBeUploadedException("You dont have write permissions in that directory.");

// check for already existing folder.
List<FileSystemEntity> children = fileSystemHelperService.getFolderContentsOfEntityAndPermissions(parent, authenticatedUser, false, false);
Optional<FileSystemEntity> entityWithSameName = children.stream().filter(child -> child.getName().equalsIgnoreCase(newFolderRequest.getName())).findFirst();
if (entityWithSameName.isPresent())
throw new FileSystemItemCouldNotBeUploadedException("A Entity with the same name already exists in this directory.");

long timeStamp = fileSystemHelperService.getCurrentTimeStamp();

String dbPath;
if (parent.getPath().equals("/")) {
dbPath = parent.getPath() + newFolderRequest.getName().toLowerCase();
} else {
dbPath = parent.getPath() + "/" + newFolderRequest.getName().toLowerCase();
}

FileSystemEntity newFolder = FileSystemEntity.builder()
.path(dbPath)
.name(newFolderRequest.getName())
.fileSystemId(idGenerationService.consumeNext())
.ownerId(parent.getOwnerId())
.editableForUserIds(parent.getEditableForUserIds())
.editableFoGroupIds(parent.getEditableFoGroupIds())
.visibleForGroupIds(parent.getVisibleForGroupIds())
.visibleForUserIds(parent.getVisibleForUserIds())
.size(0)
.typeId(FileSystemType.FOLDER.getId())
.isFile(false)
.lastUpdatedBy(authenticatedUser.getUserId())
.lastUpdated(timeStamp)
.build();

fileSystemRepository.insert(newFolder);

// add folder to children of parent.
long[] childrenWithNewFolder = fileSystemHelperService.addLongToLongArray(parent.getItemIds(), newFolder.getFileSystemId());
Query query = new Query().addCriteria(Criteria.where("fileSystemId").is(parent.getFileSystemId()));
Update update = new Update().set("itemIds", childrenWithNewFolder);
mongoTemplate.findAndModify(query, update, FileSystemEntity.class);

// update timestamps.
fileSystemHelperService.recursivlyUpdateTimeStamps(parent, authenticatedUser, timeStamp);

User owner;
try {
owner = userBusinessService.findUserById(parent.getOwnerId());
} catch (UserNotFoundException ex) {
throw new FileFighterDataException("Could not find the owner of the entity with id: " + parentId);
}

StringBuilder absolutePathBuilder = new StringBuilder("/").append(owner.getUsername());
if (parent.getPath().equals("/")) {
absolutePathBuilder.append(parent.getPath());
} else {
absolutePathBuilder.append(parent.getPath()).append("/");
}
absolutePathBuilder.append(newFolderRequest.getName().toLowerCase());

return fileSystemHelperService.createDTO(newFolder, authenticatedUser, absolutePathBuilder.toString());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package de.filefighter.rest.domain.filesystem.data.dto.upload;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Builder;
import lombok.Getter;
import lombok.ToString;

@Builder
@ToString
@Getter
public class CreateNewFolder {
private final String name;

@JsonCreator
public CreateNewFolder(@JsonProperty("name") String name) {
this.name = name;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import de.filefighter.rest.domain.common.Pair;
import de.filefighter.rest.domain.filesystem.data.dto.FileSystemItem;
import de.filefighter.rest.domain.filesystem.data.dto.FileSystemItemUpdate;
import de.filefighter.rest.domain.filesystem.data.dto.upload.CreateNewFolder;
import de.filefighter.rest.domain.filesystem.data.dto.upload.FileSystemUpload;
import de.filefighter.rest.domain.filesystem.data.dto.upload.FileSystemUploadPreflightResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
Expand Down Expand Up @@ -66,6 +67,16 @@ public ResponseEntity<List<FileSystemItem>> downloadFileOrFolder(
return fileSystemRestService.downloadFileSystemEntity(ids, new Pair<>(cookieValue, accessToken));
}

@PostMapping(FS_BASE_URI + "{fsItemId}/folder/create")
public ResponseEntity<FileSystemItem> createNewFolder(
@PathVariable long fsItemId,
@RequestBody CreateNewFolder newFolder,
@RequestHeader(value = "Authorization") String accessToken) {

log.info("Tried creating new Folder {}", newFolder);
return fileSystemRestService.createNewFolder(fsItemId, newFolder, accessToken);
}

@PostMapping(FS_BASE_URI + "{fsItemId}/upload")
public ResponseEntity<List<FileSystemItem>> uploadFileOrFolder(
@PathVariable long fsItemId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import de.filefighter.rest.domain.filesystem.business.FileSystemUploadService;
import de.filefighter.rest.domain.filesystem.data.dto.FileSystemItem;
import de.filefighter.rest.domain.filesystem.data.dto.FileSystemItemUpdate;
import de.filefighter.rest.domain.filesystem.data.dto.upload.CreateNewFolder;
import de.filefighter.rest.domain.filesystem.data.dto.upload.FileSystemUpload;
import de.filefighter.rest.domain.filesystem.data.dto.upload.FileSystemUploadPreflightResponse;
import de.filefighter.rest.domain.user.data.dto.User;
Expand Down Expand Up @@ -61,6 +62,16 @@ public ResponseEntity<List<FileSystemItem>> downloadFileSystemEntity(List<Long>
return new ResponseEntity<>(listStringPair.getFirst(), responseHeaders, HttpStatus.OK);
}

@Override
public ResponseEntity<FileSystemItem> createNewFolder(long parentId, CreateNewFolder newFolder, String accessToken) {
User authenticatedUser = authenticationService.bearerAuthenticationWithAccessToken(accessToken);
String sanitizedName = inputSanitizerService.sanitizeString(newFolder.getName());
newFolder = CreateNewFolder.builder().name(sanitizedName).build();

FileSystemItem folderItem = fileSystemUploadService.createNewFolder(parentId, newFolder, authenticatedUser);
return new ResponseEntity<>(folderItem, HttpStatus.CREATED);
}

@Override
public ResponseEntity<List<FileSystemItem>> uploadFileSystemItemWithAccessToken(long rootItemId, FileSystemUpload fileSystemUpload, String accessToken) {
User authenticatedUser = authenticationService.bearerAuthenticationWithAccessToken(accessToken);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import de.filefighter.rest.domain.common.Pair;
import de.filefighter.rest.domain.filesystem.data.dto.FileSystemItem;
import de.filefighter.rest.domain.filesystem.data.dto.FileSystemItemUpdate;
import de.filefighter.rest.domain.filesystem.data.dto.upload.CreateNewFolder;
import de.filefighter.rest.domain.filesystem.data.dto.upload.FileSystemUpload;
import de.filefighter.rest.domain.filesystem.data.dto.upload.FileSystemUploadPreflightResponse;
import org.springframework.http.ResponseEntity;
Expand All @@ -25,4 +26,6 @@ public interface FileSystemRestServiceInterface {
ResponseEntity<List<FileSystemItem>> deleteFileSystemItemWithIdAndAccessToken(long fsItemId, String accessToken);

ResponseEntity<List<FileSystemItem>> downloadFileSystemEntity(List<Long> fsItemIds, Pair<String, String> authPair);

ResponseEntity<FileSystemItem> createNewFolder(long parentId, CreateNewFolder newFolder, String accessToken);
}
4 changes: 2 additions & 2 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,6 @@ spring.data.mongodb.host=localhost
spring.data.mongodb.port=20000
spring.data.mongodb.auto-index-creation=true
#------------------- Custom -----------------------
filefighter.version=0.0.9
filefighter.date=18.05.2021
filefighter.version=0.1.0
filefighter.date=22.05.2021
filefighter.disable-password-check=false
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import de.filefighter.rest.RestApplicationIntegrationTest;
import de.filefighter.rest.domain.filesystem.data.dto.upload.CreateNewFolder;
import de.filefighter.rest.domain.filesystem.data.dto.upload.FileSystemUpload;
import de.filefighter.rest.domain.filesystem.data.dto.upload.PreflightResponse;
import io.cucumber.java.en.Then;
Expand Down Expand Up @@ -110,4 +111,21 @@ public void theUserWithTokenWantsToUploadAFileWithTheNamePathMimeTypeAndSizeToTh

executeRestApiCall(HttpMethod.POST, url, header, jsonBody);
}

@When("the user with token {string} wants to create a folder with name {string} in the the folder with the id {long}")
public void theUserWithTokenWantsToCreateAFolderWithNameInTheTheFolderWithTheId(String accessToken, String name, long parentId ) throws JsonProcessingException {

String authHeaderString = AUTHORIZATION_BEARER_PREFIX + accessToken;
String url = BASE_API_URI + FS_BASE_URI + parentId + "/folder/create";

HashMap<String, String> header = new HashMap<>();
header.put("Authorization", authHeaderString);

String jsonBody = objectMapper.writeValueAsString(CreateNewFolder.builder()
.name(name)
.build());

executeRestApiCall(HttpMethod.POST, url, header, jsonBody);

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package de.filefighter.rest.domain.filesystem.business;

import de.filefighter.rest.domain.common.InputSanitizerService;
import de.filefighter.rest.domain.filesystem.data.InteractionType;
import de.filefighter.rest.domain.filesystem.data.dto.FileSystemItem;
import de.filefighter.rest.domain.filesystem.data.dto.upload.CreateNewFolder;
import de.filefighter.rest.domain.filesystem.data.persistence.FileSystemEntity;
import de.filefighter.rest.domain.filesystem.data.persistence.FileSystemRepository;
import de.filefighter.rest.domain.filesystem.exceptions.FileSystemItemCouldNotBeUploadedException;
import de.filefighter.rest.domain.filesystem.type.FileSystemTypeRepository;
import de.filefighter.rest.domain.user.business.UserBusinessService;
import de.filefighter.rest.domain.user.data.dto.User;
import org.junit.jupiter.api.Test;
import org.springframework.data.mongodb.core.MongoTemplate;

import java.util.Collections;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

class FileSystemUploadServiceUnitTest {

private final FileSystemRepository fileSystemRepositoryMock = mock(FileSystemRepository.class);
private final FileSystemHelperService fileSystemHelperServiceMock = mock(FileSystemHelperService.class);
private final InputSanitizerService inputSanitizerServiceMock = mock(InputSanitizerService.class);
private final MongoTemplate mongoTemplateMock = mock(MongoTemplate.class);
private final FileSystemTypeRepository fileSystemTypeRepositoryMock = mock(FileSystemTypeRepository.class);
private final UserBusinessService userBusinessServiceMock = mock(UserBusinessService.class);
private final IdGenerationService idGenerationServiceMock = mock(IdGenerationService.class);

private final FileSystemUploadService fileSystemUploadService = new FileSystemUploadService(fileSystemRepositoryMock, fileSystemHelperServiceMock, inputSanitizerServiceMock, fileSystemTypeRepositoryMock, mongoTemplateMock, userBusinessServiceMock, idGenerationServiceMock);

@Test
void createNewFolderThrows() {
long parentId = 420;
String folderName = "Kevin";
CreateNewFolder createNewFolder = new CreateNewFolder(folderName);
User autheticatedUser = User.builder().build();

FileSystemItemCouldNotBeUploadedException ex = assertThrows(FileSystemItemCouldNotBeUploadedException.class,
() -> fileSystemUploadService.createNewFolder(parentId, createNewFolder, autheticatedUser));
assertEquals(FileSystemItemCouldNotBeUploadedException.getErrorMessagePrefix() + " Could not find parent entity or you are not allowed to see it.", ex.getMessage());

FileSystemEntity parent = FileSystemEntity.builder().build();
when(fileSystemRepositoryMock.findByFileSystemId(parentId)).thenReturn(parent);

ex = assertThrows(FileSystemItemCouldNotBeUploadedException.class,
() -> fileSystemUploadService.createNewFolder(parentId, createNewFolder, autheticatedUser));
assertEquals(FileSystemItemCouldNotBeUploadedException.getErrorMessagePrefix() + " Could not find parent entity or you are not allowed to see it.", ex.getMessage());

when(fileSystemHelperServiceMock.userIsAllowedToInteractWithFileSystemEntity(parent, autheticatedUser, InteractionType.READ)).thenReturn(true);

ex = assertThrows(FileSystemItemCouldNotBeUploadedException.class,
() -> fileSystemUploadService.createNewFolder(parentId, createNewFolder, autheticatedUser));
assertEquals(FileSystemItemCouldNotBeUploadedException.getErrorMessagePrefix() + " You dont have write permissions in that directory.", ex.getMessage());

when(fileSystemHelperServiceMock.userIsAllowedToInteractWithFileSystemEntity(parent, autheticatedUser, InteractionType.CHANGE)).thenReturn(true);
when(fileSystemHelperServiceMock.getFolderContentsOfEntityAndPermissions(parent, autheticatedUser, false, false)).thenReturn(Collections.singletonList(FileSystemEntity.builder().name(folderName.toUpperCase()).build()));

ex = assertThrows(FileSystemItemCouldNotBeUploadedException.class,
() -> fileSystemUploadService.createNewFolder(parentId, createNewFolder, autheticatedUser));
assertEquals(FileSystemItemCouldNotBeUploadedException.getErrorMessagePrefix() + " A Entity with the same name already exists in this directory.", ex.getMessage());
}

@Test
void createNewFolderWorks() {
long parentId = 420;
String folderName = "Kevin";
CreateNewFolder createNewFolder = new CreateNewFolder(folderName);
long userId = 420;
User autheticatedUser = User.builder().build();

FileSystemEntity parent = FileSystemEntity.builder().path("/parent").ownerId(userId).build();
when(fileSystemRepositoryMock.findByFileSystemId(parentId)).thenReturn(parent);
when(fileSystemHelperServiceMock.userIsAllowedToInteractWithFileSystemEntity(parent, autheticatedUser, InteractionType.READ)).thenReturn(true);
when(fileSystemHelperServiceMock.userIsAllowedToInteractWithFileSystemEntity(parent, autheticatedUser, InteractionType.CHANGE)).thenReturn(true);
when(fileSystemHelperServiceMock.getFolderContentsOfEntityAndPermissions(parent, autheticatedUser, false, false)).thenReturn(Collections.singletonList(FileSystemEntity.builder().name("a name").build()));
when(userBusinessServiceMock.findUserById(userId)).thenReturn(User.builder().username(folderName).build());

FileSystemItem item = FileSystemItem.builder().build();
String path = "/" + folderName + "/parent/" + folderName.toLowerCase();
when(fileSystemHelperServiceMock.createDTO(any(), eq(autheticatedUser), eq(path))).thenReturn(item);

FileSystemItem actual = fileSystemUploadService.createNewFolder(parentId, createNewFolder, autheticatedUser);
assertEquals(item, actual);
}
}
Loading