package io.digdag.server;

import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Inject;
import io.digdag.client.config.ConfigFactory;

import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;

@Provider
@PreMatching
public class AuthRequestFilter
    implements ContainerRequestFilter
{
    private Authenticator auth;
    private ConfigFactory cf;

    private final GenericJsonExceptionHandler<NotAuthorizedException> errorResultHandler;

    @Inject
    public AuthRequestFilter(Authenticator auth, ConfigFactory cf)
    {
        this.auth = auth;
        this.cf = cf;
        this.errorResultHandler = new GenericJsonExceptionHandler<NotAuthorizedException>(Response.Status.UNAUTHORIZED) { };
    }

    @Override
    public void filter(ContainerRequestContext requestContext)
    {
        String method = requestContext.getMethod();

        if (method.equals("OPTIONS") || method.equals("TRACE")) {
            return;
        }

        if (requestContext.getUriInfo().getPath().equals("/api/version")) {
            return;
        }

        Authenticator.Result result = auth.authenticate(requestContext);
        if (result.isAccepted()) {
            requestContext.setProperty("siteId", result.getSiteId());
            requestContext.setProperty("userInfo", result.getUserInfo().or(cf.create()));
            requestContext.setProperty("secrets", result.getSecrets().or(Suppliers.ofInstance(ImmutableMap.of())));
            requestContext.setProperty("admin", result.isAdmin());
        }
        else {
            requestContext.abortWith(errorResultHandler.toResponse(result.getErrorMessage()));
        }
    }
}

@@ -1454,305 +1454,138 @@
 y(%22s
-iteId%22, result.getSiteId());%0A            requestContext.setProperty(%22userInfo%22, result.getUserInfo().or(cf.create()));%0A            requestContext.setProperty(%22secrets%22, result.getSecrets().or(Suppliers.ofInstance(ImmutableMap.of())));%0A            requestContext.setProperty(%22admin%22, result.isAdmin
+ecrets%22, result.getSecrets().get());%0A            requestContext.setProperty(%22authenticatedUser%22, result.getAuthenticatedUser().get
 ());
@@ -1701,16 +1701,22 @@
 essage()
+.get()
 ));%0A    

Update RequestContext's attributes in server.AuthRequestFilter