/*
 * Copyright 2004-present 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 clients 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.docs.servlet.authorization.authzauthorizationmanagerfactory;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.test.SpringTestContext;
import org.springframework.security.config.test.SpringTestContextExtension;
import org.springframework.security.core.Authentication;
import org.springframework.security.docs.servlet.authorization.authzauthorizationmanagerfactory.AuthorizationManagerFactoryConfiguration.Anonymous;
import org.springframework.security.docs.servlet.authorization.authzauthorizationmanagerfactory.AuthorizationManagerFactoryConfiguration.RememberMe;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication;
import static org.springframework.security.test.web.servlet.response.SecurityMockMvcResultMatchers.authenticated;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * Tests for {@link AuthorizationManagerFactoryConfiguration}.
 *
 * @author Steve Riesenberg
 */
@ExtendWith(SpringTestContextExtension.class)
public class AuthorizationManagerFactoryConfigurationTests {

	public final SpringTestContext spring = new SpringTestContext(this);

	@Autowired
	MockMvc mockMvc;

	@Test
	void getAnonymousWhenCustomAnonymousClassThenOk() throws Exception {
		this.spring.register(AuthorizationManagerFactoryConfiguration.class, SecurityConfiguration.class,
				TestController.class).autowire();
		Authentication authentication = new Anonymous("anonymous");
		// @formatter:off
		this.mockMvc.perform(get("/anonymous").with(authentication(authentication)))
			.andExpect(status().isOk())
			.andExpect(authenticated().withAuthentication(authentication));
		// @formatter:on
	}

	@Test
	void getAnonymousWhenAuthenticatedThenForbidden() throws Exception {
		this.spring.register(AuthorizationManagerFactoryConfiguration.class, SecurityConfiguration.class,
				TestController.class).autowire();
		Authentication authentication = new TestingAuthenticationToken("user", "", "role_user");
		// @formatter:off
		this.mockMvc.perform(get("/anonymous").with(authentication(authentication)))
			.andExpect(status().isForbidden())
			.andExpect(authenticated().withAuthentication(authentication));
		// @formatter:on
	}

	@Test
	void getRememberMeWhenCustomRememberMeClassThenOk() throws Exception {
		this.spring.register(AuthorizationManagerFactoryConfiguration.class, SecurityConfiguration.class,
				TestController.class).autowire();
		Authentication authentication = new RememberMe("rememberMe");
		// @formatter:off
		this.mockMvc.perform(get("/rememberMe").with(authentication(authentication)))
			.andExpect(status().isOk())
			.andExpect(authenticated().withAuthentication(authentication));
		// @formatter:on
	}

	@Test
	void getRememberMeWhenAuthenticatedThenForbidden() throws Exception {
		this.spring.register(AuthorizationManagerFactoryConfiguration.class, SecurityConfiguration.class,
				TestController.class).autowire();
		Authentication authentication = new TestingAuthenticationToken("user", "", "role_user");
		// @formatter:off
		this.mockMvc.perform(get("/rememberMe").with(authentication(authentication)))
			.andExpect(status().isForbidden())
			.andExpect(authenticated().withAuthentication(authentication));
		// @formatter:on
	}

	@Test
	void getUserWhenCustomUserRoleThenOk() throws Exception {
		this.spring.register(AuthorizationManagerFactoryConfiguration.class, SecurityConfiguration.class,
				TestController.class).autowire();
		Authentication authentication = new TestingAuthenticationToken("user", "", "role_user");
		// @formatter:off
		this.mockMvc.perform(get("/user").with(authentication(authentication)))
			.andExpect(status().isOk())
			.andExpect(authenticated().withAuthentication(authentication));
		// @formatter:on
	}

	@Test
	void getUserWhenCustomAdminRoleThenOk() throws Exception {
		this.spring.register(AuthorizationManagerFactoryConfiguration.class, SecurityConfiguration.class,
				TestController.class).autowire();
		Authentication authentication = new TestingAuthenticationToken("admin", "", "role_admin");
		// @formatter:off
		this.mockMvc.perform(get("/user").with(authentication(authentication)))
			.andExpect(status().isOk())
			.andExpect(authenticated().withAuthentication(authentication));
		// @formatter:on
	}

	@Test
	void getPreAuthorizeWhenCustomUserRoleThenOk() throws Exception {
		this.spring.register(AuthorizationManagerFactoryConfiguration.class, SecurityConfiguration.class,
				TestController.class).autowire();
		Authentication authentication = new TestingAuthenticationToken("user", "", "role_user");
		// @formatter:off
		this.mockMvc.perform(get("/preAuthorize").with(authentication(authentication)))
			.andExpect(status().isOk())
			.andExpect(authenticated().withAuthentication(authentication));
		// @formatter:on
	}

	@Test
	void getPreAuthorizeWhenCustomAdminRoleThenOk() throws Exception {
		this.spring.register(AuthorizationManagerFactoryConfiguration.class, SecurityConfiguration.class,
				TestController.class).autowire();
		Authentication authentication = new TestingAuthenticationToken("admin", "", "role_admin");
		// @formatter:off
		this.mockMvc.perform(get("/preAuthorize").with(authentication(authentication)))
			.andExpect(status().isOk())
			.andExpect(authenticated().withAuthentication(authentication));
		// @formatter:on
	}

	@Test
	void getPreAuthorizeWhenOtherRoleThenForbidden() throws Exception {
		this.spring.register(AuthorizationManagerFactoryConfiguration.class, SecurityConfiguration.class,
				TestController.class).autowire();
		Authentication authentication = new TestingAuthenticationToken("other", "", "role_other");
		// @formatter:off
		this.mockMvc.perform(get("/preAuthorize").with(authentication(authentication)))
			.andExpect(status().isForbidden())
			.andExpect(authenticated().withAuthentication(authentication));
		// @formatter:on
	}

	@EnableWebMvc
	@EnableWebSecurity
	@EnableMethodSecurity
	@Configuration
	static class SecurityConfiguration {

		@Bean
		SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
			// @formatter:off
			http
				.authorizeHttpRequests((authorize) -> authorize
					.requestMatchers("/anonymous").anonymous()
					.requestMatchers("/rememberMe").rememberMe()
					.requestMatchers("/user").hasRole("user")
					.requestMatchers("/preAuthorize").permitAll()
					.anyRequest().denyAll()
				);
			// @formatter:on
			return http.build();
		}

	}

	@RestController
	static class TestController {

		@GetMapping({ "/anonymous", "/rememberMe", "/user" })
		@ResponseStatus(HttpStatus.OK)
		void httpRequest() {
		}

		@GetMapping("/preAuthorize")
		@ResponseStatus(HttpStatus.OK)
		@PreAuthorize("hasRole('user')")
		void preAuthorize() {
		}

	}

}
