io.vertx.core.http.Cookie Java Examples

The following examples show how to use io.vertx.core.http.Cookie. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ApiDispatcher.java    From servicecomb-samples with Apache License 2.0 6 votes vote down vote up
protected void onRequest(RoutingContext context) {
  Map<String, String> pathParams = context.pathParams();
  String microserviceName = pathParams.get("param0");
  String path = "/" + pathParams.get("param1");

  EdgeInvocation invoker = new EdgeInvocation() {
    // Authentication. Notice: adding context must after setContext or will override by network
    protected void setContext() throws Exception {
      super.setContext();
      // get session id from header and cookie for debug reasons
      String sessionId = context.request().getHeader("session-id");
      if (sessionId != null) {
        this.invocation.addContext("session-id", sessionId);
      } else {
        Cookie sessionCookie = context.cookieMap().get("session-id");
        if (sessionCookie != null) {
          this.invocation.addContext("session-id", sessionCookie.getValue());
        }
      }
    }
  };
  invoker.init(microserviceName, context, path, httpServerFilters);
  invoker.edgeInvoke();
}
 
Example #2
Source File: UidsCookieServiceTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnRubiconCookieValueFromHostCookieWhenUidValueIsPresentButDiffers() {
    // given
    uidsCookieService = new UidsCookieService(
            "trp_optout", "true", "rubicon", "khaos", "cookie-domain", 90, MAX_COOKIE_SIZE_BYTES, jacksonMapper);

    final Map<String, Cookie> cookies = new HashMap<>();
    // this uids cookie value stands for {"uids":{"rubicon":"J5VLCWQP-26-CWFT","adnxs":"12345"}}
    cookies.put("uids", Cookie.cookie("uids",
            "eyJ1aWRzIjp7InJ1Ymljb24iOiJKNVZMQ1dRUC0yNi1DV0ZUIiwiYWRueHMiOiIxMjM0NSJ9fQ=="));
    cookies.put("khaos", Cookie.cookie("khaos", "abc123"));

    given(routingContext.cookieMap()).willReturn(cookies);

    // when
    final UidsCookie uidsCookie = uidsCookieService.parseFromRequest(routingContext);

    // then
    assertThat(uidsCookie.uidFrom(RUBICON)).isEqualTo("abc123");
}
 
Example #3
Source File: ApiDispatcher.java    From servicecomb-samples with Apache License 2.0 6 votes vote down vote up
protected void onRequest(RoutingContext context) {
  Map<String, String> pathParams = context.pathParams();
  String microserviceName = pathParams.get("param0");
  String path = "/" + pathParams.get("param1");

  EdgeInvocation invoker = new EdgeInvocation() {
    // Authentication. Notice: adding context must after setContext or will override by network
    protected void setContext() throws Exception {
      super.setContext();
      // get session id from header and cookie for debug reasons
      String sessionId = context.request().getHeader("session-id");
      if (sessionId != null) {
        this.invocation.addContext("session-id", sessionId);
      } else {
        Cookie sessionCookie = context.cookieMap().get("session-id");
        if (sessionCookie != null) {
          this.invocation.addContext("session-id", sessionCookie.getValue());
        }
      }
    }
  };
  invoker.init(microserviceName, context, path, httpServerFilters);
  invoker.edgeInvoke();
}
 
Example #4
Source File: UidsCookieServiceTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSkipFacebookSentinelFromUidsCookie() throws JsonProcessingException {
    // given
    final Map<String, UidWithExpiry> uidsWithExpiry = new HashMap<>();
    uidsWithExpiry.put(RUBICON, UidWithExpiry.live("J5VLCWQP-26-CWFT"));
    uidsWithExpiry.put("audienceNetwork", UidWithExpiry.live("0"));
    final Uids uids = Uids.builder().uids(uidsWithExpiry).build();
    final String encodedUids = encodeUids(uids);

    given(routingContext.cookieMap()).willReturn(singletonMap("uids", Cookie.cookie("uids", encodedUids)));

    // when
    final UidsCookie uidsCookie = uidsCookieService.parseFromRequest(routingContext);

    // then
    assertThat(uidsCookie).isNotNull();
    assertThat(uidsCookie.uidFrom(RUBICON)).isEqualTo("J5VLCWQP-26-CWFT");
    assertThat(uidsCookie.uidFrom("audienceNetwork")).isNull();
}
 
