001/**
002 * Copyright (C) 2006-2020 Talend Inc. - www.talend.com
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.talend.sdk.component.server.front.security;
017
018import static javax.ws.rs.core.MediaType.APPLICATION_JSON_TYPE;
019import static org.talend.sdk.component.server.front.model.ErrorDictionary.UNAUTHORIZED;
020
021import java.io.IOException;
022
023import javax.enterprise.context.Dependent;
024import javax.enterprise.event.Event;
025import javax.inject.Inject;
026import javax.servlet.http.HttpServletRequest;
027import javax.ws.rs.container.ContainerRequestContext;
028import javax.ws.rs.container.ContainerRequestFilter;
029import javax.ws.rs.container.ResourceInfo;
030import javax.ws.rs.core.Context;
031import javax.ws.rs.core.Response;
032import javax.ws.rs.ext.Provider;
033
034import org.talend.sdk.component.server.front.model.error.ErrorPayload;
035import org.talend.sdk.component.server.service.security.event.OnCommand;
036
037@Provider
038@Dependent
039public class CommandSecurityProvider implements ContainerRequestFilter {
040
041    public static final String SKIP = CommandSecurityProvider.class.getName() + ".skip";
042
043    @Context
044    private HttpServletRequest request;
045
046    @Context
047    private ResourceInfo resourceInfo;
048
049    @Inject
050    private Event<OnCommand> onConnectionEvent;
051
052    @Override
053    public void filter(final ContainerRequestContext requestContext) throws IOException {
054        if (Boolean.TRUE.equals(request.getAttribute(SKIP))) {
055            return;
056        }
057
058        final OnCommand onCommand = new OnCommand(resourceInfo.getResourceClass(), resourceInfo.getResourceMethod());
059        onConnectionEvent.fire(onCommand);
060        if (!onCommand.isValid()) {
061            requestContext
062                    .abortWith(Response
063                            .status(Response.Status.UNAUTHORIZED)
064                            .entity(new ErrorPayload(UNAUTHORIZED, "Invalid command credentials"))
065                            .type(APPLICATION_JSON_TYPE)
066                            .build());
067        }
068    }
069}