use of io.micronaut.session.annotation.SessionValue in project micronaut-core by micronaut-projects.
the class HttpSessionFilter method encodeSessionId.
private Publisher<MutableHttpResponse<?>> encodeSessionId(HttpRequest<?> request, Publisher<MutableHttpResponse<?>> responsePublisher) {
Flux<SessionAndResponse> responseFlowable = Flux.from(responsePublisher).switchMap(response -> {
Optional<MethodExecutionHandle> routeMatch = request.getAttribute(HttpAttributes.ROUTE_MATCH, MethodExecutionHandle.class);
Optional<?> body = response.getBody();
String sessionAttr;
if (body.isPresent()) {
sessionAttr = routeMatch.flatMap(m -> {
if (!m.hasAnnotation(SessionValue.class)) {
return Optional.empty();
} else {
String attributeName = m.stringValue(SessionValue.class).orElse(null);
if (!StringUtils.isEmpty(attributeName)) {
return Optional.of(attributeName);
} else {
throw new InternalServerException("@SessionValue on a return type must specify an attribute name");
}
}
}).orElse(null);
} else {
sessionAttr = null;
}
Optional<Session> opt = request.getAttributes().get(SESSION_ATTRIBUTE, Session.class);
if (opt.isPresent()) {
Session session = opt.get();
if (sessionAttr != null) {
session.put(sessionAttr, body.get());
}
if (session.isNew() || session.isModified()) {
return Flux.from(Publishers.fromCompletableFuture(() -> sessionStore.save(session))).map(s -> new SessionAndResponse(Optional.of(s), response));
}
} else if (sessionAttr != null) {
Session newSession = sessionStore.newSession();
newSession.put(sessionAttr, body.get());
return Flux.from(Publishers.fromCompletableFuture(() -> sessionStore.save(newSession))).map(s -> new SessionAndResponse(Optional.of(s), response));
}
return Flux.just(new SessionAndResponse(opt, response));
});
return responseFlowable.map(sessionAndResponse -> {
Optional<Session> session = sessionAndResponse.session;
MutableHttpResponse<?> response = sessionAndResponse.response;
if (session.isPresent()) {
Session s = session.get();
for (HttpSessionIdEncoder encoder : encoders) {
encoder.encodeId(request, response, s);
}
}
return response;
});
}
Aggregations