1
0

#2 Folder sharing

This commit is contained in:
2023-01-23 21:02:09 +01:00
parent 7ba25aa455
commit b3ea85bdae
19 changed files with 184 additions and 70 deletions

View File

@@ -17,6 +17,7 @@ files:
|[application.properties](./web-container/src/main/resources/config/application.properties)|Main config file providing general app properties|
|[shared-application.properties](./web-container-config/src/main/resources/config/shared-application.properties)|Properties shared by all apps|
|[files-application.properties](./files/src/main/resources/config/files-application.properties)|Config file for the files app|
|[dashboard-application.properties](./dashboard/src/main/resources/config/dashboard-application.properties)|Config file for the dashboard app|
## Apache httpd config
It is advised to not expose NoBullShit-cloud directly - instead a proxy server like Apache httpd should be used to shield access.

View File

@@ -6,10 +6,12 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.SessionScope;
import java.nio.file.Path;
@Component
@SessionScope
public class AppLocationTracker implements InitializingBean {
private static final Logger logger = LoggerFactory.getLogger(AppLocationTracker.class);

View File

@@ -403,6 +403,12 @@ public class FileSystemService {
}
}
public boolean isDirectory(Path path) {
this.locationTracker.ensureValidPath(path);
return Files.isDirectory(path);
}
public List<ContentContainer> list(SortOrder sortOrder) {
return list(this.locationTracker.getCurrentLocation(), sortOrder, path -> this.locationTracker.getRelativeToBaseDir(path));
}

View File