Example #5
Source File: UidsCookieServiceTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnUidsCookieWithOptoutFalseIfOptoutCookieHasNotExpectedValue() {
    // given
    final Map<String, Cookie> cookies = new HashMap<>();
    // this uids cookie value stands for {"uids":{"rubicon":"J5VLCWQP-26-CWFT","adnxs":"12345"}}
    cookies.put("uids", Cookie.cookie("uids",
            "eyJ1aWRzIjp7InJ1Ymljb24iOiJKNVZMQ1dRUC0yNi1DV0ZUIiwiYWRueHMiOiIxMjM0NSJ9fQ=="));
    cookies.put(OPT_OUT_COOKIE_NAME, Cookie.cookie(OPT_OUT_COOKIE_NAME, "dummy"));

    given(routingContext.cookieMap()).willReturn(cookies);

    // when
    final UidsCookie uidsCookie = uidsCookieService.parseFromRequest(routingContext);

    // then
    assertThat(uidsCookie.allowsSync()).isTrue();
    assertThat(uidsCookie.uidFrom(RUBICON)).isEqualTo("J5VLCWQP-26-CWFT");
    assertThat(uidsCookie.uidFrom(ADNXS)).isEqualTo("12345");
}
 
Example #6
Source File: UidsCookieServiceTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnUidsCookieWithOptoutTrueIfUidsCookieIsPresentAndOptoutCookieHasExpectedValue() {
    // given
    final Map<String, Cookie> cookies = new HashMap<>();
    // this uids cookie value stands for {"uids":{"rubicon":"J5VLCWQP-26-CWFT","adnxs":"12345"}}
    cookies.put("uids", Cookie.cookie("uids",
            "eyJ1aWRzIjp7InJ1Ymljb24iOiJKNVZMQ1dRUC0yNi1DV0ZUIiwiYWRueHMiOiIxMjM0NSJ9fQ=="));
    cookies.put(OPT_OUT_COOKIE_NAME, Cookie.cookie(OPT_OUT_COOKIE_NAME, OPT_OUT_COOKIE_VALUE));

    given(routingContext.cookieMap()).willReturn(cookies);

    // when
    final UidsCookie uidsCookie = uidsCookieService.parseFromRequest(routingContext);

    // then
    assertThat(uidsCookie.allowsSync()).isFalse();
    assertThat(uidsCookie.uidFrom(RUBICON)).isNull();
    assertThat(uidsCookie.uidFrom(ADNXS)).isNull();
}
 
Example #7
Source File: UidsCookieServiceTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCreateUidsFromLegacyUidsIfUidsAreMissed() {
    // given
    // this uids cookie value stands for
    // {"uids":{"rubicon":"J5VLCWQP-26-CWFT"},"tempUIDs":{}},"bday":"2017-08-15T19:47:59.523908376Z"}
    given(routingContext.cookieMap()).willReturn(singletonMap("uids", Cookie.cookie(
            "uids",
            "eyJ1aWRzIjp7InJ1Ymljb24iOiJKNVZMQ1dRUC0yNi1DV0ZUIn0sInRlbXBVSURzIjp7fX0sImJkYXkiOiIyMDE3LTA"
                    + "4LTE1VDE5OjQ3OjU5LjUyMzkwODM3NloifQ==")));

    // when
    final UidsCookie uidsCookie = uidsCookieService.parseFromRequest(routingContext);

    // then
    assertThat(uidsCookie).isNotNull();
    assertThat(uidsCookie.uidFrom(RUBICON)).isEqualTo("J5VLCWQP-26-CWFT");
}
 
Example #8
Source File: UidsCookieServiceTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnNonEmptyUidsCookie() {
    // given
    // this uids cookie value stands for {"uids":{"rubicon":"J5VLCWQP-26-CWFT","adnxs":"12345"}}
    given(routingContext.cookieMap()).willReturn(singletonMap("uids", Cookie.cookie(
            "uids",
            "eyJ1aWRzIjp7InJ1Ymljb24iOiJKNVZMQ1dRUC0yNi1DV0ZUIiwiYWRueHMiOiIxMjM0NSJ9fQ==")));

    // when
    final UidsCookie uidsCookie = uidsCookieService.parseFromRequest(routingContext);

    // then
    assertThat(uidsCookie).isNotNull();
    assertThat(uidsCookie.uidFrom(RUBICON)).isEqualTo("J5VLCWQP-26-CWFT");
    assertThat(uidsCookie.uidFrom(ADNXS)).isEqualTo("12345");
}
 
