Skip to content

Commit

Permalink
faf-java-api-428 Fix after rebase
Browse files Browse the repository at this point in the history
  • Loading branch information
bukajsytlos committed Jun 4, 2023
1 parent c773104 commit ca8e310
Show file tree
Hide file tree
Showing 8 changed files with 201 additions and 294 deletions.
16 changes: 4 additions & 12 deletions src/inttest/java/com/faforever/api/clan/ClanControllerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,6 @@
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.test.context.support.WithUserDetails;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.MethodMode;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.Sql.ExecutionPhase;
import org.springframework.test.web.servlet.MvcResult;
Expand All @@ -20,16 +16,15 @@

import static org.hamcrest.Matchers.is;
import static org.hamcrest.core.IsNull.nullValue;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
@Sql(executionPhase = ExecutionPhase.BEFORE_TEST_METHOD, scripts = "classpath:sql/truncateTables.sql")
@Sql(executionPhase = ExecutionPhase.BEFORE_TEST_METHOD, scripts = "classpath:sql/prepDefaultData.sql")
@Sql(executionPhase = ExecutionPhase.BEFORE_TEST_METHOD, scripts = "classpath:sql/prepClanData.sql")
Expand Down Expand Up @@ -115,7 +110,6 @@ public void createClanWithoutAuth() throws Exception {
}

