/*
 * Copyright 2002-2020 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.security.authorization;

import java.util.function.Supplier;

import org.junit.Test;

import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Tests for {@link AuthenticatedAuthorizationManager}.
 *
 * @author Evgeniy Cheban
 */
public class AuthenticatedAuthorizationManagerTests {

	@Test
	public void authenticatedWhenUserNotAnonymousAndAuthenticatedThenGrantedDecision() {
		AuthenticatedAuthorizationManager<Object> manager = AuthenticatedAuthorizationManager.authenticated();
		Supplier<Authentication> authentication = () -> new TestingAuthenticationToken("user", "password", "ROLE_ADMIN",
				"ROLE_USER");
		Object object = new Object();

		assertThat(manager.check(authentication, object).isGranted()).isTrue();
	}

	@Test
	public void authenticatedWhenUserNullThenDeniedDecision() {
		AuthenticatedAuthorizationManager<Object> manager = AuthenticatedAuthorizationManager.authenticated();
		Supplier<Authentication> authentication = () -> null;
		Object object = new Object();

		assertThat(manager.check(authentication, object).isGranted()).isFalse();
	}

	@Test
	public void authenticatedWhenUserAnonymousThenDeniedDecision() {
		AuthenticatedAuthorizationManager<Object> manager = AuthenticatedAuthorizationManager.authenticated();
		Supplier<Authentication> authentication = () -> new AnonymousAuthenticationToken("key", "principal",
				AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS"));
		Object object = new Object();

		assertThat(manager.check(authentication, object).isGranted()).isFalse();
	}

	@Test
	public void authenticatedWhenUserNotAuthenticatedThenDeniedDecision() {
		AuthenticatedAuthorizationManager<Object> manager = AuthenticatedAuthorizationManager.authenticated();
		TestingAuthenticationToken authentication = new TestingAuthenticationToken("user", "password", "ROLE_ADMIN",
				"ROLE_USER");
		authentication.setAuthenticated(false);
		Object object = new Object();

		assertThat(manager.check(() -> authentication, object).isGranted()).isFalse();
	}

}