Example #9
Source File: OptoutHandlerTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    given(routingContext.request()).willReturn(httpRequest);
    given(routingContext.response()).willReturn(httpResponse);

    given(httpRequest.getFormAttribute("g-recaptcha-response")).willReturn("recaptcha1");

    given(httpResponse.putHeader(any(CharSequence.class), anyString())).willReturn(httpResponse);
    given(httpResponse.setStatusCode(anyInt())).willReturn(httpResponse);

    given(googleRecaptchaVerifier.verify(anyString())).willReturn(Future.succeededFuture());

    given(uidsCookieService.toCookie(any())).willReturn(Cookie.cookie("cookie", "value"));
    given(uidsCookieService.parseFromRequest(any()))
            .willReturn(new UidsCookie(Uids.builder().uids(emptyMap()).build(), jacksonMapper));

    optoutHandler = new OptoutHandler(googleRecaptchaVerifier, uidsCookieService,
            OptoutHandler.getOptoutRedirectUrl("http://external/url"), "http://optout/url", "http://optin/url");
}
 
Example #10
Source File: SetuidHandlerTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    final Map<Integer, PrivacyEnforcementAction> vendorIdToGdpr = singletonMap(null,
            PrivacyEnforcementAction.allowAll());
    given(tcfDefinerService.resultForVendorIds(anySet(), any(), any(), any(), any(), any()))
            .willReturn(Future.succeededFuture(TcfResponse.of(true, vendorIdToGdpr, null)));

    given(routingContext.request()).willReturn(httpRequest);
    given(routingContext.response()).willReturn(httpResponse);

    given(httpResponse.headers()).willReturn(new CaseInsensitiveHeaders());

    given(uidsCookieService.toCookie(any())).willReturn(Cookie.cookie("test", "test"));
    given(bidderCatalog.names()).willReturn(new HashSet<>(asList("rubicon", "audienceNetwork")));
    given(bidderCatalog.isActive(any())).willReturn(true);
    given(bidderCatalog.usersyncerByName(any())).willReturn(
            new Usersyncer(RUBICON, null, null, null, false));

    final Clock clock = Clock.fixed(Instant.now(), ZoneId.systemDefault());
    final TimeoutFactory timeoutFactory = new TimeoutFactory(clock);
    setuidHandler = new SetuidHandler(2000, uidsCookieService, applicationSettings,
            bidderCatalog, tcfDefinerService, null, false, analyticsReporter, metrics, timeoutFactory);
}
 
Example #11
Source File: SetuidHandlerTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRespondWithoutCookieIfGdprProcessingPreventsCookieSetting() {
    // given
    final PrivacyEnforcementAction privacyEnforcementAction = PrivacyEnforcementAction.restrictAll();
    given(tcfDefinerService.resultForVendorIds(anySet(), any(), any(), any(), any(), any()))
            .willReturn(Future.succeededFuture(
                    TcfResponse.of(true, singletonMap(null, privacyEnforcementAction), null)));

    given(uidsCookieService.parseFromRequest(any()))
            .willReturn(new UidsCookie(Uids.builder().uids(emptyMap()).build(), jacksonMapper));

    given(httpRequest.getParam("bidder")).willReturn(RUBICON);

    given(httpResponse.setStatusCode(anyInt())).willReturn(httpResponse);

    // when
    setuidHandler.handle(routingContext);

    // then
    verify(routingContext, never()).addCookie(any(Cookie.class));
    verify(httpResponse).setStatusCode(eq(200));
    verify(httpResponse).end(eq("The gdpr_consent param prevents cookies from being saved"));
}
 