@Test
@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
public void createClanWithExistingName() throws Exception {
Player player = playerRepository.getById(USERID_USER);

Expand All @@ -138,7 +132,6 @@ public void createClanWithExistingName() throws Exception {
}

@Test
@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
public void createClanWithExistingTag() throws Exception {
Player player = playerRepository.getById(USERID_USER);

Expand All @@ -161,7 +154,6 @@ public void createClanWithExistingTag() throws Exception {
}

@Test
@DirtiesContext(methodMode = MethodMode.BEFORE_METHOD)
public void createSecondClan() throws Exception {
Player player = playerRepository.getById(USERID_CLAN_MEMBER);

Expand Down
23 changes: 10 additions & 13 deletions src/main/java/com/faforever/api/clan/ClanService.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
Expand Down Expand Up @@ -69,15 +67,16 @@ public void preCreate(Clan clan) {
@SneakyThrows
@Transactional
@Deprecated
// use POST via Elide instead
Clan create(String name, String tag, String description) {
// use POST via Elide instead
public Clan create(String name, String tag, String description) {
Clan clan = new Clan();
clan.setName(name);
clan.setTag(tag);
clan.setDescription(description);
clan.setRequiresInvitation(true);
clan.setFounder(playerService.getCurrentPlayer());
clan.setLeader(playerService.getCurrentPlayer());
Player currentPlayer = playerService.getCurrentPlayer();
clan.setFounder(currentPlayer);
clan.setLeader(currentPlayer);

// validation is done at preCreate() called by ClanListener
clanRepository.save(clan);
Expand All @@ -86,7 +85,7 @@ Clan create(String name, String tag, String description) {

@SneakyThrows
@Transactional
String generatePlayerInvitationToken(int newMemberId, int clanId) {
public String generatePlayerInvitationToken(int newMemberId, int clanId) {
Player requester = playerService.getCurrentPlayer();

Clan clan = clanRepository.findById(clanId)
Expand All @@ -102,16 +101,14 @@ String generatePlayerInvitationToken(int newMemberId, int clanId) {
.plus(fafApiProperties.getClan().getInviteLinkExpireDurationMinutes(), ChronoUnit.MINUTES)
.toEpochMilli();

InvitationResult result = new InvitationResult(expire,
ClanResult.of(clan),
PlayerResult.of(newMember));
InvitationResult result = new InvitationResult(expire, ClanResult.of(clan), PlayerResult.of(newMember));
return jwtService.sign(result);
}

@SneakyThrows
void acceptPlayerInvitationToken(String stringToken) {
Jwt token = jwtService.decodeAndVerify(stringToken);
InvitationResult invitation = objectMapper.readValue(token.getClaims(), InvitationResult.class);
String decodedToken = jwtService.decodeAndVerify(stringToken);
InvitationResult invitation = objectMapper.readValue(decodedToken, InvitationResult.class);

if (invitation.isExpired()) {
throw ApiException.of(ErrorCode.CLAN_ACCEPT_TOKEN_EXPIRE);
Expand All @@ -122,7 +119,7 @@ void acceptPlayerInvitationToken(String stringToken) {
Clan clan = clanRepository.findById(clanId)
.orElseThrow(() -> new ApiException(new Error(ErrorCode.CLAN_NOT_EXISTS, clanId)));

Player newMember = playerService.getById(invitation.newMember().getId());
Player newMember = playerService.getById(invitation.newMember().id());

if (!Objects.equals(player.getId(), newMember.getId())) {
throw ApiException.of(ErrorCode.CLAN_ACCEPT_WRONG_PLAYER);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.lang.Nullable;
import org.springframework.security.core.Authentication;
import org.springframework.util.StreamUtils;
import org.springframework.web.multipart.MultipartFile;

Expand All @@ -16,7 +15,7 @@
* This class is used to support having both @RequestParam and @RequestPart with same multipart name in one request handler.
* When multipart request contains simple request param octet-stream, this class is used to ignore parsing
* of byte stream to {@link MapUploadMetadata}.
* See {@link com.faforever.api.map.MapsController#uploadMap(MultipartFile, String, MapUploadMetadata, Authentication)}
* See {@link com.faforever.api.map.MapsController#uploadMap(MultipartFile, String, MapUploadMetadata)}
*/
public class IgnoreOctetStreamToObjectHttpMessageConverter extends AbstractHttpMessageConverter<byte[]> {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,13 @@

import com.faforever.api.map.MapUploadMetadata;
import org.springframework.core.convert.converter.Converter;
import org.springframework.security.core.Authentication;
import org.springframework.web.multipart.MultipartFile;

/**
* This class is used to support having both @RequestParam and @RequestPart with same multipart name in one request handler.
* When multipart request contains json multipart, this class is used to ignore conversion
* of MultipartFile to String.
* See {@link com.faforever.api.map.MapsController#uploadMap(MultipartFile, String, MapUploadMetadata, Authentication)}
* See {@link com.faforever.api.map.MapsController#uploadMap(MultipartFile, String, MapUploadMetadata)}
*/
public class NoopMultipartFileToStringConverter implements Converter<MultipartFile, String> {

Expand Down
33 changes: 12 additions & 21 deletions src/main/java/com/faforever/api/map/MapsController.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.faforever.api.map;

import com.faforever.api.config.FafApiProperties;
import com.faforever.api.data.domain.Player;
import com.faforever.api.error.ApiException;
import com.faforever.api.error.ErrorCode;
Expand All @@ -14,9 +13,9 @@
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
Expand All @@ -34,12 +33,11 @@
@AllArgsConstructor
public class MapsController {
private final MapService mapService;
private final FafApiProperties fafApiProperties;
private final ObjectMapper objectMapper;
private final PlayerService playerService;


@RequestMapping(path = "/validate", method = RequestMethod.GET, produces = APPLICATION_JSON_UTF8_VALUE)
@GetMapping(path = "/validate", produces = APPLICATION_JSON_UTF8_VALUE)
public ModelAndView showValidationForm(Map<String, Object> model) {
return new ModelAndView("validate_map_metadata.html");
}
Expand All @@ -49,11 +47,7 @@ public ModelAndView showValidationForm(Map<String, Object> model) {
@ApiResponse(code = 200, message = "Information about derived names to be used in the scenario.lua"),
@ApiResponse(code = 422, message = "A list of reasons why the name is not valid.")
})
@RequestMapping(
path = "/validateMapName",
method = RequestMethod.POST,
produces = APPLICATION_JSON_UTF8_VALUE
)
@PostMapping(path = "/validateMapName", produces = APPLICATION_JSON_UTF8_VALUE)
public MapNameValidationResponse validateMapName(@RequestParam("mapName") String mapName) {
return mapService.requestMapNameValidation(mapName);
}
Expand All @@ -62,11 +56,7 @@ public MapNameValidationResponse validateMapName(@RequestParam("mapName") String
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Valid without further information"),
@ApiResponse(code = 422, message = "A list of errors in the scenario.lua")})
@RequestMapping(
path = "/validateScenarioLua",
method = RequestMethod.POST,
produces = APPLICATION_JSON_UTF8_VALUE
)
@PostMapping(path = "/validateScenarioLua", produces = APPLICATION_JSON_UTF8_VALUE)
public void validateScenarioLua(@RequestParam(name = "scenarioLua") String scenarioLua) {
mapService.validateScenarioLua(scenarioLua);
}
Expand All @@ -76,12 +66,13 @@ public void validateScenarioLua(@RequestParam(name = "scenarioLua") String scena
@ApiResponse(code = 200, message = "Success"),
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 500, message = "Failure")})
@RequestMapping(path = "/upload", method = RequestMethod.POST, produces = APPLICATION_JSON_UTF8_VALUE)
@PostMapping(path = "/upload", produces = APPLICATION_JSON_UTF8_VALUE)
@PreAuthorize("hasScope('" + OAuthScope._UPLOAD_MAP + "')")
public void uploadMap(@RequestParam("file") MultipartFile file,
@Deprecated @RequestParam(value = "metadata", required = false) String metadataJsonString,
@RequestPart(value = "metadata", required = false) MapUploadMetadata metadata,
Authentication authentication) throws IOException {
public void uploadMap(
@RequestParam("file") MultipartFile file,
@Deprecated @RequestParam(value = "metadata", required = false) String metadataJsonString,
@RequestPart(value = "metadata", required = false) MapUploadMetadata metadata
) throws IOException {
if (metadataJsonString == null && metadata == null) {
throw ApiException.of(ErrorCode.PARAMETER_MISSING, "metadata");
}
Expand All @@ -102,7 +93,7 @@ public void uploadMap(@RequestParam("file") MultipartFile file,
licenseId = metadata.licenseId();
}

Player player = playerService.getPlayer(authentication);
Player player = playerService.getCurrentPlayer();
mapService.uploadMap(file.getInputStream(), file.getOriginalFilename(), player, ranked, licenseId);
}
}
13 changes: 5 additions & 8 deletions src/main/java/com/faforever/api/mod/ModsController.java
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
package com.faforever.api.mod;

import com.faforever.api.config.FafApiProperties;
import com.faforever.api.player.PlayerService;
import com.faforever.api.security.OAuthScope;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
Expand All @@ -28,27 +26,26 @@ public class ModsController {

private final PlayerService playerService;
private final ModService modService;
private final FafApiProperties fafApiProperties;

@ApiOperation("Upload a mod")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Success"),
@ApiResponse(code = 401, message = "Unauthorized"),
@ApiResponse(code = 500, message = "Failure")})
@RequestMapping(path = "/upload", method = RequestMethod.POST, produces = APPLICATION_JSON_UTF8_VALUE)
@PostMapping(path = "/upload", produces = APPLICATION_JSON_UTF8_VALUE)
@PreAuthorize("hasScope('" + OAuthScope._UPLOAD_MOD + "')")
public void uploadMod(
@RequestParam("file") MultipartFile file,
@RequestPart(value = "metadata", required = false) ModUploadMetadata metadata, //TODO make required when implemented by client
Authentication authentication) throws IOException {
@RequestPart(value = "metadata", required = false) ModUploadMetadata metadata //TODO make required when implemented by client
) throws IOException {

Path tempFile = java.nio.file.Files.createTempFile("mod", ".tmp");
file.transferTo(tempFile.toFile());

modService.processUploadedMod(
tempFile,
file.getOriginalFilename(),
playerService.getPlayer(authentication),
playerService.getCurrentPlayer(),
metadata != null ? metadata.licenseId() : null,
metadata != null ? metadata.repositoryUrl() : null
);
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/faforever/api/player/PlayerService.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public class PlayerService {

private final PlayerRepository playerRepository;

public Player getPlayer() {
public Player getCurrentPlayer() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

if (authentication instanceof FafAuthenticationToken fafAuthenticationToken) {
Expand Down
Loading

0 comments on commit ca8e310

Please sign in to comment.