Search in sources :

Example 36 with ApiException

use of com.faforever.api.error.ApiException in project faf-java-api by FAForever.

the class MapServiceTest method emptyZip.

@Test
public void emptyZip() throws IOException {
    String zipFilename = "empty.zip";
    try (InputStream inputStream = loadMapResourceAsStream(zipFilename)) {
        try {
            byte[] mapData = ByteStreams.toByteArray(inputStream);
            instance.uploadMap(mapData, zipFilename, author, true);
            fail();
        } catch (ApiException e) {
            assertThat(e, apiExceptionWithCode(ErrorCode.MAP_MISSING_MAP_FOLDER_INSIDE_ZIP));
        }
        verify(mapRepository, never()).save(any(com.faforever.api.data.domain.Map.class));
    }
}
Also used : BufferedInputStream(java.io.BufferedInputStream) ZipInputStream(java.util.zip.ZipInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Map(com.faforever.api.config.FafApiProperties.Map) ApiException(com.faforever.api.error.ApiException) Test(org.junit.Test)

Example 37 with ApiException

use of com.faforever.api.error.ApiException in project faf-java-api by FAForever.

the class MapServiceTest method versionExistsAlready.

@Test
public void versionExistsAlready() throws IOException {
    String zipFilename = "scmp_037.zip";
    Player me = new Player();
    me.setId(1);
    com.faforever.api.data.domain.Map map = new com.faforever.api.data.domain.Map().setAuthor(me).setVersions(Collections.singletonList(new MapVersion().setVersion(1)));
    when(mapRepository.findOneByDisplayName(any())).thenReturn(Optional.of(map));
    try (InputStream inputStream = loadMapResourceAsStream(zipFilename)) {
        try {
            byte[] mapData = ByteStreams.toByteArray(inputStream);
            instance.uploadMap(mapData, zipFilename, me, true);
            fail();
        } catch (ApiException e) {
            assertThat(e, apiExceptionWithCode(ErrorCode.MAP_VERSION_EXISTS));
        }
        verify(mapRepository, never()).save(any(com.faforever.api.data.domain.Map.class));
    }
}
Also used : Player(com.faforever.api.data.domain.Player) BufferedInputStream(java.io.BufferedInputStream) ZipInputStream(java.util.zip.ZipInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) MapVersion(com.faforever.api.data.domain.MapVersion) Map(com.faforever.api.config.FafApiProperties.Map) ApiException(com.faforever.api.error.ApiException) Test(org.junit.Test)

Example 38 with ApiException

use of com.faforever.api.error.ApiException in project faf-java-api by FAForever.

the class UserService method changeEmail.

public void changeEmail(String currentPassword, String newEmail, User user, String ipAddress) {
    if (!passwordEncoder.matches(currentPassword, user.getPassword())) {
        throw new ApiException(new Error(ErrorCode.EMAIL_CHANGE_FAILED_WRONG_PASSWORD));
    }
    emailService.validateEmailAddress(newEmail);
    log.debug("Changing email for user ''{}'' to ''{}''", user, newEmail);
    user.setEmail(newEmail);
    createOrUpdateUser(user, ipAddress);
}
Also used : Error(com.faforever.api.error.Error) ApiException(com.faforever.api.error.ApiException)

Example 39 with ApiException

use of com.faforever.api.error.ApiException in project faf-java-api by FAForever.

the class UserService method register.

void register(String username, String email, String password) {
    log.debug("Registration requested for user: {}", username);
    validateUsername(username);
    emailService.validateEmailAddress(email);
    if (userRepository.existsByEmailIgnoreCase(email)) {
        throw new ApiException(new Error(ErrorCode.EMAIL_REGISTERED, email));
    }
    int usernameReservationTimeInMonths = properties.getUser().getUsernameReservationTimeInMonths();
    nameRecordRepository.getLastUsernameOwnerWithinMonths(username, usernameReservationTimeInMonths).ifPresent(reservedByUserId -> {
        throw new ApiException(new Error(ErrorCode.USERNAME_RESERVED, username, usernameReservationTimeInMonths));
    });
    String token = fafTokenService.createToken(FafTokenType.REGISTRATION, Duration.ofSeconds(properties.getRegistration().getLinkExpirationSeconds()), ImmutableMap.of(KEY_USERNAME, username, KEY_EMAIL, email, KEY_PASSWORD, passwordEncoder.encode(password)));
    String activationUrl = String.format(properties.getRegistration().getActivationUrlFormat(), token);
    emailService.sendActivationMail(username, email, activationUrl);
}
Also used : Error(com.faforever.api.error.Error) ApiException(com.faforever.api.error.ApiException)

Example 40 with ApiException

use of com.faforever.api.error.ApiException in project faf-java-api by FAForever.

the class FafTokenService method resolveToken.

/**
 * Verifies a token regarding its type, lifetime and signature.
 *
 * @return Map of original attributes
 * @see #createToken(FafTokenType, TemporalAmount, Map)
 */
@SneakyThrows
public Map<String, String> resolveToken(@NotNull FafTokenType expectedTokenType, @NotNull String token) {
    Map<String, String> claims;
    try {
        claims = objectMapper.readValue(JwtHelper.decodeAndVerify(token, macSigner).getClaims(), new TypeReference<Map<String, String>>() {
        });
    } catch (JsonProcessingException | IllegalArgumentException e) {
        log.warn("Unparseable token: {}", token);
        throw new ApiException(new Error(ErrorCode.TOKEN_INVALID));
    }
    if (!claims.containsKey(KEY_ACTION)) {
        log.warn("Missing key '{}' in token: {}", KEY_ACTION, token);
        throw new ApiException(new Error(ErrorCode.TOKEN_INVALID));
    }
    if (!claims.containsKey(KEY_LIFETIME)) {
        log.warn("Missing key '{}' in token: {}", KEY_LIFETIME, token);
        throw new ApiException(new Error(ErrorCode.TOKEN_INVALID));
    }
    FafTokenType actualTokenType;
    try {
        actualTokenType = FafTokenType.valueOf(claims.get(KEY_ACTION));
    } catch (IllegalArgumentException e) {
        log.warn("Unknown FAF token type '{}' in token: {}", claims.get(KEY_ACTION), token);
        throw new ApiException(new Error(ErrorCode.TOKEN_INVALID));
    }
    if (expectedTokenType != actualTokenType) {
        log.warn("Token types do not match (expected: '{}', actual: '{}') for token: {}", expectedTokenType, actualTokenType, token);
        throw new ApiException(new Error(ErrorCode.TOKEN_INVALID));
    }
    Instant expiresAt = Instant.parse(claims.get(KEY_LIFETIME));
    if (expiresAt.isBefore(Instant.now())) {
        log.debug("Token of expected type '{}' is invalid: {}", expectedTokenType, token);
        throw new ApiException(new Error(ErrorCode.TOKEN_EXPIRED));
    }
    Map<String, String> attributes = new HashMap<>(claims);
    attributes.remove(KEY_ACTION);
    attributes.remove(KEY_LIFETIME);
    return attributes;
}
Also used : HashMap(java.util.HashMap) Instant(java.time.Instant) Error(com.faforever.api.error.Error) TypeReference(com.fasterxml.jackson.core.type.TypeReference) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ApiException(com.faforever.api.error.ApiException) SneakyThrows(lombok.SneakyThrows)

Aggregations

ApiException (com.faforever.api.error.ApiException)48 Error (com.faforever.api.error.Error)29 Player (com.faforever.api.data.domain.Player)18 Test (org.junit.Test)18 ProgrammingError (com.faforever.api.error.ProgrammingError)13 SneakyThrows (lombok.SneakyThrows)11 Clan (com.faforever.api.data.domain.Clan)10 ClanMembership (com.faforever.api.data.domain.ClanMembership)7 InputStream (java.io.InputStream)7 Path (java.nio.file.Path)7 BufferedInputStream (java.io.BufferedInputStream)6 FileInputStream (java.io.FileInputStream)6 ArrayList (java.util.ArrayList)6 ZipInputStream (java.util.zip.ZipInputStream)6 Map (com.faforever.api.config.FafApiProperties.Map)5 Vote (com.faforever.api.data.domain.Vote)5 VotingSubject (com.faforever.api.data.domain.VotingSubject)5 NotFoundApiException (com.faforever.api.error.NotFoundApiException)5 Jwt (org.springframework.security.jwt.Jwt)5 LuaValue (org.luaj.vm2.LuaValue)4