/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * license agreements; and to You under the Apache License, version 2.0:
 *
 *   https://www.apache.org/licenses/LICENSE-2.0
 *
 * This file is part of the Apache Pekko project, which was derived from Akka.
 */

/*
 * Copyright (C) 2009-2022 Lightbend Inc. <https://www.lightbend.com>
 */

package docs.http.javadsl.server;

import java.util.Optional;

import org.junit.Test;

import org.apache.pekko.http.javadsl.model.HttpRequest;
import org.apache.pekko.http.javadsl.model.headers.Host;
import org.apache.pekko.http.javadsl.server.Route;
import org.apache.pekko.http.javadsl.server.directives.SecurityDirectives.ProvidedCredentials;
import org.apache.pekko.http.javadsl.testkit.JUnitRouteTest;
import org.apache.pekko.http.scaladsl.model.headers.Authorization;

// #basic-authenticator-java
import static org.apache.pekko.http.javadsl.server.Directives.authenticateBasic;
import static org.apache.pekko.http.javadsl.server.Directives.complete;

// #basic-authenticator-java

public class HttpBasicAuthenticatorExample extends JUnitRouteTest {

  private final String hardcodedPassword = "correcthorsebatterystaple";

  private Optional<String> authenticate(Optional<ProvidedCredentials> creds) {
    // this is where your actual authentication logic would go
    return creds
        .filter(
            c -> c.verify(hardcodedPassword)) // Only allow users that provide the right password
        .map(c -> c.identifier()); // Provide the username down to the inner route
  }

  @Test
  public void testBasicAuthenticator() {
    // #basic-authenticator-java

    final Route route =
        authenticateBasic("My realm", this::authenticate, user -> complete("Hello " + user + "!"));

    // tests:
    final HttpRequest okRequest =
        HttpRequest.GET("http://pekko.apache.org/")
            .addHeader(Host.create("pekko.apache.org"))
            .addHeader(Authorization.basic("randal", "correcthorsebatterystaple"));
    testRoute(route).run(okRequest).assertEntity("Hello randal!");

    final HttpRequest badRequest =
        HttpRequest.GET("http://pekko.apache.org/")
            .addHeader(Host.create("pekko.apache.org"))
            .addHeader(Authorization.basic("randal", "123abc"));
    testRoute(route).run(badRequest).assertStatusCode(401);

    // #basic-authenticator-java
  }
}
