ApiKeyFilter implements Filter { @Override public Payload apply(String uri, Context context, PayloadSupplier nextFilter) throws Exception { if (context.cookies().get(dsCookieName()) != null) { return nextFilter.get(); } String apiKey = readApiKeyInHeader(context); if (apiKey != null) { String login = apiKeyStore.getLogin(apiKey); if (login != null) { User user = users.find(login); context.setCurrentUser(user); return nextFilter.get().withHeader(CACHE_CONTROL, "must-revalidate"); } } return new Payload(UNAUTHORIZED); } @Inject  ApiKeyFilter(UsersWritable users, ApiKeyStore apiKeyStore); @Override boolean matches(String uri, Context context); @Override Payload apply(String uri, Context context, PayloadSupplier nextFilter);  }
@Test public void test_adds_user_to_context() throws Exception { when(context.header("authorization")).thenReturn("Bearer session_id"); when(apiKeyStore.getLogin("session_id")).thenReturn("user_id"); when(users.find("user_id")).thenReturn(new DatashareUser("user_id")); Payload payload = apiKeyFilter.apply("url", context, nextFilter); assertThat(payload).isSameAs(next); verify(context).setCurrentUser(user.capture()); assertThat(user.getValue().login()).isEqualTo("user_id"); }
@Test public void test_unauthorized_if_type_is_not_bearer() throws Exception { when(context.header("authorization")).thenReturn("Basic session_id"); Payload payload = apiKeyFilter.apply("url", context, nextFilter); assertThat(payload.code()).isEqualTo(401); }
@Test public void test_unauthorized_if_no_type() throws Exception { when(context.header("authorization")).thenReturn("session_id"); Payload payload = apiKeyFilter.apply("url", context, nextFilter); assertThat(payload.code()).isEqualTo(401); }
@Test public void test_does_nothing_if_there_is_datashare_cookie() throws Exception { when(context.cookies()).thenReturn(new SimpleCookies() {{ put("_ds_session_id", new NewCookie("_ds_session_id", "cookie value")); }}); Payload payload = apiKeyFilter.apply("url", context, nextFilter); assertThat(payload).isSameAs(next); }