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
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package de.filefighter.rest.configuration;

import de.filefighter.rest.domain.filesystem.data.persistance.FileSystemRepository;
import de.filefighter.rest.domain.token.data.persistance.AccessTokenRepository;
import de.filefighter.rest.domain.user.data.persistance.UserEntity;
import de.filefighter.rest.domain.user.data.persistance.UserRepository;
import org.slf4j.Logger;
Expand All @@ -10,18 +12,30 @@
import org.springframework.context.annotation.Profile;

@Configuration
@Profile("prod")
public class PrepareDataBaseProd {
public class PrepareDataBase {

private static final Logger LOG = LoggerFactory.getLogger(PrepareDataBaseProd.class);
private static final Logger LOG = LoggerFactory.getLogger(PrepareDataBase.class);

@Bean
CommandLineRunner initUserDataBase(UserRepository repository) {
CommandLineRunner cleanDataBase(UserRepository userRepository, FileSystemRepository fileSystemRepository, AccessTokenRepository accessTokenRepository) {

//Note: when the admin user changes his/her password, a new refreshToken will be created.
return args -> {
LOG.info("Starting with clean user collection.");
repository.deleteAll();
userRepository.deleteAll();
LOG.info("Starting with clean fileSystem collection.");
fileSystemRepository.deleteAll();
LOG.info("Starting with clean accessToken collection.");
accessTokenRepository.deleteAll();
};
}

@Bean
@Profile("prod")
CommandLineRunner initUserDataBase(UserRepository repository) {

//Note: when the admin user changes his/her password, a new refreshToken will be created.
return args -> {
LOG.info("Preloading default admin user: " + repository.save(UserEntity
.builder()
.userId(0L)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package de.filefighter.rest;

import de.filefighter.rest.configuration.RestConfiguration;
import de.filefighter.rest.domain.filesystem.rest.FileSystemRestController;
import de.filefighter.rest.domain.health.rest.SystemHealthRestController;
import de.filefighter.rest.domain.permission.rest.PermissionRestController;
import de.filefighter.rest.domain.user.rest.UserRestController;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
Expand Down
106 changes: 77 additions & 29 deletions src/test/java/de/filefighter/rest/cucumber/CommonCucumberSteps.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package de.filefighter.rest.cucumber;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.filefighter.rest.RestApplicationIntegrationTest;
import de.filefighter.rest.configuration.RestConfiguration;
import de.filefighter.rest.domain.filesystem.data.persistance.FileSystemEntity;
import de.filefighter.rest.domain.filesystem.data.persistance.FileSystemRepository;
import de.filefighter.rest.domain.token.data.persistance.AccessTokenEntity;
Expand All @@ -12,24 +14,29 @@
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;

import java.io.IOException;
import java.time.Instant;
import java.util.Arrays;
import java.util.UUID;

import static de.filefighter.rest.domain.token.business.AccessTokenBusinessService.ACCESS_TOKEN_DURATION_IN_SECONDS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class CommonCucumberSteps extends RestApplicationIntegrationTest {

private final UserRepository userRepository;
private final AccessTokenRepository accessTokenRepository;
private final FileSystemRepository fileSystemRepository;
private final ObjectMapper objectMapper;

@Autowired
public CommonCucumberSteps(UserRepository userRepository, AccessTokenRepository accessTokenRepository, FileSystemRepository fileSystemRepository) {
this.userRepository = userRepository;
this.accessTokenRepository = accessTokenRepository;
this.fileSystemRepository = fileSystemRepository;
this.objectMapper = new ObjectMapper();
}

@Given("database is empty")
Expand Down Expand Up @@ -68,53 +75,94 @@ public void userWithIdExistsAndHasUsernamePasswordAndRefreshToken(long userId, S
.build());
}

// file / folder
// This step almost needs a unit test.
@Given("{string} exists with id {long} and path {string}")
public void existsWithIdAndPath(String fileOrFolder, long fsItemId, String path) {
if(fileOrFolder.equals("file")){
//TODO: split into folders and files.
String[] names = path.split("/");
System.out.println(Arrays.toString(names));

fileSystemRepository.save(FileSystemEntity
.builder()
.isFile(true)
.id(fsItemId)
.create());
}else if(fileOrFolder.equals("folder")){
fileSystemRepository.save(FileSystemEntity
.builder()
.isFile(false)
.id(fsItemId)
.path(path)
.create());
}else{
throw new IllegalArgumentException("Found not valid string for FileOrFolder in Steps file.");
public void fileOrFolderExistsWithIdAndPath(String fileOrFolder, long fsItemId, String path) {
String[] names = path.split("/");
StringBuilder completeFilePath = new StringBuilder("/");

System.out.println(Arrays.toString(names));

// create root dir.
fileSystemRepository.save(FileSystemEntity
.builder()
.isFile(false)
.path(completeFilePath.toString())
.create());


// create all files and folders.
for (int i = 0; i < names.length; i++) {
if (!names[i].isEmpty() && !names[i].isBlank()) {
boolean isLastOne = i == names.length - 1;
if(!isLastOne){
//is obviously a folder.
completeFilePath.append(names[i]).append("/");
fileSystemRepository.save(FileSystemEntity
.builder()
.isFile(false)
.path(completeFilePath.toString())
.create());
System.out.println("folder: "+completeFilePath.toString());
}else{
System.out.println("last one: "+names[i]);
if (fileOrFolder.equals("file")) {
fileSystemRepository.save(FileSystemEntity
.builder()
.isFile(true)
.id(fsItemId)
.create());
} else if (fileOrFolder.equals("folder")) {
completeFilePath.append(names[i]).append("/");
fileSystemRepository.save(FileSystemEntity
.builder()
.isFile(false)
.id(fsItemId)
.path(completeFilePath.toString())
.create());
} else {
throw new IllegalArgumentException("Found not valid string for FileOrFolder in Steps file.");
}
}
}
}
}

@And("user {long} is owner of file or folder with id {long}")
public void userIsOwnerOfFileOrFolderWithId(long userId, long fsItemId) {
FileSystemEntity fileSystemEntity = fileSystemRepository.findById(fsItemId);
if(null == fileSystemEntity){
throw new IllegalArgumentException("FileSystemEntity was null.");
}

fileSystemEntity.setCreatedByUserId(userId);
fileSystemRepository.save(fileSystemEntity);
}

//key: value for json type response.
@Then("response contains key {string} and value {string}")
public void responseContainsKeyAndValue(String key, String value) {
public void responseContainsKeyAndValue(String key, String value) throws JsonProcessingException {
JsonNode rootNode = objectMapper.readTree(latestResponse.getBody());
String actualValue = rootNode.get(key).asText();

assertEquals(value, actualValue);
}

@And("response contains the user with id {long}")
public void responseContainsTheUserWithId(long userId) {
public void responseContainsTheUserWithId(long userId) throws JsonProcessingException {
JsonNode rootNode = objectMapper.readTree(latestResponse.getBody());
long actualValue = rootNode.get("userId").asLong();

assertEquals(userId, actualValue);
}

@Then("response status code is {int}")
public void responseStatusCodeIs(int httpStatusCode) {
public void responseStatusCodeIs(int httpStatusCode) throws IOException {
assertEquals(httpStatusCode, latestResponse.getTheResponse().getRawStatusCode());
}

@And("response contains key {string} and value of at least {int}")
public void responseContainsKeyAndValueOfAtLeast(String key, int value) throws JsonProcessingException {
JsonNode rootNode = objectMapper.readTree(latestResponse.getBody());
int actualValue = rootNode.get(key).asInt();

assertTrue(actualValue >= value);
}
}
12 changes: 12 additions & 0 deletions src/test/java/de/filefighter/rest/cucumber/SystemHealthSteps.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package de.filefighter.rest.cucumber;

import de.filefighter.rest.RestApplicationIntegrationTest;
import io.cucumber.java.en.When;
import org.springframework.http.HttpMethod;

public class SystemHealthSteps extends RestApplicationIntegrationTest {
@When("the systemHealth endpoint is requested")
public void theSystemHealthEndpointIsRequested() {
executeRestApiCall(HttpMethod.GET, "health/");
}
}
19 changes: 19 additions & 0 deletions src/test/resources/SystemHealth.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
Feature: SystemHealth
As a user
I want to be able to get status information about the state of the application.

Background:
Given database is empty

Scenario: SystemHealth is requested without users in db
When the systemHealth endpoint is requested
Then response contains key "userCount" and value "0"
And response contains key "uptimeInSeconds" and value of at least 1

Scenario: SystemHealth is requested with users in db
Given user 1234 exists
And user 3214 exists
When the systemHealth endpoint is requested
Then response contains key "userCount" and value "2"
And response contains key "uptimeInSeconds" and value of at least 1

88 changes: 44 additions & 44 deletions src/test/resources/UserAuthorization.feature
Original file line number Diff line number Diff line change
@@ -1,44 +1,44 @@
Feature: User Authorization
As a user
I want to be able to log in with username and password, as well as verify my identity
when using the endpoints.

Background:
Given database is empty
And user with id 1234 exists and has username "user", password "secure_password" and refreshToken "token"

Scenario: Successful login with username and password.
When user requests login with username "user" and password "secure_password"
Then response contains key "refreshToken" and value "token"
And response status code is 200
And response contains the user with id 1234

Scenario: Failed login with username and password.
When user requests login with username "user" and password "wrong_password"
Then response contains key "message" and value "User not authenticated."
And response contains key "status" and value "denied"
And response status code is 401

Scenario: Successful retrieval of accessToken with refreshToken.
When user requests accessToken with refreshToken "token" and userId 1234
Then response contains key "userId" and value "1234"
And response contains valid accessToken
And response status code is 200

Scenario: Failed retrieval of accessToken with wrong refreshToken.
When user requests accessToken with refreshToken "not_the_token" and userId 1234
Then response contains key "message" and value "User not authenticated."
And response contains key "status" and value "denied"
And response status code is 401

Scenario: Successful UserInfo request with valid accessToken.
Given user 1234 has access token "accessToken"
When user requests userInfo with accessToken "accessToken" and userId 1234
Then response contains the user with id 1234
And response status code is 200

Scenario: Failed UserInfo request with invalid accessToken.
When user requests userInfo with accessToken "notTheAccessToken" and userId 1234
Then response contains key "message" and value "User not authenticated."
And response contains key "status" and value "denied"
And response status code is 401
#Feature: User Authorization
# As a user
# I want to be able to log in with username and password, as well as verify my identity
# when using the endpoints.
#
#Background:
# Given database is empty
# And user with id 1234 exists and has username "user", password "secure_password" and refreshToken "token"
#
#Scenario: Successful login with username and password.
# When user requests login with username "user" and password "secure_password"
# Then response contains key "refreshToken" and value "token"
# And response status code is 200
# And response contains the user with id 1234
#
#Scenario: Failed login with username and password.
# When user requests login with username "user" and password "wrong_password"
# Then response contains key "message" and value "User not authenticated."
# And response contains key "status" and value "denied"
# And response status code is 401
#
#Scenario: Successful retrieval of accessToken with refreshToken.
# When user requests accessToken with refreshToken "token" and userId 1234
# Then response contains key "userId" and value "1234"
# And response contains valid accessToken
# And response status code is 200
#
#Scenario: Failed retrieval of accessToken with wrong refreshToken.
# When user requests accessToken with refreshToken "not_the_token" and userId 1234
# Then response contains key "message" and value "User not authenticated."
# And response contains key "status" and value "denied"
# And response status code is 401
#
#Scenario: Successful UserInfo request with valid accessToken.
# Given user 1234 has access token "accessToken"
# When user requests userInfo with accessToken "accessToken" and userId 1234
# Then response contains the user with id 1234
# And response status code is 200
#
#Scenario: Failed UserInfo request with invalid accessToken.
# When user requests userInfo with accessToken "notTheAccessToken" and userId 1234
# Then response contains key "message" and value "User not authenticated."
# And response contains key "status" and value "denied"
# And response status code is 401
Loading