Example #12
Source File: SetuidHandlerTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRespondWithInternalServerErrorStatusIfGdprProcessingFailsWithUnexpectedException() {
    // given
    given(tcfDefinerService.resultForVendorIds(anySet(), any(), any(), any(), any(), any()))
            .willReturn(Future.failedFuture("unexpected error"));

    given(uidsCookieService.parseFromRequest(any()))
            .willReturn(new UidsCookie(Uids.builder().uids(emptyMap()).build(), jacksonMapper));

    given(httpRequest.getParam("bidder")).willReturn(RUBICON);

    given(httpResponse.setStatusCode(anyInt())).willReturn(httpResponse);

    // when
    setuidHandler.handle(routingContext);

    // then
    verify(httpResponse, never()).sendFile(any());
    verify(routingContext, never()).addCookie(any(Cookie.class));
    verify(httpResponse).setStatusCode(eq(500));
    verify(httpResponse).end(eq("Unexpected GDPR processing error"));
}
 
Example #13
Source File: ClassFactoryTest.java    From rest.vertx with Apache License 2.0 6 votes vote down vote up
@Test
void constructViaContext() throws ClassFactoryException {

    RoutingContext context = Mockito.mock(RoutingContext.class);
    HttpServerRequest request = Mockito.mock(HttpServerRequest.class);

    Mockito.when(context.request()).thenReturn(request);
    Mockito.when(request.getParam("path")).thenReturn("SomePath");
    Mockito.when(request.getHeader("MyHeader")).thenReturn("true");
    Mockito.when(request.query()).thenReturn("query=1");
    Mockito.when(request.getCookie("chocolate")).thenReturn(Cookie.cookie("chocolate", "tasty"));

    MyComplexBean instance = (MyComplexBean)ClassFactory.newInstanceOf(MyComplexBean.class, context);
    assertNotNull(instance);
    assertEquals("Header: true, Path: SomePath, Query: 1, Cookie: tasty, Matrix: null", instance.toString());
}
 
Example #14
Source File: UidsCookieService.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@link Cookie} with 'uids' as a name and encoded JSON string representing supplied {@link UidsCookie}
 * as a value.
 */
public Cookie toCookie(UidsCookie uidsCookie) {
    UidsCookie modifiedUids = uidsCookie;
    byte[] cookieBytes = uidsCookie.toJson().getBytes();

    while (maxCookieSizeBytes > 0 && cookieBytes.length > maxCookieSizeBytes) {
        final String familyName = modifiedUids.getCookieUids().getUids().entrySet().stream()
                .reduce(UidsCookieService::getClosestExpiration)
                .map(Map.Entry::getKey)
                .orElse(null);
        modifiedUids = modifiedUids.deleteUid(familyName);
        cookieBytes = modifiedUids.toJson().getBytes();
    }

    final Cookie cookie = Cookie
            .cookie(COOKIE_NAME, Base64.getUrlEncoder().encodeToString(cookieBytes))
            .setPath("/")
            .setMaxAge(ttlSeconds);

    if (StringUtils.isNotBlank(hostCookieDomain)) {
        cookie.setDomain(hostCookieDomain);
    }

    return cookie;
}
 
Example #15
Source File: VertxVaadinRequestUT.java    From vertx-vaadin with MIT License 6 votes vote down vote up
@Test
public void shouldDelegateGetCookies() {
    Cookie cookie1 = Cookie.cookie("cookie1", "value1")
        .setDomain("domain").setHttpOnly(true)
        .setMaxAge(90L).setPath("path").setSecure(true);
    Cookie cookie2 = Cookie.cookie("cookie2", "value2");
    when(routingContext.cookieCount()).thenReturn(0).thenReturn(2);
    when(routingContext.cookieMap()).thenReturn(Stream.of(cookie1, cookie2).collect(Collectors.toMap(Cookie::getName, identity())));
    assertThat(vaadinRequest.getCookies()).isNull();
    javax.servlet.http.Cookie[] cookies = vaadinRequest.getCookies();
    assertThat(cookies).hasSize(2);
    assertThat(cookies[0]).extracting("name", "value", "domain", "httpOnly", "maxAge", "path", "secure")
        .containsExactly(cookie1.getName(), cookie1.getValue(), cookie1.getDomain(), true, 90, "path", true);
    assertThat(cookies[1]).extracting("name", "value", "domain", "httpOnly", "maxAge", "path", "secure")
        .containsExactly(cookie2.getName(), cookie2.getValue(), null, false, -1, null, false);
}
 