@@ -5,12 +5,14 @@ import de.nbscloud.files.exception.FileSystemServiceException;
import de.nbscloud.webcontainer.registry.App;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.annotation.SessionScope;
import java.nio.file.Path;
import java.util.List;
import java.util.Optional;
@Service
@SessionScope
public class FilesServiceImpl implements FilesService {
@Autowired
private FileSystemService fileSystemService;

View File

@@ -5,12 +5,16 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.SessionScope;
import java.nio.file.Path;
import java.nio.file.Paths;
@Component
@SessionScope
public class LocationTracker implements InitializingBean {
private static final Logger logger = LoggerFactory.getLogger(LocationTracker.class);
@@ -31,11 +35,11 @@ public class LocationTracker implements InitializingBean {
this.baseDirPath = Paths.get(this.filesConfig.getBaseDir());
this.currentLocation = this.baseDirPath.resolve("");
logger.info("Initialized location to {}", this.currentLocation);
logger.info("{}: Initialized location to {}", id(), this.currentLocation);
}
public void reset() {
logger.debug("Reset location");
logger.debug("{}: Reset location", id());
try {
afterPropertiesSet();
@@ -44,6 +48,14 @@ public class LocationTracker implements InitializingBean {
}
}
public void resetCurrentLocation() {
this.currentLocation = this.baseDirPath.resolve("");
}
private long id() {
return System.identityHashCode(this);
}
Path getCurrentLocation() {
return this.currentLocation;
}
@@ -79,7 +91,19 @@ public class LocationTracker implements InitializingBean {
public void setCurrentLocation(String navigateTo) {
validate_internal(navigateTo);
this.currentLocation = this.baseDirPath.resolve(navigateTo);
final Path newLocation = this.baseDirPath.resolve(navigateTo);
logger.debug("{}: Change location from {} to {}", id(), this.currentLocation, newLocation);
this.currentLocation = newLocation;
}
public void setBaseDirPath(String path) {
validate_internal(path);
this.baseDirPath = this.baseDirPath.resolve(path);
logger.debug("{}: Change base dir to {}", id(), baseDirPath);
}
private void validate_internal(String navigateTo) {

View File

@@ -0,0 +1,18 @@
package de.nbscloud.files;
import org.springframework.stereotype.Component;
import org.springframework.web.context.annotation.SessionScope;
@Component
@SessionScope
public class SessionInfo {
private boolean restrictedSession = false;
public boolean isRestrictedSession() {
return restrictedSession;
}
public void setRestrictedSession(boolean restrictedSession) {
this.restrictedSession = restrictedSession;
}
}

View File

@@ -12,6 +12,7 @@ import de.nbscloud.files.form.PasswordForm;
import de.nbscloud.files.form.RenameForm;
import de.nbscloud.files.form.ShareForm;
import de.nbscloud.webcontainer.MessageHelper;
import de.nbscloud.files.SessionInfo;
import de.nbscloud.webcontainer.registry.AppRegistry;
import de.nbscloud.webcontainer.shared.config.WebContainerSharedConfig;
import org.apache.commons.io.input.ObservableInputStream;
@@ -22,7 +23,6 @@ import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
@@ -37,7 +37,6 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
@@ -45,7 +44,6 @@ import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@@ -70,6 +68,8 @@ public class FilesController implements InitializingBean {
private ObjectMapper mapper;
@Autowired
private MessageHelper messageHelper;
@Autowired
private SessionInfo sessionInfo;
@GetMapping("/files/browse/**")
public String start(Model model, HttpServletRequest httpServletRequest, String sortOrder) {
@@ -82,6 +82,7 @@ public class FilesController implements InitializingBean {
model.addAttribute("content", getContent(order));
model.addAttribute("sortOrder", order);
model.addAttribute("apps", this.appRegistry.getAll());
model.addAttribute("restricted", this.sessionInfo.isRestrictedSession());
this.webContainerSharedConfig.addDefaults(model);
return "files/filesIndex";
@@ -119,6 +120,7 @@ public class FilesController implements InitializingBean {
model.addAttribute("targetDirs", this.fileSystemService.collectDirs(filename));
model.addAttribute("apps", this.appRegistry.getAll());
model.addAttribute("filename", filename);
model.addAttribute("restricted", this.sessionInfo.isRestrictedSession());
this.webContainerSharedConfig.addDefaults(model);
return "files/rename";
@@ -223,6 +225,7 @@ public class FilesController implements InitializingBean {
model.addAttribute("form", new ShareForm(filename, false, LocalDate.now().plusDays(1), null));
model.addAttribute("apps", this.appRegistry.getAll());
model.addAttribute("filename", filename);
model.addAttribute("restricted", this.sessionInfo.isRestrictedSession());
this.webContainerSharedConfig.addDefaults(model);
return "files/share";
@@ -269,21 +272,39 @@ public class FilesController implements InitializingBean {
}
@GetMapping("files/shares")
public ResponseEntity shares(String shareUuid) {
public Object shares(Model model, String shareUuid) {
this.locationTracker.reset();
try {
final String shareJson = new String(this.fileSystemService.get(this.locationTracker.resolveShare(shareUuid)));
final Share share = mapper.readValue(shareJson, Share.class);
final Path sharedFilePath = this.locationTracker.resolveToBaseDir(share.getPath());
final Optional<LocalDate> optExpiryDate = Optional.ofNullable(share.getExpiryDate());
final boolean expired = optExpiryDate.map(expiryDate -> LocalDate.now().isAfter(expiryDate)).orElse(false);
this.sessionInfo.setRestrictedSession(true);
if(share.getPassword() != null) {
// If there is a password check nothing else, so there is no information leak if the remote doesn't know the password
final HttpHeaders headers = new HttpHeaders();
model.addAttribute("form", new PasswordForm(shareUuid, null));
this.webContainerSharedConfig.addDefaults(model);
headers.add("Location", "shares/passwordCheck?shareUuid=" + shareUuid);
return new ResponseEntity<String>(headers, HttpStatus.FOUND);
return "files/checkPassword";
}
else {
return doShares(shareUuid);
if (expired) {
fileSystemService.delete(locationTracker.resolveShare(shareUuid));
return ResponseEntity.status(410).body("Share expired!");
}
if(this.fileSystemService.isDirectory(sharedFilePath)) {
this.locationTracker.setBaseDirPath(share.getPath());
return "redirect:/files/browse";
}
else {
return doShares(shareUuid);
}
}
} catch (RuntimeException | JsonProcessingException e) {
logger.error("Could not get shared file", e);
@@ -292,33 +313,40 @@ public class FilesController implements InitializingBean {
}
}
@GetMapping("files/shares/passwordCheck")
public String passwordCheck(Model model, String shareUuid) {
this.messageHelper.addAndClearAll(model);
model.addAttribute("form", new PasswordForm(shareUuid, null));
this.webContainerSharedConfig.addDefaults(model);
return "files/checkPassword";
}
@PostMapping("/files/shares/checkPassword")
public ResponseEntity checkPassword(@RequestParam(value = "shareUuid", required = true) String shareUuid,
public Object checkPassword(Model model, @RequestParam(value = "shareUuid", required = true) String shareUuid,
@RequestParam(value = "password", required = true) String password) {
try {
final String shareJson = new String(this.fileSystemService.get(this.locationTracker.resolveShare(shareUuid)));
final Share share = mapper.readValue(shareJson, Share.class);
final Path sharedFilePath = this.locationTracker.resolveToBaseDir(share.getPath());
final Optional<LocalDate> optExpiryDate = Optional.ofNullable(share.getExpiryDate());
final boolean expired = optExpiryDate.map(expiryDate -> LocalDate.now().isAfter(expiryDate)).orElse(false);
if(share.getPassword().equals(password)) {
return doShares(shareUuid);
if (expired) {
fileSystemService.delete(locationTracker.resolveShare(shareUuid));
return ResponseEntity.status(410).body("Share expired!");
}
if(this.fileSystemService.isDirectory(sharedFilePath)) {
this.locationTracker.setBaseDirPath(share.getPath());
return "redirect:/files/browse";
}
else {
return doShares(shareUuid);
}
}
else {
this.messageHelper.addResolvableError("nbscloud.files.share.error.passwordWrong");
this.messageHelper.addAndClearAll(model);
final HttpHeaders headers = new HttpHeaders();
model.addAttribute("form", new PasswordForm(shareUuid, null));
this.webContainerSharedConfig.addDefaults(model);
headers.add("Location", "passwordCheck?shareUuid=" + shareUuid);
return new ResponseEntity<String>(headers, HttpStatus.FOUND);
return "files/checkPassword";
}
} catch (RuntimeException | JsonProcessingException e) {
logger.error("Could not get shared file", e);
@@ -333,13 +361,9 @@ public class FilesController implements InitializingBean {
final Share share = mapper.readValue(shareJson, Share.class);
final Path sharedFilePath = this.locationTracker.resolveToBaseDir(share.getPath());
final String filename = sharedFilePath.getFileName().toString();
final Optional<LocalDate> optExpiryDate = Optional.ofNullable(share.getExpiryDate());
final boolean expired = optExpiryDate.map(expiryDate -> LocalDate.now().isAfter(expiryDate)).orElse(false);
if (expired) {
fileSystemService.delete(locationTracker.resolveShare(shareUuid));
return ResponseEntity.status(410).body("Share expired!");
if(this.fileSystemService.isDirectory(sharedFilePath)) {
throw new IllegalStateException("Attempt to access folder via file share: " + sharedFilePath);
}
return ResponseEntity.ok()
@@ -381,6 +405,7 @@ public class FilesController implements InitializingBean {
model.addAttribute("files", files);
model.addAttribute("apps", this.appRegistry.getAll());
model.addAttribute("restricted", this.sessionInfo.isRestrictedSession());
this.webContainerSharedConfig.addDefaults(model);
return "files/gallery";
@@ -415,7 +440,12 @@ public class FilesController implements InitializingBean {
if (split.length > 1) {
this.locationTracker.setCurrentLocation(UriUtils.decode(split[1].substring(1), StandardCharsets.UTF_8));
} else {
this.locationTracker.reset();
if(!this.sessionInfo.isRestrictedSession()) {
this.locationTracker.reset();
}
else {
this.locationTracker.resetCurrentLocation();
}
}
}
@@ -437,23 +467,23 @@ public class FilesController implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
if (this.filesConfig.isUseTrashBin()) {
try {
this.fileSystemService.createDirectory(this.filesConfig.getTrashBinName());
} catch (FileSystemServiceException e) {
if (!FileAlreadyExistsException.class.equals(e.getCause().getClass())) {
throw e;
}
// else: do nothing
}
}
try {
this.fileSystemService.createDirectory(this.filesConfig.getSharesName());
} catch (FileSystemServiceException e) {
if (!FileAlreadyExistsException.class.equals(e.getCause().getClass())) {
throw e;
}
// else: do nothing
}
// if (this.filesConfig.isUseTrashBin()) {
// try {
// this.fileSystemService.createDirectory(this.filesConfig.getTrashBinName());
// } catch (FileSystemServiceException e) {
// if (!FileAlreadyExistsException.class.equals(e.getCause().getClass())) {
// throw e;
// }
// // else: do nothing
// }
// }
// try {
// this.fileSystemService.createDirectory(this.filesConfig.getSharesName());
// } catch (FileSystemServiceException e) {
// if (!FileAlreadyExistsException.class.equals(e.getCause().getClass())) {
// throw e;
// }
// // else: do nothing
// }
}
}

View File

@@ -49,9 +49,9 @@
<td th:if="${fileEntry.directory}" class="no-mobile">d</td>
<td th:if="${!fileEntry.directory}" class="no-mobile">-</td>
<td th:if="${fileEntry.directory}">
<a th:if="${fileEntry.name != '..'}" th:href="@{/files/browse/} + ${fileEntry.path}"
<a th:if="${fileEntry.name != '..'}" th:href="@{/files/browse/__${fileEntry.path}__}"
th:text="${fileEntry.name}"/>
<a th:if="${fileEntry.name == '..'}" th:href="@{/files/browse/} + ${fileEntry.path}"
<a th:if="${fileEntry.name == '..'}" th:href="@{/files/browse/__${fileEntry.path}__}"
th:text="${fileEntry.name}"/>
</td>
<td th:if="${!fileEntry.directory && @filesFormatter.needsTruncate(fileEntry.name)}"
@@ -67,11 +67,13 @@
<details th:if="${fileEntry.name != '..'}" class="files-table-text-align-right">
<summary th:text="#{nbscloud.show-actions}"/>
<div id="files-content-table-show-actions-detail-container">
<div id="files-content-table-show-actions-detail-container-rename">
<div id="files-content-table-show-actions-detail-container-rename"
th:if="${!restricted}">
<a th:href="@{/files/rename(filename=${fileEntry.name})}"
th:text="#{nbscloud.files-content-table.table.actions.rename}"/>
</div>
<div id="files-content-table-show-actions-detail-container-delete">
<div id="files-content-table-show-actions-detail-container-delete"
th:if="${!restricted}">
<a th:href="@{/files/delete(filename=${fileEntry.name})}"
th:text="#{nbscloud.files-content-table.table.actions.delete}"/>
</div>
@@ -84,8 +86,8 @@
<a th:href="@{/files/preview(filename=${fileEntry.name})}"
th:text="#{nbscloud.files-content-table.table.actions.preview}"/>
</div>
<div th:if="${!fileEntry.directory}"
id="files-content-table-show-actions-detail-container-share">
<div id="files-content-table-show-actions-detail-container-share"
th:if="${!restricted}">
<a th:href="@{/files/share(filename=${fileEntry.name})}"
th:text="#{nbscloud.files-content-table.table.actions.share}"/>
</div>

View File

@@ -1,6 +1,6 @@
<div id="menu-container" th:fragment="menu">
<div class="menu-spacer"></div>
<div id="upload-container" class="menu-container">
<div th:if="${!restricted}" class="menu-spacer"></div>
<div th:if="${!restricted}" id="upload-container" class="menu-container">
<form method="POST" action="#" th:action="@{/files/upload}" enctype="multipart/form-data">
<!-- JavaScript required unfortunately -->
<input id="upload-container-file-input" type="file" name="files" onchange="this.form.submit()"
@@ -9,8 +9,8 @@
onclick="document.getElementById('upload-container-file-input').click();">&#xe9fc;</span>
</form>
</div>
<div class="menu-spacer"></div>
<div id="create-dir-container" class="menu-container">
<div th:if="${!restricted}" class="menu-spacer"></div>
<div th:if="${!restricted}" id="create-dir-container" class="menu-container">
<details>
<summary>
<span id="create-dir-container-span-input" class="icon menu-icon">&#xe2cc;</span>

View File

@@ -21,7 +21,7 @@
<label for="expiryDate" th:text="#{nbscloud.files.share.label.expirydate}"/>
<input type="date" id="expiryDate" th:field="*{expiryDate}"/>
<label for="password" th:text="#{nbscloud.files.share.label.password}"/>
<input type="text" id="password" th:field="*{password}"/>
<input type="password" id="password" th:field="*{password}"/>
<input type="submit" th:value="#{nbscloud.files.share.submit}" />
</form>
<div th:replace="includes/footer :: footer"/>

View File

@@ -51,7 +51,7 @@ public class NotesController implements InitializingBean {
}
this.messageHelper.addAndClearAll(model);
model.addAttribute("currentNote", notePath);
model.addAttribute("currentNote", optNotePath.orElse(Path.of("/")));
model.addAttribute("tree", this.filesService.getTree(app, Optional.empty()));
model.addAttribute("dirs", this.filesService.collectDirs(app, Optional.empty()));
model.addAttribute("apps", this.appRegistry.getAll());
@@ -124,6 +124,6 @@ public class NotesController implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
this.filesService.createAppDirectory(this.app);
//this.filesService.createAppDirectory(this.app);
}
}

View File

@@ -4,4 +4,6 @@ nbscloud.notes.action.delete=Delete
nbscloud.notes.save.success=Saved
nbscloud.notes.delete.success=Deleted
nbscloud.notes.createDir.success=Directory created
nbscloud.notes.createNote.success=Note created
nbscloud.notes.createNote.success=Note created
nbscloud.notes.index.title=nbscloud - notes\:\u0020

View File

@@ -4,4 +4,6 @@ nbscloud.notes.action.delete=L\u00F6schen
nbscloud.notes.save.success=Gespeichert
nbscloud.notes.delete.success=Gel\u00F6scht
nbscloud.notes.createDir.success=Verzeichnis erstellt
nbscloud.notes.createNote.success=Notiz erstellt
nbscloud.notes.createNote.success=Notiz erstellt
nbscloud.notes.index.title=nbscloud - Notizen\:\u0020

View File

@@ -16,5 +16,10 @@
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

View File

@@ -2,11 +2,13 @@ package de.nbscloud.webcontainer;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.web.context.annotation.SessionScope;
import java.util.ArrayList;
import java.util.List;
@Component
@SessionScope
public class MessageHelper {
// We have to temporarily store messages as we redirect: in some methods
// so everything we add to the model will be gone, that's why we store messages

View File

@@ -74,6 +74,10 @@
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- Misc -->
<dependency>

View File

@@ -2,10 +2,21 @@ package de.nbscloud.webcontainer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.ALWAYS);
return http.build();
}
}

View File

@@ -1,6 +1,7 @@
v19:
- #22 Fix a bug with password protected shares
- Add Apache httpd config example
- #2 Add folder sharing
v18:
- #22 Password protected shares

View File

@@ -1,5 +1,7 @@
<div id="header-container" th:fragment="header">
<div th:each="app : ${apps}" class="menu-entry">
<a th:href="@{/} + ${app.startPath}" th:text="${app.id}"/>
<div th:if="${restricted == null || restricted == false}">
<div th:each="app : ${apps}" class="menu-entry">
<a th:href="@{/} + ${app.startPath}" th:text="${app.id}"/>
</div>
</div>
</div>