Search in sources :

Example 21 with Error

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

the class AchievementService method updateSteps.

private UpdatedAchievementResponse updateSteps(int playerId, String achievementId, int steps, BiFunction<Integer, Integer, Integer> stepsFunction) {
    Achievement achievement = achievementRepository.getOne(achievementId);
    if (achievement.getType() != AchievementType.INCREMENTAL) {
        throw new ApiException(new Error(ACHIEVEMENT_NOT_INCREMENTAL, achievementId));
    }
    PlayerAchievement playerAchievement = getOrCreatePlayerAchievement(playerId, achievement, AchievementState.REVEALED);
    int currentSteps = MoreObjects.firstNonNull(playerAchievement.getCurrentSteps(), 0);
    int newCurrentSteps = stepsFunction.apply(currentSteps, steps);
    boolean newlyUnlocked = false;
    if (newCurrentSteps >= achievement.getTotalSteps()) {
        playerAchievement.setState(AchievementState.UNLOCKED);
        playerAchievement.setCurrentSteps(achievement.getTotalSteps());
        newlyUnlocked = playerAchievement.getState() != AchievementState.UNLOCKED;
    } else {
        playerAchievement.setCurrentSteps(newCurrentSteps);
    }
    playerAchievementRepository.save(playerAchievement);
    return new UpdatedAchievementResponse(achievementId, newlyUnlocked, playerAchievement.getState(), playerAchievement.getCurrentSteps());
}
Also used : Error(com.faforever.api.error.Error) PlayerAchievement(com.faforever.api.data.domain.PlayerAchievement) PlayerAchievement(com.faforever.api.data.domain.PlayerAchievement) Achievement(com.faforever.api.data.domain.Achievement) ApiException(com.faforever.api.error.ApiException)

Example 22 with Error

use of com.faforever.api.error.Error 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 23 with Error

use of com.faforever.api.error.Error 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 24 with Error

use of com.faforever.api.error.Error 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)

Example 25 with Error

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

the class VotingService method saveVote.

@Transactional
public void saveVote(Vote vote, Player player) {
    vote.setPlayer(player);
    Assert.notNull(vote.getVotingSubject(), "You must specify a subject");
    List<Error> errors = ableToVote(player, vote.getVotingSubject().getId());
    if (vote.getVotingAnswers() == null) {
        vote.setVotingAnswers(Collections.emptySet());
    }
    VotingSubject subject = votingSubjectRepository.findById(vote.getVotingSubject().getId()).orElseThrow(() -> new IllegalArgumentException("Subject of vote not found"));
    vote.getVotingAnswers().forEach(votingAnswer -> {
        VotingChoice votingChoice = votingAnswer.getVotingChoice();
        VotingChoice one = votingChoiceRepository.findById(votingChoice.getId()).orElseThrow(() -> new ApiException(new Error(ErrorCode.VOTING_CHOICE_DOES_NOT_EXIST, votingChoice.getId())));
        votingAnswer.setVotingChoice(one);
        votingAnswer.setVote(vote);
    });
    subject.getVotingQuestions().forEach(votingQuestion -> {
        List<VotingAnswer> votingAnswers = vote.getVotingAnswers().stream().filter(votingAnswer -> votingAnswer.getVotingChoice().getVotingQuestion().equals(votingQuestion)).collect(Collectors.toList());
        long countOfAnswers = votingAnswers.size();
        int maxAnswers = votingQuestion.getMaxAnswers();
        if (maxAnswers < countOfAnswers) {
            errors.add(new Error(ErrorCode.TOO_MANY_ANSWERS, countOfAnswers, maxAnswers));
        }
        if (votingQuestion.isAlternativeQuestion()) {
            for (int i = 0; i < countOfAnswers; i++) {
                int finalI = i;
                long answersWithOrdinal = votingAnswers.stream().filter(votingAnswer -> Objects.equals(votingAnswer.getAlternativeOrdinal(), finalI)).count();
                if (answersWithOrdinal == 1) {
                    continue;
                }
                errors.add(new Error(ErrorCode.MALFORMATTED_ALTERNATIVE_ORDINALS));
            }
        }
    });
    if (!errors.isEmpty()) {
        throw new ApiException(errors.toArray(new Error[0]));
    }
    voteRepository.save(vote);
}
Also used : Error(com.faforever.api.error.Error) ErrorCode(com.faforever.api.error.ErrorCode) VotingAnswer(com.faforever.api.data.domain.VotingAnswer) Transactional(javax.transaction.Transactional) ApiException(com.faforever.api.error.ApiException) GamePlayerStatsRepository(com.faforever.api.game.GamePlayerStatsRepository) Vote(com.faforever.api.data.domain.Vote) Player(com.faforever.api.data.domain.Player) Collectors(java.util.stream.Collectors) VotingChoice(com.faforever.api.data.domain.VotingChoice) ArrayList(java.util.ArrayList) Objects(java.util.Objects) List(java.util.List) OffsetDateTime(java.time.OffsetDateTime) Validity(com.faforever.api.data.domain.Validity) Service(org.springframework.stereotype.Service) Optional(java.util.Optional) VotingSubject(com.faforever.api.data.domain.VotingSubject) Collections(java.util.Collections) Assert(org.springframework.util.Assert) VotingAnswer(com.faforever.api.data.domain.VotingAnswer) Error(com.faforever.api.error.Error) VotingSubject(com.faforever.api.data.domain.VotingSubject) VotingChoice(com.faforever.api.data.domain.VotingChoice) ApiException(com.faforever.api.error.ApiException) Transactional(javax.transaction.Transactional)

Aggregations

ApiException (com.faforever.api.error.ApiException)29 Error (com.faforever.api.error.Error)29 ProgrammingError (com.faforever.api.error.ProgrammingError)13 SneakyThrows (lombok.SneakyThrows)11 Path (java.nio.file.Path)6 ArrayList (java.util.ArrayList)6 Player (com.faforever.api.data.domain.Player)5 NotFoundApiException (com.faforever.api.error.NotFoundApiException)5 LuaValue (org.luaj.vm2.LuaValue)4 Transactional (org.springframework.transaction.annotation.Transactional)4 Clan (com.faforever.api.data.domain.Clan)3 User (com.faforever.api.data.domain.User)3 InvitationResult (com.faforever.api.clan.result.InvitationResult)2 Achievement (com.faforever.api.data.domain.Achievement)2 Avatar (com.faforever.api.data.domain.Avatar)2 ClanMembership (com.faforever.api.data.domain.ClanMembership)2 Map (com.faforever.api.data.domain.Map)2 PlayerAchievement (com.faforever.api.data.domain.PlayerAchievement)2 Vote (com.faforever.api.data.domain.Vote)2 VotingSubject (com.faforever.api.data.domain.VotingSubject)2