Example #16
Source File: SetuidHandlerTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRespondWithBadRequestStatusIfGdprProcessingFailsWithInvalidRequestException() {
    // given
    given(tcfDefinerService.resultForVendorIds(anySet(), any(), any(), any(), any(), any()))
            .willReturn(Future.failedFuture(new InvalidRequestException("gdpr exception")));

    given(uidsCookieService.parseFromRequest(any()))
            .willReturn(new UidsCookie(Uids.builder().uids(emptyMap()).build(), jacksonMapper));

    given(httpRequest.getParam("bidder")).willReturn(RUBICON);

    given(httpResponse.setStatusCode(anyInt())).willReturn(httpResponse);

    // when
    setuidHandler.handle(routingContext);

    // then
    verify(routingContext, never()).addCookie(any(Cookie.class));
    verify(httpResponse).setStatusCode(eq(400));
    verify(httpResponse).end(eq("GDPR processing failed with error: gdpr exception"));
}
 
Example #17
Source File: ClassFactoryTest.java    From rest.vertx with Apache License 2.0 6 votes vote down vote up
@Test
void constructViaContextFail() throws ClassFactoryException {

    RoutingContext context = Mockito.mock(RoutingContext.class);
    HttpServerRequest request = Mockito.mock(HttpServerRequest.class);

    Mockito.when(context.request()).thenReturn(request);
    Mockito.when(request.getParam("path")).thenReturn("SomePath");
    Mockito.when(request.getHeader("MyHeader")).thenReturn("BLA"); // invalid type
    Mockito.when(request.query()).thenReturn("query=A"); // invalid type
    Mockito.when(request.getCookie("chocolate")).thenReturn(Cookie.cookie("chocolate", "tasty"));

    ClassFactoryException ex = assertThrows(ClassFactoryException.class, () -> ClassFactory.newInstanceOf(MyComplexBean.class, context));
    assertEquals("Failed to instantiate class, with constructor: " +
                    "com.zandero.rest.test.data.MyComplexBean(String arg0=SomePath, boolean arg1=BLA, int arg2=A, String arg3=tasty). " +
                    "Failed to convert value: 'A', to primitive type: int",
            ex.getMessage());
}
 
Example #18
Source File: CSRFHandlerImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
private String generateAndStoreToken(RoutingContext ctx) {
  byte[] salt = new byte[32];
  random.nextBytes(salt);

  String saltPlusToken = BASE64.encodeToString(salt) + "." + System.currentTimeMillis();
  String signature = BASE64.encodeToString(mac.doFinal(saltPlusToken.getBytes()));

  final String token = saltPlusToken + "." + signature;
  // a new token was generated add it to the cookie
  ctx.addCookie(
    Cookie.cookie(cookieName, token)
      .setPath(cookiePath)
      .setHttpOnly(httpOnly)
      // it's not an option to change the same site policy
      .setSameSite(CookieSameSite.STRICT));

  return token;
}
 
Example #19
Source File: QuarkusRequestWrapper.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public Cookie getCookie(String name) {
    if (name.equals(FAKE_COOKIE_NAME)) {
        return new QuarkusCookie();
    }
    return super.getCookie(name);
}
 
Example #20
Source File: CookieItemTest.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void serverFormattedElement() {
  HashMap<String, Cookie> cookieSet = new HashMap<>();
  CookieImpl cookie = new CookieImpl(COOKIE_NAME, COOKIE_VALUE);

  cookieSet.put(cookie.getName(), cookie);
  when(mockContext.cookieCount()).thenReturn(1);
  when(mockContext.cookieMap()).thenReturn(cookieSet);
  accessLogEvent.setRoutingContext(mockContext);

  ELEMENT.appendServerFormattedItem(accessLogEvent, strBuilder);
  Assert.assertEquals(COOKIE_VALUE, strBuilder.toString());
}
 
Example #21
Source File: CookieItemTest.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void serverFormattedElementOnCookieCountIsZero() {
  HashMap<String, Cookie> cookieSet = new HashMap<>();
  Mockito.when(mockContext.cookieCount()).thenReturn(0);
  Mockito.when(mockContext.cookieMap()).thenReturn(cookieSet);
  accessLogEvent.setRoutingContext(mockContext);

  ELEMENT.appendServerFormattedItem(accessLogEvent, strBuilder);
  Assert.assertEquals("-", strBuilder.toString());
}
 
