/**
 * Copyright © 2012-2024 by Data Virtuality GmbH
 */
package org.teiid.query.processor.proc;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.teiid.core.TeiidComponentException;
import org.teiid.core.TeiidProcessingException;
import org.teiid.dqp.internal.process.AuthorizationValidator;
import org.teiid.query.metadata.QueryMetadataInterface;
import org.teiid.query.sql.lang.Command;
import org.teiid.query.util.CommandContext;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author Allan Vital
 * @date 2024.04.17
 */
public class AuthorizationUtils {
    
    private static final Cache<List<?>, Boolean> validated = Caffeine.newBuilder()
            .maximumSize(100L)
            .expireAfterAccess(10, TimeUnit.SECONDS)
            .build();
    
    public static void validateAuthorizationInProcCommand(Command command, QueryMetadataInterface metadata, ProcedurePlan procEnv) throws TeiidComponentException, TeiidProcessingException {
        if (command != null && metadata != null) {
            CommandContext context = procEnv.getContext();
            if (context != null) {
                boolean isAdmin = context.getDQPWorkContext() != null && context.getDQPWorkContext().isAdmin();
                if (procEnv.isValidateAccess() && !isAdmin && context.getAuthorizationValidator() != null && validated.getIfPresent(Arrays.asList(command, context)) == null) {
                    context.getAuthorizationValidator().validate(new String[]{command.toString()}, command, metadata,
                            context, AuthorizationValidator.CommandType.USER);
                    validated.put(Arrays.asList(command, context), true);
                }
            }
        }
    }

}