/*
 * JBoss, Home of Professional Open Source.
 * See the COPYRIGHT.txt file distributed with this work for information
 * regarding copyright ownership.  Some portions may be licensed
 * to Red Hat, Inc. under one or more contributor license agreements.
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301 USA.
 * Modified by
 * @author  Data Virtuality GmbH
 * @date    $Date$
 *  
 */
// https://issues.redhat.com/browse/TEIID-3663
package org.teiid.jdbc;

import static org.junit.jupiter.api.Assertions.fail;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.teiid.core.util.UnitTestUtil;
import org.teiid.runtime.DoNothingSecurityHelper;
import org.teiid.runtime.EmbeddedConfiguration;
import org.teiid.security.SecurityHelper;
import org.wildfly.security.auth.server.SecurityIdentity;

@SuppressWarnings("nls")
public class TestPassthroughAuthentication {

	static FakeServer server = new FakeServer(false);
	static DoNothingSecurityHelper securityHelper = new DoNothingSecurityHelper() {
		@Override
		public SecurityIdentity getSecurityIdentityInContext(String securityDomain) {
			SecurityIdentity identity = super.getSecurityIdentityInContext(securityDomain);
			return identity.isAnonymous() ? null : identity;
		}
	};
	
	@AfterAll public static void oneTimeTearDown() {
		server.stop();
	}
	
	@BeforeAll public static void oneTimeSetup() throws Exception {
    	server.setUseCallingThread(true);
    	server.start(new EmbeddedConfiguration() {
		@Override
    		public SecurityHelper getSecurityHelper() {
    			return securityHelper;
    		}  		
    	}, false);
	}
	
	@Test
	public void test() throws Exception {
		try {
			server.deployVDB("not_there", UnitTestUtil.getTestDataPath() + "/PartsSupplier.vdb");
			try {
				server.createConnection("jdbc:datavirtuality:not_there.1;passthroughAuthentication=true");
				fail();
			} catch (Exception e) {
			}
			
			SecurityIdentity si = securityHelper.getSecurityDomainContext("dv-security").createAdHocIdentity("test");
			si.runAs(() -> {
			try {
				server.createConnection("jdbc:datavirtuality:not_there.1;passthroughAuthentication=true");
			} catch (Exception e) {
				fail();
				}
			});
		} finally {
			server.undeployVDB("not_there");
		}
	}
}