Example #22
Source File: CookieItemTest.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void serverFormattedElementOnNotFound() {
  HashMap<String, Cookie> cookieSet = new HashMap<>();
  CookieImpl cookie = new CookieImpl("anotherCookieName", COOKIE_VALUE);
  cookieSet.put(cookie.getName(), cookie);
  Mockito.when(mockContext.cookieCount()).thenReturn(1);
  Mockito.when(mockContext.cookieMap()).thenReturn(cookieSet);
  accessLogEvent.setRoutingContext(mockContext);

  ELEMENT.appendServerFormattedItem(accessLogEvent, strBuilder);
  Assert.assertEquals("-", strBuilder.toString());
}
 
Example #23
Source File: SessionHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private String getSessionId(RoutingContext  context) {
  if (cookieless) {
    // cookieless sessions store the session on the path or the request
    // a session is identified by a sequence of characters between braces
    String path = context.normalizedPath();
    int s = -1;
    int e = -1;
    for (int i = 0; i < path.length(); i++) {
      if (path.charAt(i) == '(') {
        s = i + 1;
        continue;
      }
      if (path.charAt(i) == ')') {
        // if not open parenthesis yet
        // this is a false end, continue looking
        if (s != -1) {
          e = i;
          break;
        }
      }
    }
    if (s != -1 && e != -1 && s < e) {
      return path.substring(s, e);
    }
  } else {
    Cookie cookie = context.getCookie(sessionCookieName);
    if (cookie != null) {
      // Look up sessionId
      return cookie.getValue();
    }
  }

  return null;
}
 
Example #24
Source File: SessionHandlerImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
private Cookie sessionCookie(final RoutingContext context, final Session session) {
  Cookie cookie = context.getCookie(sessionCookieName);
  if (cookie != null) {
    return cookie;
  }
  cookie = Cookie.cookie(sessionCookieName, session.value());
  cookie.setPath(sessionCookiePath);
  cookie.setSecure(sessionCookieSecure);
  cookie.setHttpOnly(sessionCookieHttpOnly);
  cookie.setSameSite(cookieSameSite);
  // Don't set max age - it's a session cookie
  context.addCookie(cookie);
  return cookie;
}
 
Example #25
Source File: CookieAccessItem.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public void appendServerFormattedItem(ServerAccessLogEvent accessLogEvent, StringBuilder builder) {
  Map<String, Cookie> cookieMap = accessLogEvent.getRoutingContext().cookieMap();
  if (null == cookieMap) {
    builder.append(RESULT_NOT_FOUND);
    return;
  }
  for (Cookie cookie : cookieMap.values()) {
    if (varName.equals(cookie.getName())) {
      builder.append(cookie.getValue());
      return;
    }
  }
  builder.append(RESULT_NOT_FOUND);
}
 
Example #26
Source File: SetuidHandlerTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRespondWithCookieFromRequestParam() throws IOException {
    // given
    given(uidsCookieService.parseFromRequest(any()))
            .willReturn(new UidsCookie(Uids.builder().uids(emptyMap()).build(), jacksonMapper));

    // {"tempUIDs":{"rubicon":{"uid":"J5VLCWQP-26-CWFT"}}}
    given(uidsCookieService.toCookie(any())).willReturn(Cookie
            .cookie("uids", "eyJ0ZW1wVUlEcyI6eyJydWJpY29uIjp7InVpZCI6Iko1VkxDV1FQLTI2LUNXRlQifX19"));

    given(httpRequest.getParam("bidder")).willReturn(RUBICON);
    given(httpRequest.getParam("format")).willReturn("img");
    given(httpRequest.getParam("uid")).willReturn("J5VLCWQP-26-CWFT");

    given(httpResponse.setStatusCode(anyInt())).willReturn(httpResponse);

    // when
    setuidHandler.handle(routingContext);

    // then
    verify(routingContext, never()).addCookie(any(Cookie.class));
    verify(httpResponse).sendFile(any());

    final String uidsCookie = getUidsCookie();
    final Uids decodedUids = decodeUids(uidsCookie);
    assertThat(decodedUids.getUids()).hasSize(1);
    assertThat(decodedUids.getUids().get(RUBICON).getUid()).isEqualTo("J5VLCWQP-26-CWFT");
}
 
