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());
}
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);
}
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);
}
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;
}
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);
}
Aggregations