78 lines
2.5 KiB
Java
78 lines
2.5 KiB
Java
package de.nclazz.service.mailrelay.adapter.web;
|
|
|
|
import de.nclazz.service.mailrelay.domain.Message;
|
|
import de.nclazz.service.mailrelay.domain.Relay;
|
|
import lombok.RequiredArgsConstructor;
|
|
import lombok.extern.slf4j.Slf4j;
|
|
import org.springframework.stereotype.Controller;
|
|
import org.springframework.validation.BindingResult;
|
|
import org.springframework.web.bind.annotation.PostMapping;
|
|
import org.springframework.web.bind.annotation.RequestHeader;
|
|
import org.springframework.web.bind.annotation.RequestMapping;
|
|
|
|
import javax.validation.Valid;
|
|
import java.net.URLEncoder;
|
|
import java.nio.charset.StandardCharsets;
|
|
import java.time.Clock;
|
|
import java.time.LocalDateTime;
|
|
import java.util.stream.Collectors;
|
|
|
|
@Controller
|
|
@Slf4j
|
|
@RequestMapping("send")
|
|
@RequiredArgsConstructor
|
|
public class MessageFormController {
|
|
|
|
private final Relay relay;
|
|
private final Clock clock;
|
|
|
|
@PostMapping
|
|
public String forwardMessage(@RequestHeader(name = "Referer", required = false)String referer,
|
|
@Valid MessageForm form,
|
|
BindingResult bindingResult) {
|
|
|
|
if(bindingResult.hasErrors()) {
|
|
String onError = formatErrorRedirect(referer, form, bindingResult);
|
|
return "redirect:" + onError;
|
|
}
|
|
|
|
String token = form.getToken();
|
|
Message message = form.toMessage(LocalDateTime.now(this.clock));
|
|
|
|
this.relay.forwardMessage(token, message);
|
|
|
|
String redirect = referer;
|
|
|
|
if(form.getOnSuccess() != null) {
|
|
redirect = form.getOnSuccess();
|
|
}
|
|
|
|
return "redirect:" + addRefererToRelativeUrl(referer, redirect);
|
|
}
|
|
|
|
private String formatErrorRedirect(String referer, MessageForm form, BindingResult bindingResult) {
|
|
String queryParams = bindingResult.getAllErrors().stream()
|
|
.map(ValidationError::fromObjectError)
|
|
.map(MessageFormController::mapValidationErrorToQueryParam)
|
|
.distinct()
|
|
.collect(Collectors.joining("&"));
|
|
String origin = form.getOnError() != null ? form.getOnError() : referer;
|
|
|
|
return addRefererToRelativeUrl(referer, origin) + "?" + queryParams;
|
|
}
|
|
|
|
private String addRefererToRelativeUrl(String referer, String url) {
|
|
if(!url.startsWith("/")) {
|
|
return url;
|
|
}
|
|
return referer + url;
|
|
}
|
|
|
|
private static String mapValidationErrorToQueryParam(ValidationError error) {
|
|
return String.format("%s=%s", error.getTarget(), URLEncoder.encode(error.getCode(), StandardCharsets.UTF_8));
|
|
}
|
|
|
|
|
|
|
|
}
|