Example #27
Source File: FormAuthenticationMechanism.java    From quarkus with Apache License 2.0 5 votes vote down vote up
protected void handleRedirectBack(final RoutingContext exchange) {
    Cookie redirect = exchange.getCookie(locationCookie);
    String location;
    if (redirect != null) {
        location = redirect.getValue();
        exchange.response().addCookie(redirect.setMaxAge(0));
    } else {
        location = exchange.request().scheme() + "://" + exchange.request().host() + landingPage;
    }
    exchange.response().setStatusCode(302);
    exchange.response().headers().add(HttpHeaderNames.LOCATION, location);
    exchange.response().end();
}
 
Example #28
Source File: SetuidHandlerTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldUpdateUidInCookieWithRequestValue() throws IOException {
    // given
    final Map<String, UidWithExpiry> uids = new HashMap<>();
    uids.put(RUBICON, UidWithExpiry.live("J5VLCWQP-26-CWFT"));
    uids.put(ADNXS, UidWithExpiry.live("12345"));
    given(uidsCookieService.parseFromRequest(any()))
            .willReturn(new UidsCookie(Uids.builder().uids(uids).build(), jacksonMapper));

    given(httpRequest.getParam("bidder")).willReturn(RUBICON);
    given(httpRequest.getParam("uid")).willReturn("updatedUid");

    // {"tempUIDs":{"adnxs":{"uid":"12345"}, "rubicon":{"uid":"updatedUid"}}}
    given(uidsCookieService.toCookie(any())).willReturn(Cookie
            .cookie("uids", "eyJ0ZW1wVUlEcyI6eyJhZG54cyI6eyJ1aWQiOiIxMjM0NSJ9LCAicnViaWNvbiI6eyJ1aWQiOiJ1cGRhdGVkVW"
                    + "lkIn19fQ=="));

    // when
    setuidHandler.handle(routingContext);

    // then
    verify(httpResponse).end();
    verify(routingContext, never()).addCookie(any(Cookie.class));

    final String uidsCookie = getUidsCookie();
    final Uids decodedUids = decodeUids(uidsCookie);
    assertThat(decodedUids.getUids()).hasSize(2);
    assertThat(decodedUids.getUids().get(RUBICON).getUid()).isEqualTo("updatedUid");
    assertThat(decodedUids.getUids().get(ADNXS).getUid()).isEqualTo("12345");
}
 
Example #29
Source File: HttpUtilTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Test
public void cookiesAsMapShouldReturnExpectedResult() {
    // given
    given(routingContext.cookieMap()).willReturn(singletonMap("name", Cookie.cookie("name", "value")));

    // when
    final Map<String, String> cookies = HttpUtil.cookiesAsMap(routingContext);

    // then
    assertThat(cookies).hasSize(1)
            .containsOnly(entry("name", "value"));
}
 
Example #30
Source File: SetuidHandlerTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRespondWithCookieIfUserIsNotInGdprScope() throws IOException {
    // given
    given(tcfDefinerService.resultForVendorIds(anySet(), any(), any(), any(), any(), any()))
            .willReturn(Future.succeededFuture(TcfResponse.of(false, emptyMap(), null)));

    given(uidsCookieService.parseFromRequest(any()))
            .willReturn(new UidsCookie(Uids.builder().uids(emptyMap()).build(), jacksonMapper));

    // {"tempUIDs":{"rubicon":{"uid":"J5VLCWQP-26-CWFT"}}}
    given(uidsCookieService.toCookie(any())).willReturn(Cookie
            .cookie("uids", "eyJ0ZW1wVUlEcyI6eyJydWJpY29uIjp7InVpZCI6Iko1VkxDV1FQLTI2LUNXRlQifX19"));

    given(httpRequest.getParam("bidder")).willReturn(RUBICON);
    given(httpRequest.getParam("uid")).willReturn("J5VLCWQP-26-CWFT");

    given(httpResponse.setStatusCode(anyInt())).willReturn(httpResponse);

    // when
    setuidHandler.handle(routingContext);

    // then
    verify(routingContext, never()).addCookie(any(Cookie.class));
    verify(httpResponse).end();

    final String uidsCookie = getUidsCookie();
    final Uids decodedUids = decodeUids(uidsCookie);
    assertThat(decodedUids.getUids()).hasSize(1);
    assertThat(decodedUids.getUids().get(RUBICON).getUid()).isEqualTo("J5VLCWQP-26-CWFT");
}