SessionMiddleware extends AbstractWebMiddleware<HttpRequest, NRES> { protected void sessionRequest(HttpRequest request) { some(request.getCookies(), cs -> cs.get(cookieName)) .ifPresent(sessionCookie -> { String reqKey = sessionCookie.getValue(); Session session = reqKey != null ? (Session) store.read(reqKey) : null; request.setSession(session); if (session != null) { ((WebSessionAvailable) request).setSessionKey(reqKey); } }); } SessionMiddleware(); @Override HttpResponse handle(HttpRequest request, MiddlewareChain<HttpRequest, NRES, ?, ?> chain); void setCookieName(String cookieName); void setCookieAttrs(OptionMap cookieAttrs); void setStore(KeyValueStore store);  }
@Test void restoreSession() { SessionMiddleware middleware = new SessionMiddleware(); HttpRequest request = builder(new DefaultHttpRequest()) .build(); request = MixinUtils.mixin(request, WebSessionAvailable.class); UUID sessionKey = UUID.randomUUID(); Session session = new Session(); session.put("name", "kawasima"); tryReflection(() -> { Field storeField = SessionMiddleware.class.getDeclaredField("store"); storeField.setAccessible(true); MemoryStore store = (MemoryStore) storeField.get(middleware); store.write(sessionKey.toString(), session); return store; }); Map<String, Cookie> params = new HashMap<>(); params.put("enkan-session", Cookie.create("enkan-session", sessionKey.toString())); request.setCookies(params); middleware.sessionRequest(request); assertThat(request.getSession().get("name")) .isEqualTo("kawasima"); }
@Test void sessionIdNotSent() { SessionMiddleware middleware = new SessionMiddleware(); HttpRequest request = builder(new DefaultHttpRequest()) .build(); request = MixinUtils.mixin(request, WebSessionAvailable.class); UUID sessionKey = UUID.randomUUID(); Session session = new Session(); session.put("name", "kawasima"); tryReflection(() -> { Field storeField = SessionMiddleware.class.getDeclaredField("store"); storeField.setAccessible(true); MemoryStore store = (MemoryStore) storeField.get(middleware); store.write(sessionKey.toString(), session); return store; }); middleware.sessionRequest(request); assertThat(request.getSession()).isNull(); }